@rebasepro/server 0.31.0-canary.g902a0ce → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
  2. package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
  3. package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
  4. package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
  5. package/dist/{access-CSfmyM87.js → access-BxkEYQh1.js} +6 -6
  6. package/dist/{access-CSfmyM87.js.map → access-BxkEYQh1.js.map} +1 -1
  7. package/dist/{access-CCsVee6z.js → access-D1CTJSLK.js} +3 -1
  8. package/dist/access-D1CTJSLK.js.map +1 -0
  9. package/dist/api/errors.d.ts +4 -0
  10. package/dist/api/rest/api-generator.d.ts +8 -0
  11. package/dist/{auth-Blo1R8rc.js → auth-Bfwjg4Bg.js} +37 -13
  12. package/dist/auth-Bfwjg4Bg.js.map +1 -0
  13. package/dist/auth-secrets-BZUH9916.js +60 -0
  14. package/dist/auth-secrets-BZUH9916.js.map +1 -0
  15. package/dist/backend/create-backend.d.ts +6 -0
  16. package/dist/backend/options.d.ts +10 -0
  17. package/dist/backend/services.d.ts +9 -0
  18. package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
  19. package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
  20. package/dist/boot/bundle.d.ts +11 -1
  21. package/dist/boot/env.d.ts +5 -0
  22. package/dist/boot/security-headers.d.ts +15 -5
  23. package/dist/boot/static-routing.d.ts +58 -0
  24. package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
  25. package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
  26. package/dist/{contract-routes-WwMWHWS9.js → contract-routes-CZTlAP7p.js} +3 -3
  27. package/dist/{contract-routes-WwMWHWS9.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
  28. package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
  29. package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
  30. package/dist/{cron-routes-Cqm5wQsK.js → cron-routes-Du03uJ7K.js} +5 -5
  31. package/dist/{cron-routes-Cqm5wQsK.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
  32. package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
  33. package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
  34. package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
  35. package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
  36. package/dist/dist-C1vNURUy.js +19354 -0
  37. package/dist/dist-C1vNURUy.js.map +1 -0
  38. package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
  39. package/dist/errors-NVbAQU25.js.map +1 -0
  40. package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
  41. package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
  42. package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
  43. package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
  44. package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
  45. package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
  46. package/dist/functions/index.d.ts +2 -0
  47. package/dist/functions/index.js +162 -1
  48. package/dist/functions/index.js.map +1 -1
  49. package/dist/functions/rate-limit.d.ts +71 -0
  50. package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
  51. package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
  52. package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
  53. package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
  54. package/dist/index.d.ts +6 -0
  55. package/dist/index.es.js +1242 -214
  56. package/dist/index.es.js.map +1 -1
  57. package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
  58. package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
  59. package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
  60. package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
  61. package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
  62. package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
  63. package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
  64. package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
  65. package/dist/{load-schema-CtyLeq-H.js → load-schema-B4Nv1mwq.js} +33 -40
  66. package/dist/load-schema-B4Nv1mwq.js.map +1 -0
  67. package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
  68. package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
  69. package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
  70. package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
  71. package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
  72. package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
  73. package/dist/{openapi-generator-mn6hsEmw.js → openapi-generator-CAhJiwBm.js} +4 -4
  74. package/dist/{openapi-generator-mn6hsEmw.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
  75. package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
  76. package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
  77. package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
  78. package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
  79. package/dist/push/push-options.d.ts +26 -0
  80. package/dist/push/push-routes.d.ts +30 -0
  81. package/dist/push/push-service.d.ts +13 -0
  82. package/dist/push/push-store.d.ts +45 -0
  83. package/dist/push/set-up.d.ts +25 -0
  84. package/dist/push/subscription-input.d.ts +26 -0
  85. package/dist/push/vapid-config.d.ts +35 -0
  86. package/dist/push/web-push-crypto.d.ts +44 -0
  87. package/dist/push/web-push-sender.d.ts +10 -0
  88. package/dist/{query-parser-CkKSbs1s.js → query-parser-Cd70kZO8.js} +6 -6
  89. package/dist/{query-parser-CkKSbs1s.js.map → query-parser-Cd70kZO8.js.map} +1 -1
  90. package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
  91. package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
  92. package/dist/{rls-simulator-routes-BxzeNXmI.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
  93. package/dist/{rls-simulator-routes-BxzeNXmI.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
  94. package/dist/{schema-editor-routes-mPCyks4X.js → schema-editor-routes-DEGwyQmx.js} +5 -5
  95. package/dist/{schema-editor-routes-mPCyks4X.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
  96. package/dist/{schema-tables-D4MEBZFi.js → schema-tables-DKFg6vMV.js} +4 -4
  97. package/dist/{schema-tables-D4MEBZFi.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
  98. package/dist/{schema-tables-routes-D3iLb5XU.js → schema-tables-routes-BfsNG4c4.js} +5 -5
  99. package/dist/{schema-tables-routes-D3iLb5XU.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
  100. package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
  101. package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
  102. package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
  103. package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
  104. package/dist/serve-spa.d.ts +12 -0
  105. package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
  106. package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
  107. package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
  108. package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
  109. package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
  110. package/dist/src-CNZB3fuE.js.map +1 -0
  111. package/dist/{table-source-editor-xvccIOH1.js → table-source-editor-D_zNDhEU.js} +3 -3
  112. package/dist/{table-source-editor-xvccIOH1.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
  113. package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
  114. package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
  115. package/package.json +5 -5
  116. package/dist/access-CCsVee6z.js.map +0 -1
  117. package/dist/auth-Blo1R8rc.js.map +0 -1
  118. package/dist/dist-CDIqWaSr.js +0 -19354
  119. package/dist/dist-CDIqWaSr.js.map +0 -1
  120. package/dist/errors-DpTMfX77.js.map +0 -1
  121. package/dist/load-schema-CtyLeq-H.js.map +0 -1
  122. package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
  123. package/dist/src-DLIb1O9l.js.map +0 -1
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { t as ApiError } from "./errors-DpTMfX77.js";
5
+ import { t as ApiError } from "./errors-NVbAQU25.js";
6
6
  import fs from "node:fs";
7
7
  //#region src/storage/types.ts
8
8
  /**
@@ -207,4 +207,4 @@ function validateUploadedFile(file, maxSize, allowedMimeTypes) {
207
207
  //#endregion
208
208
  export { fileWebStream as a, webStreamFrom as c, IMAGE_MIME_TYPES as d, bytesView as i, DEFAULT_MAX_FILE_SIZE as l, ObjectTooLargeError as n, meteredChunks as o, bufferWebStream as r, readStreamFully as s, validateUploadedFile as t, DOCUMENT_MIME_TYPES as u };
209
209
 
210
- //# sourceMappingURL=upload-validation-B-psYLaN.js.map
210
+ //# sourceMappingURL=upload-validation-BnIwo78L.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-validation-B-psYLaN.js","names":[],"sources":["../src/storage/types.ts","../src/storage/streams.ts","../src/storage/upload-validation.ts"],"sourcesContent":["/**\n * Storage configuration and types for Rebase backend\n */\n\nimport { StorageSource, UploadFileProps, UploadFileResult, DownloadConfig, DownloadMetadata, StorageListResult, StorageReference } from \"@rebasepro/types\";\nimport type { PutObjectStreamProps, PutObjectStreamResult, StoredObjectInfo, StoredObjectRange, StoredObjectStream } from \"@rebasepro/types\";\n\n/**\n * Local filesystem storage configuration\n */\nexport interface LocalStorageConfig {\n type: \"local\";\n /** Base directory for file storage (e.g., './uploads') */\n basePath: string;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n /** Base URL for generating download URLs (default: auto-detected from request) */\n baseUrl?: string;\n /**\n * Set when this local backend stands in for an object store the source\n * declared and nothing bound — `bucket(\"media\", { engine: \"s3\" })` with no\n * `S3_BUCKET__MEDIA` in a development process. Names the engine it stands\n * in for, so boot can say so and `rebase status` can show it. Never set in\n * production, where an unbound object store stays unbound.\n */\n standsInFor?: string;\n /**\n * Set when nothing chose this backend: no `STORAGE_TYPE` and no declared\n * engine, so local disk is only the default a source falls back to.\n * Production drops a local backend either way. This only decides how that\n * is reported: an implicit default being dropped means the project uses no\n * storage, which is not a misconfiguration.\n */\n implicit?: boolean;\n}\n\n/**\n * S3-compatible storage configuration (works with AWS S3 and MinIO)\n */\nexport interface S3StorageConfig {\n type: \"s3\";\n /** S3 bucket name */\n bucket: string;\n /** AWS region (e.g., 'us-east-1') */\n region?: string;\n /** Custom endpoint URL (required for MinIO, Cloudflare R2, Hetzner Object Storage) */\n endpoint?: string;\n /** AWS access key ID */\n accessKeyId: string;\n /** AWS secret access key */\n secretAccessKey: string;\n /** Use path-style URLs (required for MinIO) */\n forcePathStyle?: boolean;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n}\n\n/**\n * Google Cloud Storage configuration (works with GCS and Firebase Storage)\n */\nexport interface GCSStorageConfig {\n type: \"gcs\";\n /** GCS bucket name (e.g. \"my-project.appspot.com\" for Firebase Storage) */\n bucket: string;\n /** GCP project ID (optional, auto-detected from credentials) */\n projectId?: string;\n /** Path to service account JSON key file */\n keyFilename?: string;\n /** Service account credentials object (alternative to keyFilename) */\n credentials?: { client_email: string; private_key: string; project_id?: string };\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types */\n allowedMimeTypes?: string[];\n}\n\n/**\n * Storage configuration — local filesystem, S3-compatible, or Google Cloud Storage.\n *\n * **Built-in providers:**\n * - `local` — Zero-config filesystem storage. Great for dev and single-server deployments (Hetzner, bare metal).\n * - `s3` — Any S3-compatible provider. AWS S3, Cloudflare R2, MinIO, Hetzner Object Storage,\n * Backblaze B2, DigitalOcean Spaces, and even GCS (via its S3-compatible interoperability API).\n * - `gcs` — Native Google Cloud Storage / Firebase Storage via `@google-cloud/storage`.\n *\n * **Custom providers:**\n * For other cloud storage (Azure Blob, etc.), implement the `StorageController`\n * interface and pass the instance directly to the `storage` config.\n */\nexport type BackendStorageConfig = LocalStorageConfig | S3StorageConfig | GCSStorageConfig;\n\n/** What a storage request is trying to do to an object. */\nexport type {\n StorageOperation,\n StorageAuthorizeUser,\n StorageAuthorizeContext,\n StorageAuthorizeData,\n StorageAuthorize,\n PutObjectStreamProps,\n PutObjectStreamResult,\n StoredObjectInfo,\n StoredObjectRange,\n StoredObjectStream\n} from \"@rebasepro/types\";\n\n/**\n * How the server writes an object. See {@link StorageController.putObject}.\n */\nexport interface PutObjectOptions {\n /**\n * Hold this write to the controller's upload limits: `maxFileSize` and\n * `allowedMimeTypes`. Defaults to `true`.\n *\n * Those limits say what a user may upload. A write the server makes for\n * itself, such as a database backup, passes `false`. A dump is neither of\n * an allowed type nor, past a small database, under 50 MB. The upload\n * routes never pass it.\n */\n uploadLimits?: boolean;\n}\n\n/**\n * Storage controller interface for backend implementations\n */\nexport interface StorageController {\n /**\n * Upload an object.\n *\n * A write is held to the controller's upload limits — `maxFileSize` and\n * `allowedMimeTypes` — unless `options.uploadLimits` is `false`. Only the\n * server's own writes pass that; nothing a request sends reaches it.\n */\n putObject(props: UploadFileProps, options?: PutObjectOptions): Promise<UploadFileResult>;\n\n /**\n * Get a download URL (signed URL equivalent) for an object.\n *\n * For server-side code only: no route hands this URL to a client. A\n * client reads a private object through `/file/*` with the download\n * token `GET /metadata/*` mints. The built-in S3 and GCS controllers sign\n * it for an hour.\n */\n getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig>;\n\n /**\n * Describe an object — size, type, custom metadata — without producing a\n * URL for it, or `null` when there is no such object.\n *\n * `GET /metadata/*` wants only this: the client builds its own `/file/*`\n * URL and spends the download token the route mints. Asking\n * `getSignedUrl` for it made every metadata read sign a URL nobody used,\n * and on GCS signing is not free — without a key file the client asks the\n * IAM Credentials API to sign, which needs `iam.serviceAccounts.signBlob`\n * on the runtime account itself. Cloud Run does not grant that, so every\n * private object answered 500 there.\n *\n * A controller that does not implement this keeps the old behaviour: the\n * route falls back to `getSignedUrl` and reads its `metadata`.\n */\n getMetadata?(key: string, bucket?: string): Promise<DownloadMetadata | null>;\n\n /**\n * Get object as a File\n */\n getObject(key: string, bucket?: string): Promise<File | null>;\n\n /**\n * Describe an object for serving it — its size, stored type and version —\n * without reading its bytes, or `null` when there is no such object.\n *\n * Optional, together with {@link getObjectStream}. A controller that has\n * both is served streamed: `GET /file/*` answers a `304`, a `416`, a `HEAD`\n * and a cached image rendition from this alone, and otherwise reads only\n * the bytes it sends — the requested range, a chunk at a time. One without\n * them is served through {@link getObject}, which holds the whole object in\n * memory for every request, a `Range` request for one megabyte included.\n */\n statObject?(key: string, bucket?: string): Promise<StoredObjectInfo | null>;\n\n /**\n * Read an object, or one byte range of it, as a stream, or `null` when\n * there is no such object. See {@link statObject}.\n *\n * The stream holds a file or a connection until it is read to the end or\n * cancelled, so a caller that decides not to read it must cancel it.\n */\n getObjectStream?(key: string, options?: { bucket?: string; range?: StoredObjectRange }): Promise<StoredObjectStream | null>;\n\n /**\n * Write an object from a stream, a chunk at a time, for bytes the server\n * has not got all of yet: a request body on its way through.\n *\n * Past `maxBytes` this rejects with {@link ObjectTooLargeError}, and on that\n * or any other failure no object appears at the key. `maxFileSize` and\n * `allowedMimeTypes` do not apply; `maxBytes` is the caller's own limit.\n *\n * The stream can be read only once, so unlike {@link putObject} a failed\n * attempt cannot be retried here. A caller that must survive one keeps its\n * own copy.\n */\n putObjectStream?(props: PutObjectStreamProps): Promise<PutObjectStreamResult>;\n\n /**\n * Delete an object\n */\n deleteObject(key: string, bucket?: string): Promise<void>;\n\n /**\n * List objects in a prefix\n */\n listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult>;\n\n /**\n * Get the storage provider identifier.\n *\n * Built-in values are `'local'` and `'s3'`. Custom implementations\n * should return their own identifier (e.g. `'gcs'`, `'azure'`).\n */\n getType(): string;\n\n /**\n * The buckets this controller serves, if it knows.\n *\n * The `bucket` a request may name is not a free-text field: on S3 and GCS it\n * goes straight to the provider, so an unvalidated one addresses *any*\n * bucket the deployment's credentials can reach, and locally it names a\n * directory the framework would create on demand. Either way, a caller who\n * mistypes it gets \"file not found\" — the same answer as a missing object —\n * with nothing to say the bucket was the problem.\n *\n * So a controller that knows its buckets says so, and the routes refuse\n * anything else with `UNKNOWN_STORAGE_SOURCE` naming what is served. A\n * controller that does not implement this keeps the old behaviour and is\n * handed whatever the caller wrote — a custom implementation may address\n * buckets this framework has no way to enumerate.\n *\n * `\"default\"` is always among them: it is the logical name every route uses\n * when the caller names none, and each provider maps it to its own.\n */\n knownBuckets?(): string[];\n\n /**\n * Where this controller's default bucket physically is, as a string two\n * controllers return alike exactly when they store in the same place: a\n * resolved directory, an endpoint and bucket.\n *\n * Two sources declared over one bucket or directory are one store under\n * two names, and `rebase storage move --delete-source` between them found\n * every object \"already there\" — it is the same object — and deleted it\n * from both. A controller without this is found out by a probe object.\n */\n storageLocation?(): string;\n\n /**\n * The largest file this controller accepts, in bytes.\n *\n * Every door that takes a file reads it, so the number a client is told is\n * the number it is held to: the upload route checks it before anything is\n * stored, the resumable route checks it at creation — before the first\n * chunk rather than after the last — and advertises it as `Tus-Max-Size`,\n * and the server's upload body limit is the largest of them. A controller\n * that does not implement this is held to the deployment-wide limit alone.\n */\n maxFileSize?(): number;\n}\n\n/**\n * Default maximum file size (50MB)\n */\nexport const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Common image MIME types\n */\nexport const IMAGE_MIME_TYPES = [\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n \"image/svg+xml\",\n \"image/bmp\",\n \"image/tiff\"\n];\n\n/**\n * Common document MIME types\n */\nexport const DOCUMENT_MIME_TYPES = [\n \"application/pdf\",\n \"application/msword\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \"application/vnd.ms-excel\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n \"application/vnd.ms-powerpoint\",\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n \"text/plain\",\n \"text/csv\"\n];\n","/**\n * Moving object bytes without holding them.\n *\n * A stored object can be as large as the deployment's `maxFileSize` allows — a\n * video, a database dump — and the paths that used to read one whole (a\n * `File`, an `arrayBuffer()`, a `Buffer.concat`) held it three or four times\n * over per request. These helpers are what the streamed paths share instead.\n */\nimport fs from \"node:fs\";\n\n/** Anything that hands over bytes a chunk at a time: a Node readable, an SDK body. */\ntype ByteSource = AsyncIterable<Uint8Array>;\n\n/**\n * A byte source as a web stream that reads a chunk only when the consumer asks\n * for one, and releases the source when the consumer stops early.\n *\n * Pull-based with a zero high-water mark, so nothing is read ahead of the\n * reader: a slow client holds one chunk, not a queue of them. A source given\n * as a function is opened on the first read, which keeps a stream nobody reads\n * — a `HEAD`, a 304 decided late — from holding a file descriptor or a\n * connection open. Cancelling (a client that disconnects mid-download)\n * returns the iterator, which destroys a Node stream and so closes its file or\n * socket.\n */\nexport function webStreamFrom(source: ByteSource | (() => ByteSource)): ReadableStream<Uint8Array> {\n let iterator: AsyncIterator<Uint8Array> | undefined;\n const open = (): AsyncIterator<Uint8Array> => {\n iterator ??= (typeof source === \"function\" ? source() : source)[Symbol.asyncIterator]();\n return iterator;\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const next = await open().next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n } catch (err) {\n controller.error(err);\n }\n },\n async cancel() {\n // A source never opened has nothing to release — and opening it\n // now only to close it would be the cost this avoids.\n if (!iterator && typeof source === \"function\") return;\n try {\n await open().return?.();\n } catch {\n // Already failed or closed; either way it is released.\n }\n }\n }, { highWaterMark: 0 });\n}\n\n/** A streamed write ran past the limit its caller set. See {@link meteredChunks}. */\nexport class ObjectTooLargeError extends Error {\n constructor(readonly maxBytes: number) {\n super(`The object is larger than the ${maxBytes} bytes this write allows.`);\n this.name = \"ObjectTooLargeError\";\n }\n}\n\n/**\n * A stream's chunks, counted as they pass, stopping at `maxBytes`.\n *\n * Stopping cancels the stream, so a body being refused is not read to its end\n * first. The error surfaces at the consumer's next read, which is how a write in\n * progress learns to abandon itself rather than finishing an object it was\n * never allowed to keep.\n */\nexport function meteredChunks(\n stream: ReadableStream<Uint8Array>,\n maxBytes: number = Number.POSITIVE_INFINITY\n): { chunks: AsyncGenerator<Uint8Array>; size: () => number } {\n let size = 0;\n async function* read(): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n size += value.byteLength;\n if (size > maxBytes) throw new ObjectTooLargeError(maxBytes);\n yield value;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n return { chunks: read(), size: () => size };\n}\n\n/**\n * A file on disk, or an inclusive byte range of it, as a web stream. The file\n * is opened on the first read; see {@link webStreamFrom}.\n */\nexport function fileWebStream(filePath: string, range?: { start: number; end: number }): ReadableStream<Uint8Array> {\n return webStreamFrom(() => fs.createReadStream(filePath, range ? { start: range.start, end: range.end } : {}));\n}\n\n/** A buffer already in memory as a web stream of views onto it, never copies. */\nexport function bufferWebStream(bytes: Uint8Array, chunkSize = 64 * 1024): ReadableStream<Uint8Array> {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(offset + chunkSize, bytes.byteLength);\n controller.enqueue(bytes.subarray(offset, end));\n offset = end;\n }\n }, { highWaterMark: 0 });\n}\n\n/**\n * Read a stream into one buffer.\n *\n * For the one consumer that needs the whole object at once — an image decode.\n * With the size known the bytes are copied once, into a buffer of that size,\n * rather than collected and then concatenated (which holds them twice); a\n * stream that turns out longer or shorter than announced still comes back\n * whole and exact.\n */\nexport async function readStreamFully(stream: ReadableStream<Uint8Array>, expectedSize?: number): Promise<Buffer> {\n const reader = stream.getReader();\n const target = expectedSize !== undefined && expectedSize > 0 ? Buffer.allocUnsafe(expectedSize) : undefined;\n let offset = 0;\n let overflow: Uint8Array[] | undefined;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (target && !overflow && offset + value.byteLength <= target.byteLength) {\n target.set(value, offset);\n } else {\n overflow ??= target ? [target.subarray(0, offset)] : [];\n overflow.push(value);\n }\n offset += value.byteLength;\n }\n } finally {\n reader.releaseLock();\n }\n if (overflow) return Buffer.concat(overflow, offset);\n if (!target) return Buffer.alloc(0);\n return offset === target.byteLength ? target : target.subarray(0, offset);\n}\n\n/**\n * The bytes of a buffer as a `Uint8Array` the response APIs accept, without\n * copying them. `new Uint8Array(buffer)` copies; a view does not. Only a buffer\n * over shared memory — which nothing here produces — is copied.\n */\nexport function bytesView(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const backing = bytes.buffer;\n return backing instanceof ArrayBuffer\n ? new Uint8Array(backing, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n","/**\n * What every storage controller checks about a file before it stores it: the\n * source's own size cap and, when configured, its allowed content types.\n *\n * One function for the three controllers, which carried a copy each. Both\n * refusals are `ApiError`s, so they reach the caller as what they are. A plain\n * `Error` was a 500 \"Internal Server Error\" on `/upload` and a 502 on TUS —\n * after the client had sent every byte.\n */\n\nimport { ApiError } from \"../api/errors\";\n\nexport function validateUploadedFile(\n file: { size: number; type: string },\n maxSize: number,\n allowedMimeTypes: string[] | undefined\n): void {\n if (file.size > maxSize) {\n throw new ApiError(\n 413,\n \"PAYLOAD_TOO_LARGE\",\n `File size ${file.size} exceeds this storage source's maximum of ${maxSize} bytes.`,\n { size: file.size, maxFileSize: maxSize }\n );\n }\n\n if (allowedMimeTypes && allowedMimeTypes.length > 0 && !allowedMimeTypes.includes(file.type)) {\n // The code a property's `acceptedFiles` refusal answers with: to the\n // caller, \"this source does not take this type\" is the same mistake.\n throw ApiError.badRequest(\n `File type ${file.type || \"(none)\"} is not allowed on this storage source. ` +\n `Allowed types: ${allowedMimeTypes.join(\", \")}.`,\n \"STORAGE_FILE_TYPE_REFUSED\",\n { allowedMimeTypes, contentType: file.type }\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAqRA,IAAa,wBAAwB,KAAK,OAAO;;;;AAKjD,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;AAKA,IAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;;;;;;ACxRA,SAAgB,cAAc,QAAqE;CAC/F,IAAI;CACJ,MAAM,aAAwC;EAC1C,cAAc,OAAO,WAAW,aAAa,OAAO,IAAI,OAAA,CAAQ,OAAO,cAAc,CAAC;EACtF,OAAO;CACX;CACA,OAAO,IAAI,eAA2B;EAClC,MAAM,KAAK,YAAY;GACnB,IAAI;IACA,MAAM,OAAO,MAAM,KAAK,CAAC,CAAC,KAAK;IAC/B,IAAI,KAAK,MAAM,WAAW,MAAM;SAC3B,WAAW,QAAQ,KAAK,KAAK;GACtC,SAAS,KAAK;IACV,WAAW,MAAM,GAAG;GACxB;EACJ;EACA,MAAM,SAAS;GAGX,IAAI,CAAC,YAAY,OAAO,WAAW,YAAY;GAC/C,IAAI;IACA,MAAM,KAAK,CAAC,CAAC,SAAS;GAC1B,QAAQ,CAER;EACJ;CACJ,GAAG,EAAE,eAAe,EAAE,CAAC;AAC3B;;AAGA,IAAa,sBAAb,cAAyC,MAAM;CACtB;CAArB,YAAY,UAA2B;EACnC,MAAM,iCAAiC,SAAS,0BAA0B;EADzD,KAAA,WAAA;EAEjB,KAAK,OAAO;CAChB;AACJ;;;;;;;;;AAU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cAAc,OAAO,YAC3D,OAAO,IAAI,OAAO,MAAM;QACrB;IACH,aAAa,SAAS,CAAC,OAAO,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IACtD,SAAS,KAAK,KAAK;GACvB;GACA,UAAU,MAAM;EACpB;CACJ,UAAU;EACN,OAAO,YAAY;CACvB;CACA,IAAI,UAAU,OAAO,OAAO,OAAO,UAAU,MAAM;CACnD,IAAI,CAAC,QAAQ,OAAO,OAAO,MAAM,CAAC;CAClC,OAAO,WAAW,OAAO,aAAa,SAAS,OAAO,SAAS,GAAG,MAAM;AAC5E;;;;;;AAOA,SAAgB,UAAU,OAA4C;CAClE,MAAM,UAAU,MAAM;CACtB,OAAO,mBAAmB,cACpB,IAAI,WAAW,SAAS,MAAM,YAAY,MAAM,UAAU,IAC1D,IAAI,WAAW,KAAK;AAC9B;;;;;;;;;;;;ACpJA,SAAgB,qBACZ,MACA,SACA,kBACI;CACJ,IAAI,KAAK,OAAO,SACZ,MAAM,IAAI,SACN,KACA,qBACA,aAAa,KAAK,KAAK,4CAA4C,QAAQ,UAC3E;EAAE,MAAM,KAAK;EAAM,aAAa;CAAQ,CAC5C;CAGJ,IAAI,oBAAoB,iBAAiB,SAAS,KAAK,CAAC,iBAAiB,SAAS,KAAK,IAAI,GAGvF,MAAM,SAAS,WACX,aAAa,KAAK,QAAQ,SAAS,yDACjB,iBAAiB,KAAK,IAAI,EAAE,IAC9C,6BACA;EAAE;EAAkB,aAAa,KAAK;CAAK,CAC/C;AAER"}
1
+ {"version":3,"file":"upload-validation-BnIwo78L.js","names":[],"sources":["../src/storage/types.ts","../src/storage/streams.ts","../src/storage/upload-validation.ts"],"sourcesContent":["/**\n * Storage configuration and types for Rebase backend\n */\n\nimport { StorageSource, UploadFileProps, UploadFileResult, DownloadConfig, DownloadMetadata, StorageListResult, StorageReference } from \"@rebasepro/types\";\nimport type { PutObjectStreamProps, PutObjectStreamResult, StoredObjectInfo, StoredObjectRange, StoredObjectStream } from \"@rebasepro/types\";\n\n/**\n * Local filesystem storage configuration\n */\nexport interface LocalStorageConfig {\n type: \"local\";\n /** Base directory for file storage (e.g., './uploads') */\n basePath: string;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n /** Base URL for generating download URLs (default: auto-detected from request) */\n baseUrl?: string;\n /**\n * Set when this local backend stands in for an object store the source\n * declared and nothing bound — `bucket(\"media\", { engine: \"s3\" })` with no\n * `S3_BUCKET__MEDIA` in a development process. Names the engine it stands\n * in for, so boot can say so and `rebase status` can show it. Never set in\n * production, where an unbound object store stays unbound.\n */\n standsInFor?: string;\n /**\n * Set when nothing chose this backend: no `STORAGE_TYPE` and no declared\n * engine, so local disk is only the default a source falls back to.\n * Production drops a local backend either way. This only decides how that\n * is reported: an implicit default being dropped means the project uses no\n * storage, which is not a misconfiguration.\n */\n implicit?: boolean;\n}\n\n/**\n * S3-compatible storage configuration (works with AWS S3 and MinIO)\n */\nexport interface S3StorageConfig {\n type: \"s3\";\n /** S3 bucket name */\n bucket: string;\n /** AWS region (e.g., 'us-east-1') */\n region?: string;\n /** Custom endpoint URL (required for MinIO, Cloudflare R2, Hetzner Object Storage) */\n endpoint?: string;\n /** AWS access key ID */\n accessKeyId: string;\n /** AWS secret access key */\n secretAccessKey: string;\n /** Use path-style URLs (required for MinIO) */\n forcePathStyle?: boolean;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n}\n\n/**\n * Google Cloud Storage configuration (works with GCS and Firebase Storage)\n */\nexport interface GCSStorageConfig {\n type: \"gcs\";\n /** GCS bucket name (e.g. \"my-project.appspot.com\" for Firebase Storage) */\n bucket: string;\n /** GCP project ID (optional, auto-detected from credentials) */\n projectId?: string;\n /** Path to service account JSON key file */\n keyFilename?: string;\n /** Service account credentials object (alternative to keyFilename) */\n credentials?: { client_email: string; private_key: string; project_id?: string };\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types */\n allowedMimeTypes?: string[];\n}\n\n/**\n * Storage configuration — local filesystem, S3-compatible, or Google Cloud Storage.\n *\n * **Built-in providers:**\n * - `local` — Zero-config filesystem storage. Great for dev and single-server deployments (Hetzner, bare metal).\n * - `s3` — Any S3-compatible provider. AWS S3, Cloudflare R2, MinIO, Hetzner Object Storage,\n * Backblaze B2, DigitalOcean Spaces, and even GCS (via its S3-compatible interoperability API).\n * - `gcs` — Native Google Cloud Storage / Firebase Storage via `@google-cloud/storage`.\n *\n * **Custom providers:**\n * For other cloud storage (Azure Blob, etc.), implement the `StorageController`\n * interface and pass the instance directly to the `storage` config.\n */\nexport type BackendStorageConfig = LocalStorageConfig | S3StorageConfig | GCSStorageConfig;\n\n/** What a storage request is trying to do to an object. */\nexport type {\n StorageOperation,\n StorageAuthorizeUser,\n StorageAuthorizeContext,\n StorageAuthorizeData,\n StorageAuthorize,\n PutObjectStreamProps,\n PutObjectStreamResult,\n StoredObjectInfo,\n StoredObjectRange,\n StoredObjectStream\n} from \"@rebasepro/types\";\n\n/**\n * How the server writes an object. See {@link StorageController.putObject}.\n */\nexport interface PutObjectOptions {\n /**\n * Hold this write to the controller's upload limits: `maxFileSize` and\n * `allowedMimeTypes`. Defaults to `true`.\n *\n * Those limits say what a user may upload. A write the server makes for\n * itself, such as a database backup, passes `false`. A dump is neither of\n * an allowed type nor, past a small database, under 50 MB. The upload\n * routes never pass it.\n */\n uploadLimits?: boolean;\n}\n\n/**\n * Storage controller interface for backend implementations\n */\nexport interface StorageController {\n /**\n * Upload an object.\n *\n * A write is held to the controller's upload limits — `maxFileSize` and\n * `allowedMimeTypes` — unless `options.uploadLimits` is `false`. Only the\n * server's own writes pass that; nothing a request sends reaches it.\n */\n putObject(props: UploadFileProps, options?: PutObjectOptions): Promise<UploadFileResult>;\n\n /**\n * Get a download URL (signed URL equivalent) for an object.\n *\n * For server-side code only: no route hands this URL to a client. A\n * client reads a private object through `/file/*` with the download\n * token `GET /metadata/*` mints. The built-in S3 and GCS controllers sign\n * it for an hour.\n */\n getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig>;\n\n /**\n * Describe an object — size, type, custom metadata — without producing a\n * URL for it, or `null` when there is no such object.\n *\n * `GET /metadata/*` wants only this: the client builds its own `/file/*`\n * URL and spends the download token the route mints. Asking\n * `getSignedUrl` for it made every metadata read sign a URL nobody used,\n * and on GCS signing is not free — without a key file the client asks the\n * IAM Credentials API to sign, which needs `iam.serviceAccounts.signBlob`\n * on the runtime account itself. Cloud Run does not grant that, so every\n * private object answered 500 there.\n *\n * A controller that does not implement this keeps the old behaviour: the\n * route falls back to `getSignedUrl` and reads its `metadata`.\n */\n getMetadata?(key: string, bucket?: string): Promise<DownloadMetadata | null>;\n\n /**\n * Get object as a File\n */\n getObject(key: string, bucket?: string): Promise<File | null>;\n\n /**\n * Describe an object for serving it — its size, stored type and version —\n * without reading its bytes, or `null` when there is no such object.\n *\n * Optional, together with {@link getObjectStream}. A controller that has\n * both is served streamed: `GET /file/*` answers a `304`, a `416`, a `HEAD`\n * and a cached image rendition from this alone, and otherwise reads only\n * the bytes it sends — the requested range, a chunk at a time. One without\n * them is served through {@link getObject}, which holds the whole object in\n * memory for every request, a `Range` request for one megabyte included.\n */\n statObject?(key: string, bucket?: string): Promise<StoredObjectInfo | null>;\n\n /**\n * Read an object, or one byte range of it, as a stream, or `null` when\n * there is no such object. See {@link statObject}.\n *\n * The stream holds a file or a connection until it is read to the end or\n * cancelled, so a caller that decides not to read it must cancel it.\n */\n getObjectStream?(key: string, options?: { bucket?: string; range?: StoredObjectRange }): Promise<StoredObjectStream | null>;\n\n /**\n * Write an object from a stream, a chunk at a time, for bytes the server\n * has not got all of yet: a request body on its way through.\n *\n * Past `maxBytes` this rejects with {@link ObjectTooLargeError}, and on that\n * or any other failure no object appears at the key. `maxFileSize` and\n * `allowedMimeTypes` do not apply; `maxBytes` is the caller's own limit.\n *\n * The stream can be read only once, so unlike {@link putObject} a failed\n * attempt cannot be retried here. A caller that must survive one keeps its\n * own copy.\n */\n putObjectStream?(props: PutObjectStreamProps): Promise<PutObjectStreamResult>;\n\n /**\n * Delete an object\n */\n deleteObject(key: string, bucket?: string): Promise<void>;\n\n /**\n * List objects in a prefix\n */\n listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult>;\n\n /**\n * Get the storage provider identifier.\n *\n * Built-in values are `'local'` and `'s3'`. Custom implementations\n * should return their own identifier (e.g. `'gcs'`, `'azure'`).\n */\n getType(): string;\n\n /**\n * The buckets this controller serves, if it knows.\n *\n * The `bucket` a request may name is not a free-text field: on S3 and GCS it\n * goes straight to the provider, so an unvalidated one addresses *any*\n * bucket the deployment's credentials can reach, and locally it names a\n * directory the framework would create on demand. Either way, a caller who\n * mistypes it gets \"file not found\" — the same answer as a missing object —\n * with nothing to say the bucket was the problem.\n *\n * So a controller that knows its buckets says so, and the routes refuse\n * anything else with `UNKNOWN_STORAGE_SOURCE` naming what is served. A\n * controller that does not implement this keeps the old behaviour and is\n * handed whatever the caller wrote — a custom implementation may address\n * buckets this framework has no way to enumerate.\n *\n * `\"default\"` is always among them: it is the logical name every route uses\n * when the caller names none, and each provider maps it to its own.\n */\n knownBuckets?(): string[];\n\n /**\n * Where this controller's default bucket physically is, as a string two\n * controllers return alike exactly when they store in the same place: a\n * resolved directory, an endpoint and bucket.\n *\n * Two sources declared over one bucket or directory are one store under\n * two names, and `rebase storage move --delete-source` between them found\n * every object \"already there\" — it is the same object — and deleted it\n * from both. A controller without this is found out by a probe object.\n */\n storageLocation?(): string;\n\n /**\n * The largest file this controller accepts, in bytes.\n *\n * Every door that takes a file reads it, so the number a client is told is\n * the number it is held to: the upload route checks it before anything is\n * stored, the resumable route checks it at creation — before the first\n * chunk rather than after the last — and advertises it as `Tus-Max-Size`,\n * and the server's upload body limit is the largest of them. A controller\n * that does not implement this is held to the deployment-wide limit alone.\n */\n maxFileSize?(): number;\n}\n\n/**\n * Default maximum file size (50MB)\n */\nexport const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Common image MIME types\n */\nexport const IMAGE_MIME_TYPES = [\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n \"image/svg+xml\",\n \"image/bmp\",\n \"image/tiff\"\n];\n\n/**\n * Common document MIME types\n */\nexport const DOCUMENT_MIME_TYPES = [\n \"application/pdf\",\n \"application/msword\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \"application/vnd.ms-excel\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n \"application/vnd.ms-powerpoint\",\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n \"text/plain\",\n \"text/csv\"\n];\n","/**\n * Moving object bytes without holding them.\n *\n * A stored object can be as large as the deployment's `maxFileSize` allows — a\n * video, a database dump — and the paths that used to read one whole (a\n * `File`, an `arrayBuffer()`, a `Buffer.concat`) held it three or four times\n * over per request. These helpers are what the streamed paths share instead.\n */\nimport fs from \"node:fs\";\n\n/** Anything that hands over bytes a chunk at a time: a Node readable, an SDK body. */\ntype ByteSource = AsyncIterable<Uint8Array>;\n\n/**\n * A byte source as a web stream that reads a chunk only when the consumer asks\n * for one, and releases the source when the consumer stops early.\n *\n * Pull-based with a zero high-water mark, so nothing is read ahead of the\n * reader: a slow client holds one chunk, not a queue of them. A source given\n * as a function is opened on the first read, which keeps a stream nobody reads\n * — a `HEAD`, a 304 decided late — from holding a file descriptor or a\n * connection open. Cancelling (a client that disconnects mid-download)\n * returns the iterator, which destroys a Node stream and so closes its file or\n * socket.\n */\nexport function webStreamFrom(source: ByteSource | (() => ByteSource)): ReadableStream<Uint8Array> {\n let iterator: AsyncIterator<Uint8Array> | undefined;\n const open = (): AsyncIterator<Uint8Array> => {\n iterator ??= (typeof source === \"function\" ? source() : source)[Symbol.asyncIterator]();\n return iterator;\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const next = await open().next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n } catch (err) {\n controller.error(err);\n }\n },\n async cancel() {\n // A source never opened has nothing to release — and opening it\n // now only to close it would be the cost this avoids.\n if (!iterator && typeof source === \"function\") return;\n try {\n await open().return?.();\n } catch {\n // Already failed or closed; either way it is released.\n }\n }\n }, { highWaterMark: 0 });\n}\n\n/** A streamed write ran past the limit its caller set. See {@link meteredChunks}. */\nexport class ObjectTooLargeError extends Error {\n constructor(readonly maxBytes: number) {\n super(`The object is larger than the ${maxBytes} bytes this write allows.`);\n this.name = \"ObjectTooLargeError\";\n }\n}\n\n/**\n * A stream's chunks, counted as they pass, stopping at `maxBytes`.\n *\n * Stopping cancels the stream, so a body being refused is not read to its end\n * first. The error surfaces at the consumer's next read, which is how a write in\n * progress learns to abandon itself rather than finishing an object it was\n * never allowed to keep.\n */\nexport function meteredChunks(\n stream: ReadableStream<Uint8Array>,\n maxBytes: number = Number.POSITIVE_INFINITY\n): { chunks: AsyncGenerator<Uint8Array>; size: () => number } {\n let size = 0;\n async function* read(): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n size += value.byteLength;\n if (size > maxBytes) throw new ObjectTooLargeError(maxBytes);\n yield value;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n return { chunks: read(), size: () => size };\n}\n\n/**\n * A file on disk, or an inclusive byte range of it, as a web stream. The file\n * is opened on the first read; see {@link webStreamFrom}.\n */\nexport function fileWebStream(filePath: string, range?: { start: number; end: number }): ReadableStream<Uint8Array> {\n return webStreamFrom(() => fs.createReadStream(filePath, range ? { start: range.start, end: range.end } : {}));\n}\n\n/** A buffer already in memory as a web stream of views onto it, never copies. */\nexport function bufferWebStream(bytes: Uint8Array, chunkSize = 64 * 1024): ReadableStream<Uint8Array> {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(offset + chunkSize, bytes.byteLength);\n controller.enqueue(bytes.subarray(offset, end));\n offset = end;\n }\n }, { highWaterMark: 0 });\n}\n\n/**\n * Read a stream into one buffer.\n *\n * For the one consumer that needs the whole object at once — an image decode.\n * With the size known the bytes are copied once, into a buffer of that size,\n * rather than collected and then concatenated (which holds them twice); a\n * stream that turns out longer or shorter than announced still comes back\n * whole and exact.\n */\nexport async function readStreamFully(stream: ReadableStream<Uint8Array>, expectedSize?: number): Promise<Buffer> {\n const reader = stream.getReader();\n const target = expectedSize !== undefined && expectedSize > 0 ? Buffer.allocUnsafe(expectedSize) : undefined;\n let offset = 0;\n let overflow: Uint8Array[] | undefined;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (target && !overflow && offset + value.byteLength <= target.byteLength) {\n target.set(value, offset);\n } else {\n overflow ??= target ? [target.subarray(0, offset)] : [];\n overflow.push(value);\n }\n offset += value.byteLength;\n }\n } finally {\n reader.releaseLock();\n }\n if (overflow) return Buffer.concat(overflow, offset);\n if (!target) return Buffer.alloc(0);\n return offset === target.byteLength ? target : target.subarray(0, offset);\n}\n\n/**\n * The bytes of a buffer as a `Uint8Array` the response APIs accept, without\n * copying them. `new Uint8Array(buffer)` copies; a view does not. Only a buffer\n * over shared memory — which nothing here produces — is copied.\n */\nexport function bytesView(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const backing = bytes.buffer;\n return backing instanceof ArrayBuffer\n ? new Uint8Array(backing, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n","/**\n * What every storage controller checks about a file before it stores it: the\n * source's own size cap and, when configured, its allowed content types.\n *\n * One function for the three controllers, which carried a copy each. Both\n * refusals are `ApiError`s, so they reach the caller as what they are. A plain\n * `Error` was a 500 \"Internal Server Error\" on `/upload` and a 502 on TUS —\n * after the client had sent every byte.\n */\n\nimport { ApiError } from \"../api/errors\";\n\nexport function validateUploadedFile(\n file: { size: number; type: string },\n maxSize: number,\n allowedMimeTypes: string[] | undefined\n): void {\n if (file.size > maxSize) {\n throw new ApiError(\n 413,\n \"PAYLOAD_TOO_LARGE\",\n `File size ${file.size} exceeds this storage source's maximum of ${maxSize} bytes.`,\n { size: file.size, maxFileSize: maxSize }\n );\n }\n\n if (allowedMimeTypes && allowedMimeTypes.length > 0 && !allowedMimeTypes.includes(file.type)) {\n // The code a property's `acceptedFiles` refusal answers with: to the\n // caller, \"this source does not take this type\" is the same mistake.\n throw ApiError.badRequest(\n `File type ${file.type || \"(none)\"} is not allowed on this storage source. ` +\n `Allowed types: ${allowedMimeTypes.join(\", \")}.`,\n \"STORAGE_FILE_TYPE_REFUSED\",\n { allowedMimeTypes, contentType: file.type }\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAqRA,IAAa,wBAAwB,KAAK,OAAO;;;;AAKjD,IAAa,mBAAmB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;AAKA,IAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;;;;;;ACxRA,SAAgB,cAAc,QAAqE;CAC/F,IAAI;CACJ,MAAM,aAAwC;EAC1C,cAAc,OAAO,WAAW,aAAa,OAAO,IAAI,OAAA,CAAQ,OAAO,cAAc,CAAC;EACtF,OAAO;CACX;CACA,OAAO,IAAI,eAA2B;EAClC,MAAM,KAAK,YAAY;GACnB,IAAI;IACA,MAAM,OAAO,MAAM,KAAK,CAAC,CAAC,KAAK;IAC/B,IAAI,KAAK,MAAM,WAAW,MAAM;SAC3B,WAAW,QAAQ,KAAK,KAAK;GACtC,SAAS,KAAK;IACV,WAAW,MAAM,GAAG;GACxB;EACJ;EACA,MAAM,SAAS;GAGX,IAAI,CAAC,YAAY,OAAO,WAAW,YAAY;GAC/C,IAAI;IACA,MAAM,KAAK,CAAC,CAAC,SAAS;GAC1B,QAAQ,CAER;EACJ;CACJ,GAAG,EAAE,eA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": "Database-Agnostic Backend Core for Rebase",
5
5
  "keywords": [
6
6
  "rebase",
@@ -60,10 +60,10 @@
60
60
  "jsonwebtoken": "^9.0.3",
61
61
  "ws": "^8.21.1",
62
62
  "zod": "^4.4.3",
63
- "@rebasepro/client": "0.31.0-canary.g902a0ce",
64
- "@rebasepro/common": "0.31.0-canary.g902a0ce",
65
- "@rebasepro/types": "0.31.0-canary.g902a0ce",
66
- "@rebasepro/utils": "0.31.0-canary.g902a0ce"
63
+ "@rebasepro/common": "0.32.0",
64
+ "@rebasepro/types": "0.32.0",
65
+ "@rebasepro/utils": "0.32.0",
66
+ "@rebasepro/client": "0.32.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@jest/globals": "^30.4.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"access-CCsVee6z.js","names":[],"sources":["../../common/src/collections/field-access.ts","../../common/src/table/access.ts"],"sourcesContent":["\n/**\n * Field-level access control: the one predicate every enforcement point reads.\n *\n * A table's `rls` decides which *rows* a caller reaches; a column's `access`\n * decides which *fields* of a reached row they see and may set. The two are\n * independent — a field rule never widens row access, and a row a caller\n * cannot read has no fields to talk about. `.private()` is `access: { read: [],\n * write: [] }` (`table/access.ts` expands it); the panel reads its property\n * view model through the same predicates.\n *\n * @module\n */\n\n/**\n * The caller a field rule is judged against: whatever the call context carries\n * as the user's application roles.\n *\n * `undefined` is the trusted server plane — an in-process `rebase.data` call\n * with no request behind it, the auth adapter writing a password hash, a\n * migration. Every API boundary has a viewer: an unauthenticated REST request is\n * scoped as `{ uid: ANONYMOUS_USER_ID, roles: [\"anon\"] }` before it reaches a\n * driver, so \"no viewer\" cannot be reached from outside.\n */\nexport interface FieldViewer {\n roles?: readonly string[];\n}\n\n/**\n * The role that satisfies any non-empty list.\n *\n * The same arm every baseline policy carries: `security_rules` injects\n * `rolesOverlap(['admin'])` into the default read and write policies, and\n * `rebase.dataAsAdmin` is scoped with `{ uid: \"service\", roles: [\"admin\"] }`.\n * Without this an author could declare `access: { read: [\"hr\"] }` and lock the\n * administrator out of a column of their own database — and lock the Studio out\n * of rendering it.\n */\nexport const ADMIN_ROLE = \"admin\";\n\n/**\n * Does a caller holding `roles` satisfy `allowed`?\n *\n * Three cases, and the middle one is the one worth stating out loud:\n *\n * - `allowed` omitted — the field carries no rule of its own, so the row's\n * policies have already answered. True.\n * - `allowed` empty — nobody, at any privilege, through any API. Not the admin,\n * not the service key, not the trusted plane reading on a caller's behalf.\n * This is what `excludeFromApi` has always meant on the read side, and\n * collapsing the two spellings means the empty list has to keep meaning it.\n * - `allowed` non-empty — one of the named roles, or `admin`, or no viewer at\n * all (the trusted server plane, which is not an API caller).\n */\nfunction satisfies(allowed: readonly string[] | undefined, viewer: FieldViewer | undefined): boolean {\n if (allowed === undefined) return true;\n if (allowed.length === 0) return false;\n if (!viewer) return true;\n const roles = viewer.roles;\n if (!roles || roles.length === 0) return false;\n return roles.includes(ADMIN_ROLE) || allowed.some(role => roles.includes(role));\n}\n\n/**\n * May this caller receive a value whose read rule is `access`? The same\n * predicate the panel's `canReadField` applies to a property, and the one a\n * column's or a relation's `access` in a table descriptor is judged by.\n */\nexport function canReadWithAccess(access: { read?: readonly string[] } | undefined, viewer: FieldViewer | undefined): boolean {\n return satisfies(access?.read, viewer);\n}\n\n/**\n * May this caller set a value whose write rule is `access`? The write half of\n * {@link canReadWithAccess}.\n */\nexport function canWriteWithAccess(access: { write?: readonly string[] } | undefined, viewer: FieldViewer | undefined): boolean {\n return satisfies(access?.write, viewer);\n}\n","import type { ColumnAccess, ColumnDescriptor, RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\n\nimport { canReadWithAccess, canWriteWithAccess, type FieldViewer } from \"../collections/field-access\";\n\n/**\n * Column- and relation-level access over a {@link TableDescriptor}: the same\n * rules as `collections/field-access.ts`, read from the descriptor instead of\n * from `property.access` / `excludeFromApi`.\n *\n * - `.private()` (`private: true`) is `{ read: [], write: [] }`: nobody, through\n * any API — exactly what `excludeFromApi` expanded to.\n * - A list that is absent leaves that direction to the row's policies.\n * - An empty list closes it to every caller, the admin and the trusted plane\n * included.\n * - A non-empty list admits its roles, `admin`, and no viewer at all (the\n * trusted server plane).\n *\n * The predicate itself is common's `canReadWithAccess`, so the two models\n * cannot answer differently while both exist.\n *\n * @module\n */\n\n/** What carries access rules: a column, or a relation (which has no `readOnly`). */\ntype AccessTarget = Pick<ColumnDescriptor, \"private\" | \"access\"> & { readOnly?: true };\n\n/** The rule `.private()` expands to. Frozen: it is shared by every caller. */\nconst PRIVATE_ACCESS: ColumnAccess = Object.freeze({ read: Object.freeze([]), write: Object.freeze([]) });\n\n/**\n * What a column's or relation's access rules actually are, with `private`\n * expanded, or `undefined` when it constrains nothing.\n *\n * Replaces `effectiveAccess(property)`.\n *\n * @group Table\n */\nexport function columnAccess(target: Pick<ColumnDescriptor, \"private\" | \"access\">): ColumnAccess | undefined {\n if (target.private) return PRIVATE_ACCESS;\n const access = target.access;\n if (!access || (access.read === undefined && access.write === undefined)) return undefined;\n return access;\n}\n\n/**\n * May this caller receive the column's (or relation's) value?\n *\n * Replaces `canReadField(property, viewer)`.\n *\n * @group Table\n */\nexport function canReadColumn(target: Pick<ColumnDescriptor, \"private\" | \"access\">, viewer: FieldViewer | undefined): boolean {\n return canReadWithAccess(columnAccess(target), viewer);\n}\n\n/**\n * May this caller set the column's (or relation's) value?\n *\n * Replaces `canWriteField(property, viewer)`. The write list is judged by the\n * same predicate as a read list. A `readOnly` column (`.readOnly()`, a\n * generated column — what the lift makes of `access.write: []`) is written by\n * nobody through any API: the database or the server's own stamps fill it.\n *\n * @group Table\n */\nexport function canWriteColumn(target: AccessTarget, viewer: FieldViewer | undefined): boolean {\n if (\"readOnly\" in target && target.readOnly) return false;\n const access = columnAccess(target);\n return canWriteWithAccess(access, viewer);\n}\n\n/**\n * The column a `belongsTo` is bound to on its own table — the declared (or\n * derived) column its `localKey` names — or `undefined` for any other kind, or\n * a link whose key the table does not describe.\n *\n * The two are one fact under two names: `{ reviewer: 7 }` sets the column\n * `{ reviewerId: 7 }` sets, and `?include=reviewer` hands over the value the\n * column holds. So every rule of one is a rule of the other — see\n * {@link canReadRelation} and {@link canWriteRelation}.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server's OpenAPI generator; not part of the public API.\n */\nexport function boundKeyColumn(table: TableDescriptor, relation: RelationDescriptor): ColumnDescriptor | undefined {\n if (relation.kind !== \"belongsTo\") return undefined;\n return table.columns.find(column => column.key === relation.localField);\n}\n\n/**\n * May this caller be handed the rows of this relation?\n *\n * The relation's own rules, and the rules of every column its join reads\n * ({@link relationJoinColumns}): a relation is exactly as readable as what it\n * is joined on. `?include=handler` embeds the staff row whose key `handlerId`\n * holds; `staff?include=handledCases` groups each case under the staff row\n * that same key points at; a `via` over `handler_id` does both. A caller\n * `handlerId`'s `access.read` withholds may do none of them.\n *\n * `related` resolves the other tables a join passes through (by slug or SQL\n * name). Without it, only this table's join columns are judged — enough for a\n * `belongsTo`, not for a `hasMany` / `hasOne` (whose key is the target's) or a\n * `via` past its first step.\n *\n * @param table - the table that declares the relation.\n * @param relation - one of `table.relations`.\n * @param viewer - the caller; `undefined` is the trusted server plane.\n * @param related - the other tables, by slug or SQL name; pass it whenever the\n * relation may join through another table's columns.\n *\n * @group Table\n */\nexport function canReadRelation(\n table: TableDescriptor,\n relation: RelationDescriptor,\n viewer: FieldViewer | undefined,\n related?: RelatedTables\n): boolean {\n if (!canReadColumn(relation, viewer)) return false;\n return relationJoinColumns(table, relation, related).every(column => canReadColumn(column, viewer));\n}\n\n/**\n * May this caller set this relation?\n *\n * The relation's own rules, and — for a `belongsTo` — its key column's\n * (`.readOnly()`, `.private()`, `access.write`): writing a link by name sets\n * that column, so it is closed exactly when writing the column is.\n *\n * @group Table\n */\nexport function canWriteRelation(table: TableDescriptor, relation: RelationDescriptor, viewer: FieldViewer | undefined): boolean {\n if (!canWriteColumn(relation, viewer)) return false;\n const bound = boundKeyColumn(table, relation);\n return bound === undefined || canWriteColumn(bound, viewer);\n}\n\n/**\n * Whether the API does not have this relation at all: it is `.private()`, or\n * it is a `belongsTo` bound to a `.private()` key column — the link would\n * otherwise put the hidden column back on the surface under another name.\n *\n * @group Table\n */\nexport function isPrivateRelation(table: TableDescriptor, relation: RelationDescriptor, related?: RelatedTables): boolean {\n return relation.private === true || relationJoinColumns(table, relation, related).some(column => column.private === true);\n}\n\n/**\n * Any table's descriptor, by slug or by SQL table name: what a relation's\n * target and a `via` step name. Answers `undefined` for a table it does not\n * know (an implicit junction, a table this caller is not served).\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server and @rebasepro/server-postgres; not part of the public API.\n */\nexport type RelatedTables = (slugOrTable: string) => TableDescriptor | typeof UNSERVED_TABLE | undefined;\n\n/**\n * What a {@link RelatedTables} lookup answers for a table the server does not\n * serve: one it withheld (`TABLE_WITHHELD`), or a name no table of its\n * database has. A `via` whose steps pass through such a table is readable and\n * writable by nobody ({@link relationJoinColumns}): the join would read a\n * table the server refuses everyone, and whose column rules it cannot judge.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server-postgres; not part of the public API.\n */\nexport const UNSERVED_TABLE: unique symbol = Symbol(\"rebase.unservedTable\");\n\n/**\n * The join column a `via` reads on a table the server does not serve\n * ({@link UNSERVED_TABLE}): closed to every caller, the admin and the trusted\n * plane included, so every gate that judges a relation by its join columns\n * refuses it.\n */\nconst UNSERVED_JOIN_COLUMN: ColumnDescriptor = {\n key: \"\",\n column: \"\",\n type: { kind: \"text\" },\n nullable: true,\n readOnly: true,\n access: PRIVATE_ACCESS\n};\n\n/**\n * The declared columns a relation's join condition reads, on every table it\n * passes through — the one answer every read gate asks:\n *\n * - `belongsTo` — its key column on this table;\n * - `hasMany` / `hasOne` — this table's source key (the primary key unless\n * `sourceKey` says otherwise) and the target's `foreignKey`;\n * - `manyToMany` — this table's and the target's primary keys, and the\n * junction's two link columns when the junction is a declared table;\n * - `via` — every column every step joins on, `from` on the table before the\n * step and `to` on the step's table (a `table.column` spelling names its\n * own table).\n *\n * A column a table does not describe (an implicit key, an implicit junction)\n * has no rules and is not listed; so is a table `related` cannot find. A\n * `via` step (or a `table.column` qualifier) `related` answers\n * {@link UNSERVED_TABLE} for lists a column nobody may read or write: the\n * relation is closed whole.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server and @rebasepro/server-postgres; not part of the public API.\n */\nexport function relationJoinColumns(table: TableDescriptor, relation: RelationDescriptor, related?: RelatedTables): ColumnDescriptor[] {\n const out: ColumnDescriptor[] = [];\n const add = (on: TableDescriptor | undefined, name: string | undefined): void => {\n if (!on || name === undefined) return;\n const column = on.columns.find(candidate => candidate.column === name || candidate.key === name);\n if (column && !out.includes(column)) out.push(column);\n };\n const target = (): TableDescriptor | undefined => described(related?.(relation.target));\n const primaryKey = (on: TableDescriptor | undefined): void => {\n for (const key of on?.primaryKey ?? []) add(on, key);\n };\n switch (relation.kind) {\n case \"belongsTo\": {\n const bound = boundKeyColumn(table, relation);\n if (bound) out.push(bound);\n break;\n }\n case \"hasMany\":\n case \"hasOne\":\n if (relation.sourceKey !== undefined) add(table, relation.sourceKey);\n else primaryKey(table);\n add(target(), relation.foreignKey);\n break;\n case \"manyToMany\": {\n primaryKey(table);\n const junction = described(related?.(relation.through.table));\n add(junction, relation.through.sourceKey);\n add(junction, relation.through.targetKey);\n primaryKey(target());\n break;\n }\n case \"via\": {\n const tableNamed = (name: string): TableDescriptor | undefined => {\n if (name === table.table || name === table.slug) return table;\n const found = related?.(name);\n if (found === UNSERVED_TABLE) {\n if (!out.includes(UNSERVED_JOIN_COLUMN)) out.push(UNSERVED_JOIN_COLUMN);\n return undefined;\n }\n if (found) return found;\n const end = target();\n return end && end.table === name ? end : undefined;\n };\n let previous: TableDescriptor | undefined = table;\n for (const step of relation.steps) {\n const here = tableNamed(step.table);\n for (const condition of Array.isArray(step.on) ? step.on : [step.on]) {\n for (const name of Array.isArray(condition.from) ? condition.from : [condition.from]) {\n const [qualifier, column] = splitQualified(name);\n add(qualifier === undefined ? previous : tableNamed(qualifier), column);\n }\n for (const name of Array.isArray(condition.to) ? condition.to : [condition.to]) {\n const [qualifier, column] = splitQualified(name);\n add(qualifier === undefined ? here : tableNamed(qualifier), column);\n }\n }\n previous = here;\n }\n break;\n }\n }\n return out;\n}\n\n/**\n * Every table a `via` relation's join passes through, by the name its steps\n * use: each step's table, and each table a `table.column` in a join\n * condition names. In step order, each name once.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server-postgres; not part of the public API.\n */\nexport function viaJoinTableNames(relation: Extract<RelationDescriptor, { kind: \"via\" }>): string[] {\n const out: string[] = [];\n const add = (name: string | undefined): void => {\n if (name !== undefined && !out.includes(name)) out.push(name);\n };\n for (const step of relation.steps) {\n add(step.table);\n for (const condition of Array.isArray(step.on) ? step.on : [step.on]) {\n for (const name of [condition.from, condition.to].flat()) add(splitQualified(name)[0]);\n }\n }\n return out;\n}\n\n/** A lookup's answer as a descriptor: a table it does not serve has none to judge. */\nfunction described(found: TableDescriptor | typeof UNSERVED_TABLE | undefined): TableDescriptor | undefined {\n return found === UNSERVED_TABLE ? undefined : found;\n}\n\n/** `table.column` as its two parts; a bare column has no table. */\nfunction splitQualified(name: string): [string | undefined, string] {\n const dot = name.lastIndexOf(\".\");\n return dot < 0 ? [undefined, name] : [name.slice(0, dot), name.slice(dot + 1)];\n}\n\n/**\n * Whether any relation of this table joins on a column with access rules —\n * on this table or, through `related`, on the others it passes through. The\n * check a read makes before it judges a relation path at all.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server-postgres; not part of the public API.\n */\nexport function hasJoinAccessRules(table: TableDescriptor, related?: RelatedTables): boolean {\n return table.relations.some(relation =>\n relationJoinColumns(table, relation, related).some(column => columnAccess(column) !== undefined));\n}\n\n/**\n * The names on this table a caller may not touch, in both spellings a caller\n * can write them in: `declared` holds column keys and relation names, `refused`\n * those plus the SQL names behind the columns.\n *\n * A column and the `belongsTo` bound to it are one fact under two names, so a\n * restriction on either restricts both: a restricted relation takes its foreign\n * key with it (`bandId: 7` names the band exactly as `band: 7` does), and a\n * restricted key column takes its link with it (`reviewer: 7` sets the\n * `.readOnly()` `reviewerId`; `?include=handler` reads the `access.read`-closed\n * `handlerId`). On a read, a relation is listed when any column its join reads\n * is ({@link relationJoinColumns}; pass `related` to judge the other tables'\n * columns — `staff.handledCases` reads `cases.handlerId`).\n *\n * Replaces `restrictedFieldNames(collection, viewer, kind)`.\n *\n * @group Table\n */\nexport function restrictedKeys(\n table: TableDescriptor,\n viewer: FieldViewer | undefined,\n kind: \"read\" | \"write\",\n related?: RelatedTables\n): { declared: string[]; refused: Set<string> } {\n const allowed = kind === \"read\" ? canReadColumn : canWriteColumn;\n // A write sets a link's own key column alone; a read reads every column\n // the join does.\n return namesWhere(table, target => !allowed(target, viewer), kind === \"read\" ? related ?? NO_RELATED : undefined);\n}\n\n/**\n * The names the API does not have, in every spelling: the private columns,\n * their SQL names, the private relations, the foreign key of a private\n * `belongsTo` and every relation whose join reads a private column (with\n * `related`, on the other tables too). A query naming one is answered as a\n * query naming nothing.\n *\n * Not {@link restrictedKeys}: a column restricted by role is public by name\n * (OpenAPI and MCP describe it); a private one is described nowhere.\n *\n * Replaces `apiHiddenFieldNames(collection)`.\n *\n * @group Table\n */\nexport function apiHiddenKeys(table: TableDescriptor, related?: RelatedTables): Set<string> {\n return namesWhere(table, target => target.private === true, related ?? NO_RELATED).refused;\n}\n\n/** No other table known: a join is judged by this table's columns alone. */\nconst NO_RELATED: RelatedTables = () => undefined;\n\n/**\n * Whether anything on the table restricts a column or relation, either way —\n * the check a per-row strip makes before doing any work.\n *\n * Replaces `hasFieldAccessRules(collection)`.\n *\n * @group Table\n */\nexport function hasColumnAccessRules(table: TableDescriptor): boolean {\n return table.columns.some(column => columnAccess(column) !== undefined)\n || table.relations.some(relation => columnAccess(relation) !== undefined);\n}\n\nfunction namesWhere(\n table: TableDescriptor,\n restricted: (target: AccessTarget) => boolean,\n /** Judge a relation by every column its join reads; absent, by its bound key column alone (a write). */\n joins?: RelatedTables\n): { declared: string[]; refused: Set<string> } {\n const declared: string[] = [];\n const refused = new Set<string>();\n const restrict = (name: string): void => {\n if (!declared.includes(name)) declared.push(name);\n refused.add(name);\n };\n for (const column of table.columns) {\n if (!restricted(column)) continue;\n restrict(column.key);\n refused.add(column.column);\n }\n for (const relation of table.relations) {\n const read = joins ? relationJoinColumns(table, relation, joins === NO_RELATED ? undefined : joins) : [boundKeyColumn(table, relation)];\n if (!restricted(relation) && !read.some(column => column !== undefined && restricted(column))) continue;\n restrict(relation.name);\n if (relation.kind === \"belongsTo\") restrictForeignKey(table, relation, restrict, refused);\n }\n return { declared, refused };\n}\n\nfunction restrictForeignKey(\n table: TableDescriptor,\n relation: Extract<RelationDescriptor, { kind: \"belongsTo\" }>,\n restrict: (name: string) => void,\n refused: Set<string>\n): void {\n const column = table.columns.find(candidate => candidate.key === relation.localField);\n restrict(column?.key ?? relation.localField);\n refused.add(relation.localKey);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,SAAS,UAAU,SAAwC,QAA0C;CACjG,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAQ,OAAO;CACrB,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO;CACzC,OAAO,MAAM,SAAA,OAAmB,KAAK,QAAQ,MAAK,SAAQ,MAAM,SAAS,IAAI,CAAC;AAClF;;;;;;AAOA,SAAgB,kBAAkB,QAAkD,QAA0C;CAC1H,OAAO,UAAU,QAAQ,MAAM,MAAM;AACzC;;;;;AAMA,SAAgB,mBAAmB,QAAmD,QAA0C;CAC5H,OAAO,UAAU,QAAQ,OAAO,MAAM;AAC1C;;;;ACnDA,IAAM,iBAA+B,OAAO,OAAO;CAAE,MAAM,OAAO,OAAO,CAAC,CAAC;CAAG,OAAO,OAAO,OAAO,CAAC,CAAC;AAAE,CAAC;;;;;;;;;AAUxG,SAAgB,aAAa,QAAgF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