@rebasepro/server 0.22.0 → 0.23.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 (114) hide show
  1. package/dist/{GCSStorageController-CLIJXwGS.js → GCSStorageController-CjrA4PMo.js} +37 -23
  2. package/dist/GCSStorageController-CjrA4PMo.js.map +1 -0
  3. package/dist/{S3StorageController-Dcuf8lMA.js → S3StorageController-B6pKDNVj.js} +2 -2
  4. package/dist/{S3StorageController-Dcuf8lMA.js.map → S3StorageController-B6pKDNVj.js.map} +1 -1
  5. package/dist/api/ast-schema-editor.d.ts +35 -0
  6. package/dist/api/live-schema-routes.d.ts +14 -0
  7. package/dist/api/rest/api-generator.d.ts +117 -35
  8. package/dist/api/rest/auth-collection-writes.d.ts +85 -0
  9. package/dist/api/rest/field-access-query.d.ts +6 -2
  10. package/dist/api/rest/idempotency.d.ts +7 -1
  11. package/dist/api/rest/nested-write-access.d.ts +46 -0
  12. package/dist/api/rest/write-validation.d.ts +32 -0
  13. package/dist/{ast-schema-editor-CslO8Oje.js → ast-schema-editor-Mvr50v_S.js} +104 -4
  14. package/dist/ast-schema-editor-Mvr50v_S.js.map +1 -0
  15. package/dist/auth/address-ownership.d.ts +53 -0
  16. package/dist/auth/admin-user-ops.d.ts +35 -2
  17. package/dist/auth/auth-hooks.d.ts +4 -0
  18. package/dist/auth/captcha.d.ts +5 -0
  19. package/dist/auth/interfaces.d.ts +36 -6
  20. package/dist/auth/jwt.d.ts +17 -0
  21. package/dist/auth/oauth-signin-policy.d.ts +25 -8
  22. package/dist/auth/rate-limiter.d.ts +31 -1
  23. package/dist/auth/session-routes.d.ts +7 -0
  24. package/dist/auth/token-revocation.d.ts +4 -1
  25. package/dist/{auth-CCDpk2rn.js → auth-B-GIMpDG.js} +639 -228
  26. package/dist/auth-B-GIMpDG.js.map +1 -0
  27. package/dist/backend-DTAOsLQc.js +30 -0
  28. package/dist/backend-DTAOsLQc.js.map +1 -0
  29. package/dist/backup/backup-common.d.ts +19 -0
  30. package/dist/{backup-DzI9jLwc.js → backup-D7YR94N3.js} +69 -8
  31. package/dist/backup-D7YR94N3.js.map +1 -0
  32. package/dist/boot/driver.d.ts +10 -0
  33. package/dist/boot/env.d.ts +2 -2
  34. package/dist/boot/fetch-bundle.d.ts +18 -1
  35. package/dist/boot/rls-audit-option.d.ts +26 -0
  36. package/dist/boot/sources.d.ts +1 -0
  37. package/dist/{contract-routes-eLxV0le1.js → contract-routes-CbFjuBwa.js} +2 -2
  38. package/dist/{contract-routes-eLxV0le1.js.map → contract-routes-CbFjuBwa.js.map} +1 -1
  39. package/dist/cron/cron-routes.d.ts +7 -2
  40. package/dist/cron/cron-scheduler.d.ts +128 -8
  41. package/dist/cron/cron-store.d.ts +72 -8
  42. package/dist/cron/index.d.ts +1 -1
  43. package/dist/{cron-loader-CQjvjpEw.js → cron-loader-DfTj2Hbi.js} +2 -2
  44. package/dist/{cron-loader-CQjvjpEw.js.map → cron-loader-DfTj2Hbi.js.map} +1 -1
  45. package/dist/{cron-routes-B7CRGfiq.js → cron-routes-eE8nif_b.js} +33 -12
  46. package/dist/cron-routes-eE8nif_b.js.map +1 -0
  47. package/dist/{cron-scheduler-COPQxlEq.js → cron-scheduler-B0pLfAix.js} +394 -68
  48. package/dist/cron-scheduler-B0pLfAix.js.map +1 -0
  49. package/dist/{cron-store-BYGZFNWk.js → cron-store-TcoGz-xS.js} +133 -12
  50. package/dist/cron-store-TcoGz-xS.js.map +1 -0
  51. package/dist/{ddl-bootstrap-CfNvxMuK.js → ddl-bootstrap-C6mo0Kmz.js} +2 -25
  52. package/dist/ddl-bootstrap-C6mo0Kmz.js.map +1 -0
  53. package/dist/email/link-base.d.ts +5 -4
  54. package/dist/email/smtp-email-service.d.ts +13 -1
  55. package/dist/email/templates.d.ts +9 -0
  56. package/dist/email/types.d.ts +3 -2
  57. package/dist/env.d.ts +24 -5
  58. package/dist/{history-recorder-BQmB0P_j.js → history-recorder-B4MpJfJK.js} +8 -6
  59. package/dist/history-recorder-B4MpJfJK.js.map +1 -0
  60. package/dist/{history-store-CetkrBBD.js → history-store-BhxWOuz9.js} +2 -2
  61. package/dist/{history-store-CetkrBBD.js.map → history-store-BhxWOuz9.js.map} +1 -1
  62. package/dist/index.d.ts +6 -2
  63. package/dist/index.es.js +2717 -866
  64. package/dist/index.es.js.map +1 -1
  65. package/dist/init/docs.d.ts +5 -2
  66. package/dist/init/shutdown.d.ts +8 -3
  67. package/dist/jobs/index.d.ts +2 -2
  68. package/dist/jobs/job-queue.d.ts +23 -2
  69. package/dist/jobs/job-store.d.ts +37 -5
  70. package/dist/jobs/types.d.ts +8 -6
  71. package/dist/{jobs-Bjr8DZAi.js → jobs-CazMYhyy.js} +305 -166
  72. package/dist/jobs-CazMYhyy.js.map +1 -0
  73. package/dist/{jwt-C4OW-DNq.js → jwt-DnQHNFCl.js} +77 -25
  74. package/dist/{jwt-C4OW-DNq.js.map → jwt-DnQHNFCl.js.map} +1 -1
  75. package/dist/{keys-Qfc4XieN.js → keys-CogCQpxG.js} +18 -3
  76. package/dist/{keys-Qfc4XieN.js.map → keys-CogCQpxG.js.map} +1 -1
  77. package/dist/{logs-routes-3EEzPjhl.js → logs-routes-Bj4TYYUl.js} +7 -4
  78. package/dist/{logs-routes-3EEzPjhl.js.map → logs-routes-Bj4TYYUl.js.map} +1 -1
  79. package/dist/mcp/mcp-routes.d.ts +38 -2
  80. package/dist/mcp/mcp-tools.d.ts +7 -1
  81. package/dist/mcp/oauth-routes.d.ts +27 -0
  82. package/dist/mcp/oauth-store.d.ts +29 -13
  83. package/dist/metrics/history-recorder.d.ts +1 -1
  84. package/dist/{openapi-generator-D8uFz-LW.js → openapi-generator-O_O24MAT.js} +34 -12
  85. package/dist/openapi-generator-O_O24MAT.js.map +1 -0
  86. package/dist/{query-parser-BleZmY18.js → query-parser-DGRVFNM3.js} +39 -30
  87. package/dist/query-parser-DGRVFNM3.js.map +1 -0
  88. package/dist/rls-audit/index.d.ts +4 -0
  89. package/dist/{schema-editor-routes-DdLihzp0.js → schema-editor-routes-C5-lh_jO.js} +2 -2
  90. package/dist/{schema-editor-routes-DdLihzp0.js.map → schema-editor-routes-C5-lh_jO.js.map} +1 -1
  91. package/dist/{src-1vL-I1Po.js → src-pmvW7BFx.js} +122 -14
  92. package/dist/src-pmvW7BFx.js.map +1 -0
  93. package/dist/{src-Br6ARbs6.js → src-vkcwKXbT.js} +2 -27
  94. package/dist/{src-Br6ARbs6.js.map → src-vkcwKXbT.js.map} +1 -1
  95. package/dist/storage/GCSStorageController.d.ts +11 -1
  96. package/dist/storage/keys.d.ts +12 -0
  97. package/dist/storage/rendition-cache.d.ts +11 -1
  98. package/dist/storage/request-keys.d.ts +67 -0
  99. package/dist/storage/types.d.ts +17 -1
  100. package/dist/types-BfKcm9do.js.map +1 -1
  101. package/package.json +9 -9
  102. package/dist/GCSStorageController-CLIJXwGS.js.map +0 -1
  103. package/dist/ast-schema-editor-CslO8Oje.js.map +0 -1
  104. package/dist/auth-CCDpk2rn.js.map +0 -1
  105. package/dist/backup-DzI9jLwc.js.map +0 -1
  106. package/dist/cron-routes-B7CRGfiq.js.map +0 -1
  107. package/dist/cron-scheduler-COPQxlEq.js.map +0 -1
  108. package/dist/cron-store-BYGZFNWk.js.map +0 -1
  109. package/dist/ddl-bootstrap-CfNvxMuK.js.map +0 -1
  110. package/dist/history-recorder-BQmB0P_j.js.map +0 -1
  111. package/dist/jobs-Bjr8DZAi.js.map +0 -1
  112. package/dist/openapi-generator-D8uFz-LW.js.map +0 -1
  113. package/dist/query-parser-BleZmY18.js.map +0 -1
  114. package/dist/src-1vL-I1Po.js.map +0 -1
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import { o as folderKey, s as listingPrefix } from "./keys-Qfc4XieN.js";
6
+ import { c as listingPrefix, s as folderKey } from "./keys-CogCQpxG.js";
7
7
  import "./types-BfKcm9do.js";
8
8
  //#region src/storage/GCSStorageController.ts
9
9
  /**
@@ -72,7 +72,16 @@ var GCSStorageController = class {
72
72
  storageUrl: `gs://${usedBucket}/${key}`
73
73
  };
74
74
  }
75
- async getSignedUrl(key, bucket) {
75
+ /**
76
+ * Read the object's metadata and nothing else — no signing.
77
+ *
78
+ * Signing needs a private key. With `keyFilename` or `credentials` the
79
+ * client has one; on Cloud Run, GKE or GCE it has only the metadata
80
+ * server's token, and falls back to the IAM Credentials `signBlob` API,
81
+ * which the runtime account may call on itself only when it holds
82
+ * `iam.serviceAccounts.signBlob` there. That is not a default grant.
83
+ */
84
+ async getMetadata(key, bucket) {
76
85
  let resolvedPath = key;
77
86
  let resolvedBucket = this.getBucket(bucket);
78
87
  const match = key.match(/^(gs|s3):\/\//);
@@ -86,32 +95,37 @@ var GCSStorageController = class {
86
95
  }
87
96
  }
88
97
  try {
89
- const gcsFile = (await this.getClient()).bucket(resolvedBucket).file(resolvedPath);
90
- const [fileMetadata] = await gcsFile.getMetadata();
91
- const expiresIn = this.config.signedUrlExpiration ?? 3600;
92
- const [url] = await gcsFile.getSignedUrl({
93
- action: "read",
94
- expires: Date.now() + expiresIn * 1e3
95
- });
98
+ const [fileMetadata] = await (await this.getClient()).bucket(resolvedBucket).file(resolvedPath).getMetadata();
96
99
  return {
97
- url,
98
- metadata: {
99
- bucket: resolvedBucket,
100
- fullPath: resolvedPath,
101
- name: resolvedPath.split("/").pop() || resolvedPath,
102
- size: Number(fileMetadata.size) || 0,
103
- contentType: fileMetadata.contentType || "application/octet-stream",
104
- customMetadata: fileMetadata.metadata || {}
105
- }
100
+ bucket: resolvedBucket,
101
+ fullPath: resolvedPath,
102
+ name: resolvedPath.split("/").pop() || resolvedPath,
103
+ size: Number(fileMetadata.size) || 0,
104
+ contentType: fileMetadata.contentType || "application/octet-stream",
105
+ customMetadata: fileMetadata.metadata || {}
106
106
  };
107
107
  } catch (error) {
108
- if (isNotFoundError(error)) return {
109
- url: null,
110
- fileNotFound: true
111
- };
108
+ if (isNotFoundError(error)) return null;
112
109
  throw error;
113
110
  }
114
111
  }
112
+ async getSignedUrl(key, bucket) {
113
+ const metadata = await this.getMetadata(key, bucket);
114
+ if (!metadata) return {
115
+ url: null,
116
+ fileNotFound: true
117
+ };
118
+ const client = await this.getClient();
119
+ const expiresIn = this.config.signedUrlExpiration ?? 3600;
120
+ const [url] = await client.bucket(metadata.bucket).file(metadata.fullPath).getSignedUrl({
121
+ action: "read",
122
+ expires: Date.now() + expiresIn * 1e3
123
+ });
124
+ return {
125
+ url,
126
+ metadata
127
+ };
128
+ }
115
129
  async getObject(key, bucket) {
116
130
  let resolvedPath = key;
117
131
  let resolvedBucket = this.getBucket(bucket);
@@ -225,4 +239,4 @@ function isNotFoundError(error) {
225
239
  //#endregion
226
240
  export { GCSStorageController_exports as n, GCSStorageController as t };
227
241
 
228
- //# sourceMappingURL=GCSStorageController-CLIJXwGS.js.map
242
+ //# sourceMappingURL=GCSStorageController-CjrA4PMo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GCSStorageController-CjrA4PMo.js","names":[],"sources":["../src/storage/GCSStorageController.ts"],"sourcesContent":["/**\n * Google Cloud Storage controller (works with GCS and Firebase Storage)\n *\n * The `@google-cloud/storage` package is loaded lazily so it remains an\n * optional peer dependency — users who don't need GCS never pay for the\n * import cost or need it installed.\n */\n\nimport {\n StorageController,\n GCSStorageConfig,\n DEFAULT_MAX_FILE_SIZE\n} from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n UploadFileProps,\n UploadFileResult,\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference\n} from \"@rebasepro/types\";\n\n// ---------------------------------------------------------------------------\n// Lazy import of @google-cloud/storage\n// ---------------------------------------------------------------------------\n\nlet gcsModule: typeof import(\"@google-cloud/storage\") | null = null;\n\nasync function loadGCS(): Promise<typeof import(\"@google-cloud/storage\")> {\n if (gcsModule) return gcsModule;\n try {\n gcsModule = await import(\"@google-cloud/storage\");\n return gcsModule;\n } catch {\n throw new Error(\n \"Google Cloud Storage is required for the GCS storage controller. \" +\n \"Install it with: pnpm add @google-cloud/storage\"\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// GCSStorageController\n// ---------------------------------------------------------------------------\n\n/**\n * Google Cloud Storage implementation of `StorageController`.\n *\n * Works with standard GCS buckets **and** Firebase Storage buckets\n * (e.g. `\"my-project.appspot.com\"`).\n */\nexport class GCSStorageController implements StorageController {\n private config: GCSStorageConfig;\n private client: InstanceType<typeof import(\"@google-cloud/storage\").Storage> | null = null;\n\n constructor(config: GCSStorageConfig) {\n this.config = config;\n }\n\n // ------------------------------------------------------------------\n // Lazy client initialisation\n // ------------------------------------------------------------------\n\n private async getClient(): Promise<InstanceType<typeof import(\"@google-cloud/storage\").Storage>> {\n if (this.client) return this.client;\n const { Storage } = await loadGCS();\n this.client = new Storage({\n projectId: this.config.projectId,\n keyFilename: this.config.keyFilename,\n credentials: this.config.credentials\n });\n return this.client;\n }\n\n // ------------------------------------------------------------------\n // StorageController interface\n // ------------------------------------------------------------------\n\n getType(): \"gcs\" {\n return \"gcs\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n * @see S3StorageController.knownBuckets\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n const client = await this.getClient();\n const gcsFile = client.bucket(usedBucket).file(key);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n await gcsFile.save(buffer, {\n contentType: file.type,\n metadata: metadata ? { metadata: this.flattenMetadata(metadata) } : undefined\n });\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `gs://${usedBucket}/${key}`\n };\n }\n\n /**\n * Read the object's metadata and nothing else — no signing.\n *\n * Signing needs a private key. With `keyFilename` or `credentials` the\n * client has one; on Cloud Run, GKE or GCE it has only the metadata\n * server's token, and falls back to the IAM Credentials `signBlob` API,\n * which the runtime account may call on itself only when it holds\n * `iam.serviceAccounts.signBlob` there. That is not a default grant.\n */\n async getMetadata(key: string, bucket?: string): Promise<DownloadMetadata | null> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const [fileMetadata] = await client.bucket(resolvedBucket).file(resolvedPath).getMetadata();\n\n return {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: Number(fileMetadata.size) || 0,\n contentType: fileMetadata.contentType || \"application/octet-stream\",\n customMetadata: (fileMetadata.metadata as Record<string, string> | undefined) || {}\n };\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Metadata first, to check existence and populate the response.\n const metadata = await this.getMetadata(key, bucket);\n if (!metadata) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n\n const client = await this.getClient();\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const [url] = await client.bucket(metadata.bucket).file(metadata.fullPath).getSignedUrl({\n action: \"read\",\n expires: Date.now() + expiresIn * 1000\n });\n\n return {\n url,\n metadata\n };\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n const [contents] = await gcsFile.download();\n\n // Get content type from metadata\n const [fileMetadata] = await gcsFile.getMetadata();\n const contentType = fileMetadata.contentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([new Uint8Array(contents)], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n await gcsFile.delete({ ignoreNotFound: true });\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n const client = await this.getClient();\n const gcsBucket = client.bucket(resolvedBucket);\n\n // Fetch files (objects) matching the prefix\n const [files, , filesApiResponse] = await gcsBucket.getFiles({\n prefix: listingPrefix(prefix),\n delimiter: \"/\",\n maxResults: options?.maxResults ?? 1000,\n pageToken: options?.pageToken,\n autoPaginate: false\n });\n\n const items: StorageReference[] = files.map(file => ({\n bucket: resolvedBucket,\n fullPath: file.name,\n name: file.name.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${file.name}`\n }));\n\n // Common prefixes (folder-like entries) come from the API response\n const apiPrefixes: string[] =\n (filesApiResponse as Record<string, unknown> | undefined)?.prefixes as string[] ?? [];\n\n const prefixes: StorageReference[] = apiPrefixes.map(p => {\n // Without the trailing slash GCS puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(p);\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${folder}`\n };\n });\n\n // The next page token is returned on the query object (second element)\n const nextPageToken =\n (filesApiResponse as Record<string, unknown> | undefined)?.nextPageToken as string | undefined;\n\n return {\n items,\n prefixes,\n nextPageToken\n };\n }\n\n // ------------------------------------------------------------------\n // Private helpers\n // ------------------------------------------------------------------\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name — either from parameter or config.\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for GCS it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n /**\n * Flatten nested metadata to string values (GCS custom metadata requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether an error represents a 404 / Not Found from the GCS client.\n */\nfunction isNotFoundError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const err = error as Record<string, unknown>;\n if (err[\"code\"] === 404) return true;\n if (typeof err[\"message\"] === \"string\" && /not found/i.test(err[\"message\"])) return true;\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,IAAI,YAA2D;AAE/D,eAAe,UAA2D;CACtE,IAAI,WAAW,OAAO;CACtB,IAAI;EACA,YAAY,MAAM,OAAO;EACzB,OAAO;CACX,QAAQ;EACJ,MAAM,IAAI,MACN,kHAEJ;CACJ;AACJ;;;;;;;AAYA,IAAa,uBAAb,MAA+D;CAC3D;CACA,SAAsF;CAEtF,YAAY,QAA0B;EAClC,KAAK,SAAS;CAClB;CAMA,MAAc,YAAmF;EAC7F,IAAI,KAAK,QAAQ,OAAO,KAAK;EAC7B,MAAM,EAAE,YAAY,MAAM,QAAQ;EAClC,KAAK,SAAS,IAAI,QAAQ;GACtB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,aAAa,KAAK,OAAO;EAC7B,CAAC;EACD,OAAO,KAAK;CAChB;CAMA,UAAiB;EACb,OAAO;CACX;;;;;CAMA,eAAyB;EACrB,OAAO,CAAC,WAAW,KAAK,OAAO,MAAM;CACzC;CAEA,MAAM,UAAU,EACZ,MACA,KACA,UACA,UAC2C;EAC3C,KAAK,aAAa,IAAI;EAEtB,MAAM,aAAa,KAAK,UAAU,MAAM;EAExC,MAAM,WAAU,MADK,KAAK,UAAU,EAAA,CACb,OAAO,UAAU,CAAC,CAAC,KAAK,GAAG;EAGlD,MAAM,cAAc,MAAM,KAAK,YAAY;EAC3C,MAAM,SAAS,OAAO,KAAK,WAAW;EAEt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,KAAK,gCAAgC,SAAS;EAGpF,IAAI,KAAK,OAAO,oBAAoB,KAAK,OAAO,iBAAiB,SAAS;OAClE,CAAC,KAAK,OAAO,iBAAiB,SAAS,KAAK,IAAI,GAChD,MAAM,IAAI,MAAM,aAAa,KAAK,KAAK,kCAAkC,KAAK,OAAO,iBAAiB,KAAK,IAAI,GAAG;EAAA;CAG9H;;;;CAKA,UAAkB,QAAyB;EAGvC,IAAI,CAAC,UAAU,WAAW,WAAW,OAAO,KAAK,OAAO;EACxD,OAAO;CACX;;;;CAKA,gBAAwB,UAA2D;EAC/E,MAAM,YAAoC,CAAC;EAC3C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAC9C,IAAI,OAAO,UAAU,UACjB,UAAU,OAAO;OACd,IAAI,UAAU,KAAA,KAAa,UAAU,MACxC,UAAU,OAAO,KAAK,UAAU,KAAK;EAG7C,OAAO;CACX;AACJ;;;;AASA,SAAS,gBAAgB,OAAyB;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,MAAM;CACZ,IAAI,IAAI,YAAY,KAAK,OAAO;CAChC,IAAI,OAAO,IAAI,eAAe,YAAY,aAAa,KAAK,IAAI,UAAU,GAAG,OAAO;CACpF,OAAO;AACX"}
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import { o as folderKey, s as listingPrefix } from "./keys-Qfc4XieN.js";
6
+ import { c as listingPrefix, s as folderKey } from "./keys-CogCQpxG.js";
7
7
  import "./types-BfKcm9do.js";
8
8
  //#region src/storage/S3StorageController.ts
9
9
  var S3StorageController_exports = /* @__PURE__ */ __exportAll({ S3StorageController: () => S3StorageController });
@@ -261,4 +261,4 @@ var S3StorageController = class {
261
261
  //#endregion
262
262
  export { S3StorageController_exports as n, S3StorageController as t };
263
263
 
264
- //# sourceMappingURL=S3StorageController-Dcuf8lMA.js.map
264
+ //# sourceMappingURL=S3StorageController-B6pKDNVj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"S3StorageController-Dcuf8lMA.js","names":[],"sources":["../src/storage/S3StorageController.ts"],"sourcesContent":["/**\n * S3-compatible storage controller (works with AWS S3 and MinIO)\n */\n\nimport type { S3Client as S3ClientType, } from \"@aws-sdk/client-s3\";\nimport { DEFAULT_MAX_FILE_SIZE, S3StorageConfig, StorageController } from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference,\n UploadFileProps,\n UploadFileResult\n} from \"@rebasepro/types\";\n\nlet _s3Module: typeof import(\"@aws-sdk/client-s3\") | undefined;\nlet _presignerModule: typeof import(\"@aws-sdk/s3-request-presigner\") | undefined;\n\nasync function loadS3() {\n if (!_s3Module) {\n try {\n _s3Module = await import(\"@aws-sdk/client-s3\");\n } catch {\n throw new Error(\n \"@aws-sdk/client-s3 is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _s3Module;\n}\n\nasync function loadPresigner() {\n if (!_presignerModule) {\n try {\n _presignerModule = await import(\"@aws-sdk/s3-request-presigner\");\n } catch {\n throw new Error(\n \"@aws-sdk/s3-request-presigner is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _presignerModule;\n}\n\n/**\n * S3-compatible storage implementation\n * Works with AWS S3 and MinIO (with forcePathStyle option)\n */\nexport class S3StorageController implements StorageController {\n private config: S3StorageConfig;\n private _client: S3ClientType | undefined;\n\n constructor(config: S3StorageConfig) {\n this.config = config;\n }\n\n /**\n * Lazily create and cache the S3 client on first use\n */\n private async getClient(): Promise<S3ClientType> {\n if (!this._client) {\n const s3 = await loadS3();\n this._client = new s3.S3Client({\n region: this.config.region || \"us-east-1\",\n endpoint: this.config.endpoint,\n forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint, // Auto-enable for custom endpoints (MinIO)\n credentials: {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey\n }\n });\n }\n return this._client;\n }\n\n getType(): \"s3\" {\n return \"s3\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n *\n * Any other name went straight to S3 as a bucket name, so the request\n * parameter was a way to address *any* bucket the deployment's credentials\n * can reach — and a mistyped one came back as \"file not found\".\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name - either from parameter or config\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for S3 it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.PutObjectCommand({\n Bucket: usedBucket,\n Key: key,\n Body: buffer,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n });\n\n await client.send(command);\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Flatten nested metadata to string values (S3 requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle s3:// and gs:// URLs for backward compatibility\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const presigner = await loadPresigner();\n const client = await this.getClient();\n\n // First check if the object exists and get metadata\n const headCommand = new s3.HeadObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const headResult = await client.send(headCommand);\n\n // Generate a signed URL\n const getCommand = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: headResult.ContentLength || 0,\n contentType: headResult.ContentType || \"application/octet-stream\",\n customMetadata: headResult.Metadata || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NotFound\" || s3Error.$metadata?.httpStatusCode === 404) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const response = await client.send(command);\n\n if (!response.Body) {\n return null;\n }\n\n // Convert stream to buffer\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n\n const contentType = response.ContentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.DeleteObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n // Deleting something that is already gone is the outcome the caller\n // wanted, so it is not an error. AWS itself answers DeleteObject with\n // 204 for a key that never existed, but S3-compatible backends (MinIO,\n // Ceph, R2 in some configurations) do raise NoSuchKey — and the local\n // controller has always returned quietly in this case. Without this,\n // which of those a deployment happens to run decides whether\n // `DELETE /api/storage/:path` on a stale reference is a 200 or a 500.\n try {\n await client.send(command);\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return;\n }\n throw error;\n }\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: listingPrefix(prefix),\n MaxKeys: options?.maxResults ?? 1000,\n ContinuationToken: options?.pageToken,\n Delimiter: \"/\" // This gives us folder-like behavior\n });\n\n const response = await client.send(command);\n\n const items: StorageReference[] = (response.Contents || []).map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${obj.Key}`\n }));\n\n const prefixes: StorageReference[] = (response.CommonPrefixes || []).map(common => {\n // Without the trailing slash S3 puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(common.Prefix || \"\");\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${folder}`\n };\n });\n\n return {\n items,\n prefixes,\n nextPageToken: response.NextContinuationToken\n };\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,IAAI;AACJ,IAAI;AAEJ,eAAe,SAAS;CACpB,IAAI,CAAC,WACD,IAAI;EACA,YAAY,M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;EAErD,MAAM,KAAK,MAAM,OAAO;EACxB,MAAM,SAAS,MAAM,KAAK,UAAU;EAEpC,MAAM,UAAU,IAAI,GAAG,qBAAqB;GACxC,QAAQ;GACR,QAAQ,cAAc,MAAM;GAC5B,SAAS,SAAS,cAAc;GAChC,mBAAmB,SAAS;GAC5B,WAAW;EACf,CAAC;EAED,MAAM,WAAW,MAAM,OAAO,KAAK,OAAO;EAyB1C,OAAO;GACH,QAxB+B,SAAS,YAAY,CAAC,EAAA,CAAG,KAAI,SAAQ;IACpE,QAAQ;IACR,UAAU,IAAI,OAAO;IACrB,OAAO,IAAI,OAAO,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;IAC1C,QAAQ;IACR,MAAM;IACN,gBAAgB,QAAQ,eAAe,GAAG,IAAI;GAClD,EAiBI;GACA,WAhBkC,SAAS,kBAAkB,CAAC,EAAA,CAAG,KAAI,WAAU;IAG/E,MAAM,SAAS,UAAU,OAAO,UAAU,EAAE;IAC5C,OAAO;KACH,QAAQ;KACR,UAAU;KACV,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;KACjC,QAAQ;KACR,MAAM;KACN,gBAAgB,QAAQ,eAAe,GAAG;IAC9C;GACJ,CAII;GACA,eAAe,SAAS;EAC5B;CACJ;AACJ"}
1
+ {"version":3,"file":"S3StorageController-B6pKDNVj.js","names":[],"sources":["../src/storage/S3StorageController.ts"],"sourcesContent":["/**\n * S3-compatible storage controller (works with AWS S3 and MinIO)\n */\n\nimport type { S3Client as S3ClientType, } from \"@aws-sdk/client-s3\";\nimport { DEFAULT_MAX_FILE_SIZE, S3StorageConfig, StorageController } from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference,\n UploadFileProps,\n UploadFileResult\n} from \"@rebasepro/types\";\n\nlet _s3Module: typeof import(\"@aws-sdk/client-s3\") | undefined;\nlet _presignerModule: typeof import(\"@aws-sdk/s3-request-presigner\") | undefined;\n\nasync function loadS3() {\n if (!_s3Module) {\n try {\n _s3Module = await import(\"@aws-sdk/client-s3\");\n } catch {\n throw new Error(\n \"@aws-sdk/client-s3 is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _s3Module;\n}\n\nasync function loadPresigner() {\n if (!_presignerModule) {\n try {\n _presignerModule = await import(\"@aws-sdk/s3-request-presigner\");\n } catch {\n throw new Error(\n \"@aws-sdk/s3-request-presigner is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _presignerModule;\n}\n\n/**\n * S3-compatible storage implementation\n * Works with AWS S3 and MinIO (with forcePathStyle option)\n */\nexport class S3StorageController implements StorageController {\n private config: S3StorageConfig;\n private _client: S3ClientType | undefined;\n\n constructor(config: S3StorageConfig) {\n this.config = config;\n }\n\n /**\n * Lazily create and cache the S3 client on first use\n */\n private async getClient(): Promise<S3ClientType> {\n if (!this._client) {\n const s3 = await loadS3();\n this._client = new s3.S3Client({\n region: this.config.region || \"us-east-1\",\n endpoint: this.config.endpoint,\n forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint, // Auto-enable for custom endpoints (MinIO)\n credentials: {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey\n }\n });\n }\n return this._client;\n }\n\n getType(): \"s3\" {\n return \"s3\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n *\n * Any other name went straight to S3 as a bucket name, so the request\n * parameter was a way to address *any* bucket the deployment's credentials\n * can reach — and a mistyped one came back as \"file not found\".\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name - either from parameter or config\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for S3 it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.PutObjectCommand({\n Bucket: usedBucket,\n Key: key,\n Body: buffer,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n });\n\n await client.send(command);\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Flatten nested metadata to string values (S3 requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle s3:// and gs:// URLs for backward compatibility\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const presigner = await loadPresigner();\n const client = await this.getClient();\n\n // First check if the object exists and get metadata\n const headCommand = new s3.HeadObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const headResult = await client.send(headCommand);\n\n // Generate a signed URL\n const getCommand = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: headResult.ContentLength || 0,\n contentType: headResult.ContentType || \"application/octet-stream\",\n customMetadata: headResult.Metadata || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NotFound\" || s3Error.$metadata?.httpStatusCode === 404) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const response = await client.send(command);\n\n if (!response.Body) {\n return null;\n }\n\n // Convert stream to buffer\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n\n const contentType = response.ContentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.DeleteObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n // Deleting something that is already gone is the outcome the caller\n // wanted, so it is not an error. AWS itself answers DeleteObject with\n // 204 for a key that never existed, but S3-compatible backends (MinIO,\n // Ceph, R2 in some configurations) do raise NoSuchKey — and the local\n // controller has always returned quietly in this case. Without this,\n // which of those a deployment happens to run decides whether\n // `DELETE /api/storage/:path` on a stale reference is a 200 or a 500.\n try {\n await client.send(command);\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return;\n }\n throw error;\n }\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: listingPrefix(prefix),\n MaxKeys: options?.maxResults ?? 1000,\n ContinuationToken: options?.pageToken,\n Delimiter: \"/\" // This gives us folder-like behavior\n });\n\n const response = await client.send(command);\n\n const items: StorageReference[] = (response.Contents || []).map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${obj.Key}`\n }));\n\n const prefixes: StorageReference[] = (response.CommonPrefixes || []).map(common => {\n // Without the trailing slash S3 puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(common.Prefix || \"\");\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${folder}`\n };\n });\n\n return {\n items,\n prefixes,\n nextPageToken: response.NextContinuationToken\n };\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,IAAI;AACJ,IAAI;AAEJ,eAAe,SAAS;CACpB,IAAI,CAAC,WACD,IAAI;EACA,YAAY,MAAM,OAAO;CAC7B,QAAQ;EACJ,MAAM,IAAI,MACN,sHAEJ;CACJ;CAEJ,OAAO;AACX;AAEA,eAAe,gBAAgB;CAC3B,IAAI,CAAC,kBACD,IAAI;EACA,mBAAmB,MAAM,OAAO;CACpC,QAAQ;EACJ,MAAM,IAAI,MACN,iIAEJ;CACJ;CAEJ,OAAO;AACX;;;;;AAMA,IAAa,sBAAb,MAA8D;CAC1D;CACA;CAEA,YAAY,QAAyB;EACjC,KAAK,SAAS;CAClB;;;;CAKA,MAAc,YAAmC;EAC7C,IAAI,CAAC,KAAK,SAAS;GACf,MAAM,KAAK,MAAM,OAAO;GACxB,KAAK,UAAU,IAAI,GAAG,SAAS;IAC3B,QAAQ,KAAK,OAAO,UAAU;IAC9B,UAAU,KAAK,OAAO;IACtB,gBAAgB,KAAK,OAAO,kBAAkB,C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AAS,kBAAkB,CAAC,EAAA,CAAG,KAAI,WAAU;IAG/E,MAAM,SAAS,UAAU,OAAO,UAAU,EAAE;IAC5C,OAAO;KACH,QAAQ;KACR,UAAU;KACV,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;KACjC,QAAQ;KACR,MAAM;KACN,gBAAgB,QAAQ,eAAe,GAAG;IAC9C;GACJ,CAII;GACA,eAAe,SAAS;EAC5B;CACJ;AACJ"}
@@ -95,7 +95,18 @@ export declare class AstSchemaEditor {
95
95
  * and kanban config in the same write.
96
96
  */
97
97
  private mergeIntoObjectLiteral;
98
+ /**
99
+ * Drop whatever a refused edit left in memory.
100
+ *
101
+ * One editor serves every request, and `project.save()` writes every file
102
+ * with unsaved changes. So an edit refused halfway through — a relation with
103
+ * no target, found after the name was already rewritten and an import
104
+ * added — reached the disk with the next save of some other collection, and
105
+ * a file refused as it was being created appeared anyway.
106
+ */
107
+ private forgetUnsaved;
98
108
  saveProperty(collectionId: string, propertyKey: string, propertyConfig: Record<string, unknown>): Promise<void>;
109
+ private writeProperty;
99
110
  deleteProperty(collectionId: string, propertyKey: string): Promise<void>;
100
111
  /**
101
112
  * Write a collection back to its file.
@@ -111,6 +122,30 @@ export declare class AstSchemaEditor {
111
122
  saveCollection(collectionId: string, collectionData: Record<string, unknown>, options?: {
112
123
  partial?: boolean;
113
124
  }): Promise<void>;
125
+ private writeCollection;
126
+ /**
127
+ * Every property relation's `target`, as source.
128
+ *
129
+ * The collection-level `relations` array has {@link writeRelations}. A
130
+ * relation declared on a property went through `convertJsonToAstString`
131
+ * like any other value, so a target the property form had picked — a slug,
132
+ * which is all JSON can carry — was written as the string literal
133
+ * `target: "authors"`, and the next boot threw in `resolveRelation` for every
134
+ * collection in the directory. The same rule applies here as there: a slug
135
+ * becomes `() => xCollection` plus its import, an arrow returning one
136
+ * identifier is written through, and a relation sent without a target keeps
137
+ * the one already in the file — or is refused, when there is none.
138
+ *
139
+ * Walks into `map` properties, an array's `of` and a block's `oneOf`, which
140
+ * the registry resolves relations in too. `oldProperties` is the same
141
+ * properties object in the file, when there is one.
142
+ */
143
+ private relationTargetsAsSource;
144
+ private propertyRelationTargetsAsSource;
145
+ /** The initializer of `obj[key]` in the file, when it is written as a property assignment. */
146
+ private initializerOf;
147
+ /** `obj[key]` in the file, when it is an object literal. */
148
+ private objectAt;
114
149
  /**
115
150
  * Write the collection-level `relations` array.
116
151
  *
@@ -131,6 +131,20 @@ export declare function commitAuthor(user: unknown): {
131
131
  /**
132
132
  * The proposed collection set: everything as it is, with one collection
133
133
  * replaced or added.
134
+ *
135
+ * The replacement arrives as JSON, and a relation's `target` is a thunk —
136
+ * `JSON.stringify` drops it, so every relation the panel did not touch comes
137
+ * back with no target, and one picked in the property form names its target by
138
+ * slug. The planner calls `target()` on every relation in the set, so as it
139
+ * arrived it threw on the first one, and no change of any kind could be planned
140
+ * for a collection that had a relation.
141
+ *
142
+ * So each target is made callable again, the way the AST editor makes it
143
+ * source again when it writes the file: a slug becomes a lookup in the
144
+ * proposed set — so a link to the collection being edited reaches its new
145
+ * version — and a missing target is the one the same relation has now. A
146
+ * target that is neither is refused here, as the caller's mistake, rather than
147
+ * thrown from inside the planner as a 500.
134
148
  */
135
149
  export declare function proposedCollections(current: CollectionConfig[], change: ProposedChange): CollectionConfig[];
136
150
  export declare function createLiveSchemaRoutes(config: LiveSchemaRoutesConfig): Hono<HonoEnv>;
@@ -119,28 +119,55 @@ export declare class RestApiGenerator {
119
119
  */
120
120
  private enforceApiKeyPermission;
121
121
  /**
122
- * API key permission check for nested paths. The operation targets the
123
- * LAST collection in the path (e.g. "posts" for /authors/1/posts), so
124
- * that is the slug the key must hold permission for — checking the
125
- * parent instead would let a key scoped to "authors" write "posts".
126
- * `parseSubPath` always yields a collectionPath ending in a collection
127
- * slug, never an id.
122
+ * API key permission check for nested paths.
123
+ *
124
+ * The operation lands on the collection the path addresses — the target
125
+ * of its last relation — so that is the collection the key must hold the
126
+ * route's operation for; checking only the parent would let a key scoped
127
+ * to `authors` write `posts`. The *collection*, not the path segment: a
128
+ * relation's name is not its target's slug, and a key for `notes` read
129
+ * `internal_notes` through `projects/1/notes` because the check read the
130
+ * name off the URL.
131
+ *
132
+ * Every collection the path passes through is addressed as well — "the
133
+ * posts of author 1" goes through a row of `authors` — so the key must be
134
+ * able to read each of them.
128
135
  */
129
136
  private enforceSubcollectionApiKeyPermission;
130
137
  /**
131
- * The collection a nested path writes into — the target of the relation its
132
- * last segment names.
138
+ * The collection a path's first segment names.
133
139
  *
134
- * Needed so a nested write can be checked against a schema at all. Without
135
- * it these routes skipped `assertKnownWriteFields` entirely, which is why a
136
- * typo `POST /posts` rejected with a 400 while the same typo on
137
- * `POST /authors/1/posts` was dropped from the statement and answered 201.
140
+ * By the rule the driver's registry applies (`CollectionRegistry.get`),
141
+ * because the driver is what a nested path is forwarded to: the slug, then
142
+ * the slug written in kebab case — URLs are — then the table name. Matching
143
+ * the slug alone left the other two spellings resolving in the driver and
144
+ * in nothing here, so a nested request spelled either way was checked
145
+ * against no collection at all.
146
+ */
147
+ private collectionNamed;
148
+ /**
149
+ * Walk a nested path to the collection it addresses — the target of the
150
+ * relation its last segment names.
138
151
  *
139
- * Returns `undefined` rather than throwing when the path cannot be walked:
140
- * the driver raises the authoritative error a moment later, and duplicating
141
- * it here would report a resolution failure as a validation failure.
152
+ * Needed so a nested request can be checked against a schema at all: the
153
+ * fields a body may write and a query may read are the target's. A path
154
+ * that names nothing is a 404 here, before anything else happens. This
155
+ * used to return `undefined` instead and leave the refusal to the driver,
156
+ * and every check on these routes was written `if (target) …` — so a path
157
+ * the driver could resolve and this walk could not was a request with no
158
+ * checks on it, rather than a refused one.
159
+ *
160
+ * The path handed back is spelled with the root's slug, which is what
161
+ * makes the two agree: whatever spelling arrived, the driver is asked about
162
+ * the collection this route checked the request against.
163
+ */
164
+ private resolveNestedPath;
165
+ /**
166
+ * Refuse a write through `nested` that sets a relation this caller may not
167
+ * write — the parent's relation, or the parent's key on the child. See
168
+ * {@link assertNestedWriteAllowed}; the socket asks it the same question.
142
169
  */
143
- private resolveNestedWriteCollection;
170
+ private assertNestedRelationWritable;
144
171
  /**
145
172
  * `PATCH <collection>/<id>/<relation>/<targetId>` with a `_pivot` body: set
146
173
  * the columns that one many-to-many link carries.
@@ -160,15 +187,30 @@ export declare class RestApiGenerator {
160
187
  */
161
188
  private updateRelationPivotFromBody;
162
189
  /**
163
- * The synthetic collection standing in for the junction a nested path's last
164
- * hop reaches through, or `undefined` when that hop is not a `manyToMany`
165
- * carrying `through.properties`.
190
+ * Updates to rows of the auth collection, checked and put in stored form
191
+ * by the auth adapter — `AuthAdapter.prepareUserUpdates`. Those rows are
192
+ * the users, so an update is user administration and holds to what
193
+ * `/admin/users` holds to: the last administrator stays one, an email is
194
+ * stored the way sign-in looks it up. Any other collection's values, and
195
+ * an adapter with no such step, pass through unchanged.
196
+ */
197
+ private prepareUserUpdates;
198
+ /**
199
+ * Delete rows of the auth collection as user administration: the adapter's
200
+ * checks and `beforeUserDelete` before (either may refuse), its session
201
+ * cleanup and `afterUserDelete` after. See {@link prepareUserUpdates}.
202
+ */
203
+ private deletingUsers;
204
+ /**
205
+ * `POST /users/bulk`: every row a user creation, the rows written as one
206
+ * transaction, the invitations sent once it has committed.
166
207
  *
167
- * Built from the relation rather than by walking every collection: the same
168
- * `getJunctionConfigForRelation` the schema planner and the driver use, so
169
- * the shape validated here is the shape the columns were emitted from.
208
+ * Answered in full whatever `Prefer` says, and never replayed from the
209
+ * idempotency store, as `POST /users` is: the answer can carry temporary
210
+ * passwords, which are shown once. Dropped from a minimal answer they are
211
+ * gone, and handed out again on a replayed key they are disclosed.
170
212
  */
171
- private resolveJunctionCollection;
213
+ private createUsers;
172
214
  /**
173
215
  * Get the request-scoped driver. Throws if none is set — never falls
174
216
  * back to the unscoped `this.driver` to avoid bypassing RLS/auth.
@@ -199,16 +241,38 @@ export declare class RestApiGenerator {
199
241
  */
200
242
  private runIdempotent;
201
243
  /**
202
- * The row as the read routes serve it, for hashing into an `ETag`.
203
- *
204
- * A tag derived from a version column is the same whichever read produced
205
- * the row, so nothing extra is fetched for it. The fallback hashes the row
206
- * itself, and there the *shape* matters: `GET /:id` serves the REST walk
207
- * while the write routes read through `driver.fetchOne` (the admin view
208
- * model), so hashing whichever one happened to be in hand would give the
209
- * same row two different tags and make every `If-Match` a coin toss.
244
+ * The row an `ETag` is hashed from: the REST read of it, with no
245
+ * `?fields=` projection and no `?include=`.
246
+ *
247
+ * The read routes and the write routes both take their tag from here, so a
248
+ * tag a `GET` handed out and the tag a write compares it against are
249
+ * hashes of one rendering of the row. The write routes' own existence read
250
+ * is not that rendering, not even for its version column: `driver.fetchOne`
251
+ * returns the admin view model, where a date is a `{ __type: "date" }`
252
+ * envelope rather than the ISO string the REST row carries. Hashing it
253
+ * matched no tag any read ever handed out, so every conditional write to a
254
+ * collection with an `on_update` date was a 412.
255
+ *
256
+ * A driver without a REST read serves `GET /:id` from `fetchOne` too, so
257
+ * there the row already read is the rendering to hash.
258
+ *
259
+ * @param withDeleted how the row was read — a purge reads a trashed row,
260
+ * and a tag compared against a read that hides it compares against
261
+ * nothing.
210
262
  */
211
263
  private rowForETag;
264
+ /**
265
+ * `GET /:id`, at a row's own address or through a parent: the row as the
266
+ * query asked for it, and the `ETag` naming its version.
267
+ *
268
+ * The tag names the row, not the read. `?fields=` and `?include=` change
269
+ * what the response carries, and hashing what they produced gave one row a
270
+ * different tag for every way of reading it — none of them the tag a write
271
+ * computes, so the `If-Match` of any caller that read a projection or a
272
+ * relation was a 412. A narrowed read therefore takes its tag from
273
+ * {@link rowForETag}, the read the write routes make.
274
+ */
275
+ private readRow;
212
276
  /**
213
277
  * Answer a bulk write, honouring `Prefer: return=minimal`.
214
278
  *
@@ -218,6 +282,28 @@ export declare class RestApiGenerator {
218
282
  * the count never has to ask for the rows.
219
283
  */
220
284
  private respondBulk;
285
+ /**
286
+ * Create one row: `POST /<collection>`, and the same create reached through
287
+ * a parent, `POST /<parent>/<id>/<relation>`.
288
+ *
289
+ * Errors from here are deliberately not re-classified. This layer cannot
290
+ * tell a constraint violation from an unreachable database, and it used to
291
+ * call both `BAD_REQUEST` — a claim that the caller sent something wrong and
292
+ * should not retry. The driver holds the SQLSTATE and raises an `ApiError`
293
+ * for what is genuinely the request's fault; anything still unclassified
294
+ * here is ours, and that is a 500.
295
+ */
296
+ private createRow;
297
+ /**
298
+ * Update one row: `PATCH /<collection>/<id>`, and the same row reached
299
+ * through a parent. Errors are not re-classified; see {@link createRow}.
300
+ */
301
+ private updateRow;
302
+ /**
303
+ * Delete one row: `DELETE /<collection>/<id>`, and the same row reached
304
+ * through a parent.
305
+ */
306
+ private deleteRow;
221
307
  /**
222
308
  * Create REST routes for a collection using existing Rebase patterns
223
309
  */
@@ -267,8 +353,4 @@ export declare class RestApiGenerator {
267
353
  * Count raw entities for a collection
268
354
  */
269
355
  private countRawEntities;
270
- /**
271
- * Fetch single entity raw data without Entity wrapper (fallback)
272
- */
273
- private fetchRawEntity;
274
356
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * A write to the auth collection is user administration.
3
+ *
4
+ * The auth collection's rows are the users. `/admin/users` holds a change to
5
+ * one to the auth adapter's rules: a create goes through the adapter's user
6
+ * creation (the password hashed, the email normalized, the collection's
7
+ * `onCreateUser`, the invitation), an update may not leave the project without
8
+ * an administrator and stores an email the way sign-in looks it up, and a
9
+ * deletion runs `beforeUserDelete` (a veto), ends the sessions and runs
10
+ * `afterUserDelete`. The data doors that write the same rows — the REST routes
11
+ * and MCP's write tools — call these, so that no door writes a user by rules
12
+ * of its own. (The Postgres socket calls the adapter's methods directly.)
13
+ *
14
+ * Every function here leaves any other collection, and an adapter without the
15
+ * step, exactly as it was: the rows are then written as any table's.
16
+ */
17
+ import type { AuthAdapter, CollectionConfig, UserCreationFinalizeResult, UserCreationPrepareResult } from "@rebasepro/types";
18
+ import type { FieldViewer } from "@rebasepro/common";
19
+ /** Whether `collection` is the auth collection — its rows are the users. */
20
+ export declare function isAuthCollection(collection: CollectionConfig): boolean;
21
+ /** An adapter that performs user creation (`prepareUserCreation`). */
22
+ export type UserCreatingAdapter = AuthAdapter & Required<Pick<AuthAdapter, "prepareUserCreation">>;
23
+ /**
24
+ * Whether a create on `collection` is a user creation `adapter` performs: the
25
+ * collection is the auth collection and the adapter has the step. When not,
26
+ * the door writes the row as any other.
27
+ */
28
+ export declare function createsUsers(adapter: AuthAdapter | undefined, collection: CollectionConfig): adapter is UserCreatingAdapter;
29
+ /**
30
+ * Check a create body for the auth collection against what the adapter says a
31
+ * create consumes (`describeUserCreationContract`).
32
+ *
33
+ * Signups carry credential fields (`password`) the collection does not declare
34
+ * as columns, so the body is checked for everything else. A custom
35
+ * `onCreateUser` owns the body's shape, and then the adapter asks for no check:
36
+ * the collection's fields do not describe what arrived.
37
+ *
38
+ * `rowIndex` names the row in a bulk write's message.
39
+ */
40
+ export declare function assertUserCreationBodyValid(adapter: AuthAdapter | undefined, collection: CollectionConfig, body: Record<string, unknown>, viewer: FieldViewer, rowIndex?: number): void;
41
+ /**
42
+ * The first half of creating users, before anything is written: each body
43
+ * through the adapter's `prepareUserCreation` (the password hashed or
44
+ * generated, the email normalized, the collection's `onCreateUser`), in order.
45
+ * The `values` of each result are what the door writes.
46
+ */
47
+ export declare function prepareUserCreations(adapter: UserCreatingAdapter, collection: CollectionConfig, bodies: readonly Record<string, unknown>[]): Promise<UserCreationPrepareResult[]>;
48
+ /**
49
+ * The second half, once the rows are written — and only then, so a write that
50
+ * fails invites nobody: the credentials' delivery through
51
+ * {@link completeUserCreation}, which is also what `POST /admin/users` calls.
52
+ *
53
+ * @returns For each row, the delivery fields a create response carries
54
+ * (`invitationSent`, and `temporaryPassword` when nobody was sent one).
55
+ */
56
+ export declare function completeUserCreations(adapter: UserCreatingAdapter, prepared: readonly UserCreationPrepareResult[], rows: readonly Record<string, unknown>[]): Promise<UserCreationFinalizeResult[]>;
57
+ /**
58
+ * Create one user through the auth collection: {@link prepareUserCreations},
59
+ * then `save` (the door's own driver write), then
60
+ * {@link completeUserCreations}.
61
+ *
62
+ * `undefined` when the create is not a user creation ({@link createsUsers}) —
63
+ * the door then writes the row as any other.
64
+ */
65
+ export declare function createUserThroughAuthCollection(adapter: AuthAdapter | undefined, collection: CollectionConfig, body: Record<string, unknown>, save: (values: Record<string, unknown>) => Promise<Record<string, unknown>>): Promise<{
66
+ row: Record<string, unknown>;
67
+ delivery: UserCreationFinalizeResult;
68
+ } | undefined>;
69
+ /**
70
+ * Updates to rows of the auth collection, checked and put in stored form by
71
+ * the adapter's `prepareUserUpdates`: judged together, so a bulk demotion of
72
+ * every administrator is refused although each row alone would pass.
73
+ *
74
+ * @returns Each update's values, as they should be written, in order.
75
+ */
76
+ export declare function prepareAuthCollectionUpdates(adapter: AuthAdapter | undefined, collection: CollectionConfig, updates: {
77
+ uid: string;
78
+ values: Record<string, unknown>;
79
+ }[]): Promise<Record<string, unknown>[]>;
80
+ /**
81
+ * Delete rows of the auth collection as user administration: the adapter's
82
+ * checks and `beforeUserDelete` before `remove` runs (either may refuse), its
83
+ * session cleanup and `afterUserDelete` after.
84
+ */
85
+ export declare function deletingAuthCollectionUsers<T>(adapter: AuthAdapter | undefined, collection: CollectionConfig | undefined, uids: string[], remove: () => Promise<T>): Promise<T>;
@@ -1,4 +1,4 @@
1
- import type { CollectionConfig } from "@rebasepro/types";
1
+ import type { CollectionConfig, IncludeSpec } from "@rebasepro/types";
2
2
  import type { LogicalCondition } from "@rebasepro/types";
3
3
  import { type FieldViewer } from "@rebasepro/common";
4
4
  /**
@@ -39,7 +39,7 @@ export declare function requestViewer(c: {
39
39
  get: (key: never) => unknown;
40
40
  }): FieldViewer;
41
41
  /** Which query parameter a refused field arrived in, for the message. */
42
- type Where = "filter" | "orderBy" | "fields" | "select" | "groupBy";
42
+ type Where = "filter" | "orderBy" | "fields" | "select" | "groupBy" | "vector_search";
43
43
  /**
44
44
  * Refuse the request when any of `names` is a field this caller cannot read.
45
45
  *
@@ -62,5 +62,9 @@ export declare function assertQueryFieldsReadable(options: {
62
62
  field: string;
63
63
  }[];
64
64
  fields?: string[];
65
+ include?: IncludeSpec;
66
+ vectorSearch?: {
67
+ property: string;
68
+ };
65
69
  }, collection: CollectionConfig, viewer: FieldViewer | undefined): void;
66
70
  export {};