@rebasepro/common 0.24.0 → 0.24.1-canary.g56af4a4
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.
- package/dist/collections/CollectionRegistry.es.js +404 -0
- package/dist/collections/CollectionRegistry.es.js.map +1 -0
- package/dist/collections/auth-secrets.es.js +47 -0
- package/dist/collections/auth-secrets.es.js.map +1 -0
- package/dist/collections/default-collections.es.js +120 -0
- package/dist/collections/default-collections.es.js.map +1 -0
- package/dist/collections/engine-support.es.js +35 -0
- package/dist/collections/engine-support.es.js.map +1 -0
- package/dist/collections/field-access.d.ts +13 -0
- package/dist/collections/field-access.es.js +142 -0
- package/dist/collections/field-access.es.js.map +1 -0
- package/dist/collections/index.d.ts +1 -0
- package/dist/collections/soft-delete.es.js +34 -0
- package/dist/collections/soft-delete.es.js.map +1 -0
- package/dist/collections/unknown-field.d.ts +65 -0
- package/dist/collections/unknown-field.es.js +135 -0
- package/dist/collections/unknown-field.es.js.map +1 -0
- package/dist/data/buildRebaseData.d.ts +12 -2
- package/dist/data/buildRebaseData.es.js +1026 -0
- package/dist/data/buildRebaseData.es.js.map +1 -0
- package/dist/data/buildRoutedRebaseData.d.ts +6 -1
- package/dist/data/buildRoutedRebaseData.es.js +47 -0
- package/dist/data/buildRoutedRebaseData.es.js.map +1 -0
- package/dist/data/collection-accessor.d.ts +54 -0
- package/dist/data/collection-accessor.es.js +101 -0
- package/dist/data/collection-accessor.es.js.map +1 -0
- package/dist/data/cursor.es.js +166 -0
- package/dist/data/cursor.es.js.map +1 -0
- package/dist/data/filter-conditions.es.js +24 -0
- package/dist/data/filter-conditions.es.js.map +1 -0
- package/dist/data/filter-dialect.d.ts +3 -3
- package/dist/data/filter-dialect.es.js +786 -0
- package/dist/data/filter-dialect.es.js.map +1 -0
- package/dist/data/include-spec.d.ts +2 -0
- package/dist/data/include-spec.es.js +273 -0
- package/dist/data/include-spec.es.js.map +1 -0
- package/dist/data/paginate.d.ts +8 -1
- package/dist/data/paginate.es.js +181 -0
- package/dist/data/paginate.es.js.map +1 -0
- package/dist/data/query_builder.d.ts +52 -4
- package/dist/data/query_builder.es.js +151 -0
- package/dist/data/query_builder.es.js.map +1 -0
- package/dist/data/resolveDataSource.es.js +87 -0
- package/dist/data/resolveDataSource.es.js.map +1 -0
- package/dist/data/row-etag.d.ts +46 -0
- package/dist/data/row-etag.es.js +64 -0
- package/dist/data/row-etag.es.js.map +1 -0
- package/dist/data/sort-dialect.es.js +236 -0
- package/dist/data/sort-dialect.es.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.es.js +56 -7588
- package/dist/table-classification.es.js +107 -0
- package/dist/table-classification.es.js.map +1 -0
- package/dist/util/auth-default-policies.es.js +184 -0
- package/dist/util/auth-default-policies.es.js.map +1 -0
- package/dist/util/builders.es.js +15 -0
- package/dist/util/builders.es.js.map +1 -0
- package/dist/util/callback-errors.es.js +164 -0
- package/dist/util/callback-errors.es.js.map +1 -0
- package/dist/util/callbacks.es.js +72 -0
- package/dist/util/callbacks.es.js.map +1 -0
- package/dist/util/collections.es.js +79 -0
- package/dist/util/collections.es.js.map +1 -0
- package/dist/util/common.es.js +7 -0
- package/dist/util/common.es.js.map +1 -0
- package/dist/util/conditions.es.js +100 -0
- package/dist/util/conditions.es.js.map +1 -0
- package/dist/util/copy.es.js +74 -0
- package/dist/util/copy.es.js.map +1 -0
- package/dist/util/download-url-cache.d.ts +122 -0
- package/dist/util/download-url-cache.es.js +187 -0
- package/dist/util/download-url-cache.es.js.map +1 -0
- package/dist/util/email.es.js +36 -0
- package/dist/util/email.es.js.map +1 -0
- package/dist/util/entities.d.ts +18 -1
- package/dist/util/entities.es.js +328 -0
- package/dist/util/entities.es.js.map +1 -0
- package/dist/util/enums.d.ts +10 -1
- package/dist/util/enums.es.js +37 -0
- package/dist/util/enums.es.js.map +1 -0
- package/dist/util/identity.es.js +138 -0
- package/dist/util/identity.es.js.map +1 -0
- package/dist/util/index.d.ts +4 -0
- package/dist/util/internal-tables.d.ts +10 -0
- package/dist/util/internal-tables.es.js +202 -0
- package/dist/util/internal-tables.es.js.map +1 -0
- package/dist/util/junction-policies.es.js +273 -0
- package/dist/util/junction-policies.es.js.map +1 -0
- package/dist/util/paths.es.js +26 -0
- package/dist/util/paths.es.js.map +1 -0
- package/dist/util/permissions.es.js +108 -0
- package/dist/util/permissions.es.js.map +1 -0
- package/dist/util/pg-column-to-property.es.js +303 -0
- package/dist/util/pg-column-to-property.es.js.map +1 -0
- package/dist/util/policy/compileRulePolicies.es.js +43 -0
- package/dist/util/policy/compileRulePolicies.es.js.map +1 -0
- package/dist/util/policy/evaluatePolicy.es.js +104 -0
- package/dist/util/policy/evaluatePolicy.es.js.map +1 -0
- package/dist/util/policy/policyToPostgres.d.ts +24 -0
- package/dist/util/policy/policyToPostgres.es.js +593 -0
- package/dist/util/policy/policyToPostgres.es.js.map +1 -0
- package/dist/util/policy/policyToSecurityRule.es.js +79 -0
- package/dist/util/policy/policyToSecurityRule.es.js.map +1 -0
- package/dist/util/policy/securityRuleToConditions.es.js +48 -0
- package/dist/util/policy/securityRuleToConditions.es.js.map +1 -0
- package/dist/util/policy/sqlToPolicy.es.js +326 -0
- package/dist/util/policy/sqlToPolicy.es.js.map +1 -0
- package/dist/util/relations.es.js +243 -0
- package/dist/util/relations.es.js.map +1 -0
- package/dist/util/resolutions.es.js +318 -0
- package/dist/util/resolutions.es.js.map +1 -0
- package/dist/util/resolve-relation.es.js +163 -0
- package/dist/util/resolve-relation.es.js.map +1 -0
- package/dist/util/resumable-upload-threshold.d.ts +15 -0
- package/dist/util/resumable-upload-threshold.es.js +20 -0
- package/dist/util/resumable-upload-threshold.es.js.map +1 -0
- package/dist/util/resumable-upload.d.ts +51 -0
- package/dist/util/resumable-upload.es.js +121 -0
- package/dist/util/resumable-upload.es.js.map +1 -0
- package/dist/util/sql-redaction.d.ts +21 -0
- package/dist/util/sql-redaction.es.js +107 -0
- package/dist/util/sql-redaction.es.js.map +1 -0
- package/dist/util/sql-rows.es.js +41 -0
- package/dist/util/sql-rows.es.js.map +1 -0
- package/dist/util/storage.d.ts +26 -4
- package/dist/util/storage.es.js +117 -0
- package/dist/util/storage.es.js.map +1 -0
- package/dist/util/string-column-length.es.js +31 -0
- package/dist/util/string-column-length.es.js.map +1 -0
- package/dist/util/tenant.es.js +201 -0
- package/dist/util/tenant.es.js.map +1 -0
- package/dist/util/untrusted-envelope.es.js +40 -0
- package/dist/util/untrusted-envelope.es.js.map +1 -0
- package/package.json +5 -3
- package/dist/index.es.js.map +0 -1
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { UploadFileResult } from "@rebasepro/types";
|
|
2
|
+
/** One response, as the resumable upload reads it. */
|
|
3
|
+
export interface ResumableUploadResponse {
|
|
4
|
+
status: number;
|
|
5
|
+
header(name: string): string | null;
|
|
6
|
+
/** The error a non-2xx response stands for, as the transport reports it. */
|
|
7
|
+
error?: Error;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Send one TUS request. `path` is `""` for the creation request and
|
|
11
|
+
* `/<upload id>` after it, relative to the source's `…/storage/tus` endpoint.
|
|
12
|
+
* Answers every HTTP status; throws only when no response arrived.
|
|
13
|
+
*/
|
|
14
|
+
export type ResumableUploadSend = (method: "POST" | "PATCH" | "HEAD" | "DELETE", path: string, headers: Record<string, string>, body?: Blob) => Promise<ResumableUploadResponse>;
|
|
15
|
+
export interface ResumableUploadOptions {
|
|
16
|
+
file: Blob;
|
|
17
|
+
/** `Upload-Metadata` entries: `key`, `filename`, `filetype`, `bucket`, `storageId`, `collection`, `property`, `metadata_<name>`. */
|
|
18
|
+
metadata: Record<string, string>;
|
|
19
|
+
send: ResumableUploadSend;
|
|
20
|
+
/** Bytes per `PATCH`. Default {@link RESUMABLE_UPLOAD_THRESHOLD}. */
|
|
21
|
+
chunkSize?: number;
|
|
22
|
+
/** How long to wait before each retry of a chunk; its length is the number of retries. */
|
|
23
|
+
retryDelaysMs?: readonly number[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* What a resumable upload came to: the stored object, or — for a reason the
|
|
27
|
+
* multipart route does not share — nothing, and the caller sends the file
|
|
28
|
+
* through `POST /storage/upload` instead.
|
|
29
|
+
*/
|
|
30
|
+
export type ResumableUploadOutcome = {
|
|
31
|
+
stored: UploadFileResult;
|
|
32
|
+
} | {
|
|
33
|
+
unavailable: string;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Upload `file` through a Rebase server's TUS endpoint, one chunk at a time.
|
|
37
|
+
*
|
|
38
|
+
* The server holds every upload to what `POST /storage/upload` holds a file
|
|
39
|
+
* to — the source's and the property's limits, the authorize hook, the bucket
|
|
40
|
+
* — and stores it with the same key, type and custom metadata, and fires the
|
|
41
|
+
* same triggers. So a refusal is thrown as the multipart route would have
|
|
42
|
+
* thrown it. A chunk that fails on the way — a dropped connection, a 5xx, a
|
|
43
|
+
* conflict over the offset — is retried from the offset the server reports.
|
|
44
|
+
*
|
|
45
|
+
* Answers `unavailable` when the resumable path cannot carry this file and
|
|
46
|
+
* the multipart one can: a server without the endpoint (or one too old to
|
|
47
|
+
* report the stored object), an upload another instance cannot see (several
|
|
48
|
+
* instances, no shared volume, no sticky sessions), or a chunk over the
|
|
49
|
+
* server's body limit.
|
|
50
|
+
*/
|
|
51
|
+
export declare function uploadResumable(options: ResumableUploadOptions): Promise<ResumableUploadOutcome>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { RESUMABLE_UPLOAD_THRESHOLD } from "./resumable-upload-threshold.es.js";
|
|
2
|
+
//#region src/util/resumable-upload.ts
|
|
3
|
+
/** What `create` answers in `Rebase-Upload-Result` when the last `PATCH` will carry the stored object there. */
|
|
4
|
+
var RESULT_ON_COMPLETE = "on-complete";
|
|
5
|
+
var DEFAULT_RETRY_DELAYS_MS = [
|
|
6
|
+
250,
|
|
7
|
+
1e3,
|
|
8
|
+
3e3
|
|
9
|
+
];
|
|
10
|
+
/** `value` as UTF-8, base64-encoded — what `Upload-Metadata` carries. */
|
|
11
|
+
function base64Utf8(value) {
|
|
12
|
+
const bytes = new TextEncoder().encode(value);
|
|
13
|
+
let binary = "";
|
|
14
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
15
|
+
return btoa(binary);
|
|
16
|
+
}
|
|
17
|
+
/** Worth asking for the offset and sending again: an offset conflict, a lock, a rate limit, a server fault. */
|
|
18
|
+
var isRetryable = (status) => status === 409 || status === 423 || status === 429 || status >= 500;
|
|
19
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
/** The stored object a finished upload reports, or `null` when the header says nothing readable. */
|
|
21
|
+
function storedObjectOf(header) {
|
|
22
|
+
if (!header) return null;
|
|
23
|
+
let value;
|
|
24
|
+
try {
|
|
25
|
+
value = JSON.parse(decodeURIComponent(header));
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value !== "object" || value === null) return null;
|
|
30
|
+
const key = "key" in value ? value.key : void 0;
|
|
31
|
+
const bucket = "bucket" in value ? value.bucket : void 0;
|
|
32
|
+
const storageUrl = "storageUrl" in value ? value.storageUrl : void 0;
|
|
33
|
+
if (typeof key !== "string" || typeof bucket !== "string" || typeof storageUrl !== "string") return null;
|
|
34
|
+
return {
|
|
35
|
+
key,
|
|
36
|
+
bucket,
|
|
37
|
+
storageUrl
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Upload `file` through a Rebase server's TUS endpoint, one chunk at a time.
|
|
42
|
+
*
|
|
43
|
+
* The server holds every upload to what `POST /storage/upload` holds a file
|
|
44
|
+
* to — the source's and the property's limits, the authorize hook, the bucket
|
|
45
|
+
* — and stores it with the same key, type and custom metadata, and fires the
|
|
46
|
+
* same triggers. So a refusal is thrown as the multipart route would have
|
|
47
|
+
* thrown it. A chunk that fails on the way — a dropped connection, a 5xx, a
|
|
48
|
+
* conflict over the offset — is retried from the offset the server reports.
|
|
49
|
+
*
|
|
50
|
+
* Answers `unavailable` when the resumable path cannot carry this file and
|
|
51
|
+
* the multipart one can: a server without the endpoint (or one too old to
|
|
52
|
+
* report the stored object), an upload another instance cannot see (several
|
|
53
|
+
* instances, no shared volume, no sticky sessions), or a chunk over the
|
|
54
|
+
* server's body limit.
|
|
55
|
+
*/
|
|
56
|
+
async function uploadResumable(options) {
|
|
57
|
+
const { file, send } = options;
|
|
58
|
+
const chunkSize = Math.max(1, options.chunkSize ?? RESUMABLE_UPLOAD_THRESHOLD);
|
|
59
|
+
const retryDelays = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
60
|
+
const tus = { "Tus-Resumable": "1.0.0" };
|
|
61
|
+
const created = await send("POST", "", {
|
|
62
|
+
...tus,
|
|
63
|
+
"Upload-Length": String(file.size),
|
|
64
|
+
"Upload-Metadata": Object.entries(options.metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`).join(",")
|
|
65
|
+
});
|
|
66
|
+
if (created.status === 404 || created.status === 405 || created.status === 501) return { unavailable: `the server has no resumable upload endpoint (${created.status})` };
|
|
67
|
+
if (created.status < 200 || created.status >= 300) throw created.error ?? /* @__PURE__ */ new Error(`The upload was refused (${created.status}).`);
|
|
68
|
+
const id = created.header("Location")?.split("?")[0].split("/").filter(Boolean).pop();
|
|
69
|
+
if (!id) return { unavailable: "the server did not say where the upload lives" };
|
|
70
|
+
const path = `/${encodeURIComponent(id)}`;
|
|
71
|
+
if (created.header("Rebase-Upload-Result") !== RESULT_ON_COMPLETE) {
|
|
72
|
+
await send("DELETE", path, tus).catch(() => void 0);
|
|
73
|
+
return { unavailable: "the server does not report the object a resumable upload stores" };
|
|
74
|
+
}
|
|
75
|
+
let offset = 0;
|
|
76
|
+
let lastFailure;
|
|
77
|
+
for (let attempt = 0;;) {
|
|
78
|
+
const end = Math.min(file.size, offset + chunkSize);
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await send("PATCH", path, {
|
|
82
|
+
...tus,
|
|
83
|
+
"Upload-Offset": String(offset),
|
|
84
|
+
"Content-Type": "application/offset+octet-stream"
|
|
85
|
+
}, file.slice(offset, end));
|
|
86
|
+
} catch (error) {
|
|
87
|
+
lastFailure = error instanceof Error ? error : new Error(String(error));
|
|
88
|
+
}
|
|
89
|
+
if (response && response.status >= 200 && response.status < 300) {
|
|
90
|
+
attempt = 0;
|
|
91
|
+
const reported = Number(response.header("Upload-Offset"));
|
|
92
|
+
offset = Number.isFinite(reported) && reported > offset ? reported : end;
|
|
93
|
+
if (offset < file.size) continue;
|
|
94
|
+
const stored = storedObjectOf(response.header("Rebase-Upload-Result"));
|
|
95
|
+
if (!stored) throw new Error("The upload finished, but the server did not say where it stored it.");
|
|
96
|
+
return { stored };
|
|
97
|
+
}
|
|
98
|
+
if (response?.status === 404) return { unavailable: "the server no longer knows this upload — another instance may have answered" };
|
|
99
|
+
if (response?.status === 413) {
|
|
100
|
+
await send("DELETE", path, tus).catch(() => void 0);
|
|
101
|
+
return { unavailable: "a chunk is over the server's request body limit" };
|
|
102
|
+
}
|
|
103
|
+
if (response && !isRetryable(response.status)) {
|
|
104
|
+
await send("DELETE", path, tus).catch(() => void 0);
|
|
105
|
+
throw response.error ?? /* @__PURE__ */ new Error(`The upload was refused (${response.status}).`);
|
|
106
|
+
}
|
|
107
|
+
if (response) lastFailure = response.error ?? /* @__PURE__ */ new Error(`The upload failed (${response.status}).`);
|
|
108
|
+
if (attempt >= retryDelays.length) throw lastFailure ?? /* @__PURE__ */ new Error("The upload failed.");
|
|
109
|
+
await sleep(retryDelays[attempt++]);
|
|
110
|
+
try {
|
|
111
|
+
const progress = await send("HEAD", path, tus);
|
|
112
|
+
if (progress.status === 404) return { unavailable: "the server no longer knows this upload — another instance may have answered" };
|
|
113
|
+
const held = Number(progress.header("Upload-Offset"));
|
|
114
|
+
if (progress.status >= 200 && progress.status < 300 && Number.isFinite(held)) offset = held;
|
|
115
|
+
} catch {}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
export { uploadResumable };
|
|
120
|
+
|
|
121
|
+
//# sourceMappingURL=resumable-upload.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resumable-upload.es.js","names":[],"sources":["../../src/util/resumable-upload.ts"],"sourcesContent":["import type { UploadFileResult } from \"@rebasepro/types\";\nimport { RESUMABLE_UPLOAD_THRESHOLD } from \"./resumable-upload-threshold\";\n\n/** One response, as the resumable upload reads it. */\nexport interface ResumableUploadResponse {\n status: number;\n header(name: string): string | null;\n /** The error a non-2xx response stands for, as the transport reports it. */\n error?: Error;\n}\n\n/**\n * Send one TUS request. `path` is `\"\"` for the creation request and\n * `/<upload id>` after it, relative to the source's `…/storage/tus` endpoint.\n * Answers every HTTP status; throws only when no response arrived.\n */\nexport type ResumableUploadSend = (\n method: \"POST\" | \"PATCH\" | \"HEAD\" | \"DELETE\",\n path: string,\n headers: Record<string, string>,\n body?: Blob\n) => Promise<ResumableUploadResponse>;\n\nexport interface ResumableUploadOptions {\n file: Blob;\n /** `Upload-Metadata` entries: `key`, `filename`, `filetype`, `bucket`, `storageId`, `collection`, `property`, `metadata_<name>`. */\n metadata: Record<string, string>;\n send: ResumableUploadSend;\n /** Bytes per `PATCH`. Default {@link RESUMABLE_UPLOAD_THRESHOLD}. */\n chunkSize?: number;\n /** How long to wait before each retry of a chunk; its length is the number of retries. */\n retryDelaysMs?: readonly number[];\n}\n\n/**\n * What a resumable upload came to: the stored object, or — for a reason the\n * multipart route does not share — nothing, and the caller sends the file\n * through `POST /storage/upload` instead.\n */\nexport type ResumableUploadOutcome =\n | { stored: UploadFileResult }\n | { unavailable: string };\n\n/** What `create` answers in `Rebase-Upload-Result` when the last `PATCH` will carry the stored object there. */\nconst RESULT_ON_COMPLETE = \"on-complete\";\nconst DEFAULT_RETRY_DELAYS_MS = [250, 1_000, 3_000];\n\n/** `value` as UTF-8, base64-encoded — what `Upload-Metadata` carries. */\nfunction base64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/** Worth asking for the offset and sending again: an offset conflict, a lock, a rate limit, a server fault. */\nconst isRetryable = (status: number) => status === 409 || status === 423 || status === 429 || status >= 500;\n\nconst sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/** The stored object a finished upload reports, or `null` when the header says nothing readable. */\nfunction storedObjectOf(header: string | null): UploadFileResult | null {\n if (!header) return null;\n let value: unknown;\n try {\n value = JSON.parse(decodeURIComponent(header));\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null) return null;\n const key = \"key\" in value ? value.key : undefined;\n const bucket = \"bucket\" in value ? value.bucket : undefined;\n const storageUrl = \"storageUrl\" in value ? value.storageUrl : undefined;\n if (typeof key !== \"string\" || typeof bucket !== \"string\" || typeof storageUrl !== \"string\") return null;\n return { key, bucket, storageUrl };\n}\n\n/**\n * Upload `file` through a Rebase server's TUS endpoint, one chunk at a time.\n *\n * The server holds every upload to what `POST /storage/upload` holds a file\n * to — the source's and the property's limits, the authorize hook, the bucket\n * — and stores it with the same key, type and custom metadata, and fires the\n * same triggers. So a refusal is thrown as the multipart route would have\n * thrown it. A chunk that fails on the way — a dropped connection, a 5xx, a\n * conflict over the offset — is retried from the offset the server reports.\n *\n * Answers `unavailable` when the resumable path cannot carry this file and\n * the multipart one can: a server without the endpoint (or one too old to\n * report the stored object), an upload another instance cannot see (several\n * instances, no shared volume, no sticky sessions), or a chunk over the\n * server's body limit.\n */\nexport async function uploadResumable(options: ResumableUploadOptions): Promise<ResumableUploadOutcome> {\n const { file, send } = options;\n const chunkSize = Math.max(1, options.chunkSize ?? RESUMABLE_UPLOAD_THRESHOLD);\n const retryDelays = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;\n const tus = { \"Tus-Resumable\": \"1.0.0\" };\n\n const created = await send(\"POST\", \"\", {\n ...tus,\n \"Upload-Length\": String(file.size),\n \"Upload-Metadata\": Object.entries(options.metadata)\n .map(([name, value]) => `${name} ${base64Utf8(value)}`)\n .join(\",\")\n });\n if (created.status === 404 || created.status === 405 || created.status === 501) {\n return { unavailable: `the server has no resumable upload endpoint (${created.status})` };\n }\n if (created.status < 200 || created.status >= 300) {\n throw created.error ?? new Error(`The upload was refused (${created.status}).`);\n }\n const id = created.header(\"Location\")?.split(\"?\")[0].split(\"/\").filter(Boolean).pop();\n if (!id) return { unavailable: \"the server did not say where the upload lives\" };\n const path = `/${encodeURIComponent(id)}`;\n if (created.header(\"Rebase-Upload-Result\") !== RESULT_ON_COMPLETE) {\n await send(\"DELETE\", path, tus).catch(() => undefined);\n return { unavailable: \"the server does not report the object a resumable upload stores\" };\n }\n\n let offset = 0;\n let lastFailure: Error | undefined;\n for (let attempt = 0; ;) {\n const end = Math.min(file.size, offset + chunkSize);\n let response: ResumableUploadResponse | undefined;\n try {\n response = await send(\"PATCH\", path, {\n ...tus,\n \"Upload-Offset\": String(offset),\n \"Content-Type\": \"application/offset+octet-stream\"\n }, file.slice(offset, end));\n } catch (error: unknown) {\n // No response: the connection dropped. Ask where the upload got to.\n lastFailure = error instanceof Error ? error : new Error(String(error));\n }\n\n if (response && response.status >= 200 && response.status < 300) {\n attempt = 0;\n const reported = Number(response.header(\"Upload-Offset\"));\n offset = Number.isFinite(reported) && reported > offset ? reported : end;\n if (offset < file.size) continue;\n const stored = storedObjectOf(response.header(\"Rebase-Upload-Result\"));\n if (!stored) throw new Error(\"The upload finished, but the server did not say where it stored it.\");\n return { stored };\n }\n if (response?.status === 404) {\n return { unavailable: \"the server no longer knows this upload — another instance may have answered\" };\n }\n if (response?.status === 413) {\n await send(\"DELETE\", path, tus).catch(() => undefined);\n return { unavailable: \"a chunk is over the server's request body limit\" };\n }\n if (response && !isRetryable(response.status)) {\n await send(\"DELETE\", path, tus).catch(() => undefined);\n throw response.error ?? new Error(`The upload was refused (${response.status}).`);\n }\n if (response) lastFailure = response.error ?? new Error(`The upload failed (${response.status}).`);\n\n if (attempt >= retryDelays.length) throw lastFailure ?? new Error(\"The upload failed.\");\n await sleep(retryDelays[attempt++]);\n // Resume from what the server holds, which may be more than was\n // acknowledged (the chunk arrived, its answer did not) or less.\n try {\n const progress = await send(\"HEAD\", path, tus);\n if (progress.status === 404) {\n return { unavailable: \"the server no longer knows this upload — another instance may have answered\" };\n }\n const held = Number(progress.header(\"Upload-Offset\"));\n if (progress.status >= 200 && progress.status < 300 && Number.isFinite(held)) offset = held;\n } catch {\n // Still no connection: the next attempt asks again.\n }\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL a person ran, as the audit log may keep it: every string literal masked.
|
|
3
|
+
*
|
|
4
|
+
* The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app
|
|
5
|
+
* PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and
|
|
6
|
+
* `dblink_connect('host=db password=hunter2')` put the password in the
|
|
7
|
+
* production logs, where the logger's redaction — by key name — never looks.
|
|
8
|
+
*
|
|
9
|
+
* A literal is a value the statement carries inline, which is exactly what the
|
|
10
|
+
* line already declines to write when it is bound as a parameter: the
|
|
11
|
+
* statement's shape is the audit signal, the values are whatever the operator
|
|
12
|
+
* was touching. So every literal goes, not only the ones beside a word that
|
|
13
|
+
* looks like `password` — a secret has no reliable neighbour. Identifiers,
|
|
14
|
+
* keywords, numbers and comments stay.
|
|
15
|
+
*
|
|
16
|
+
* Read with Postgres's own lexical rules, not a regular expression over the
|
|
17
|
+
* text: a quote inside a comment, a doubled quote, an `E'…\'…'` escape or a
|
|
18
|
+
* `$tag$` body must not shift where a literal is thought to end, or the mask
|
|
19
|
+
* covers the statement and leaves the secret.
|
|
20
|
+
*/
|
|
21
|
+
export declare function redactSqlLiterals(sql: string): string;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
//#region src/util/sql-redaction.ts
|
|
2
|
+
/**
|
|
3
|
+
* SQL a person ran, as the audit log may keep it: every string literal masked.
|
|
4
|
+
*
|
|
5
|
+
* The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app
|
|
6
|
+
* PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and
|
|
7
|
+
* `dblink_connect('host=db password=hunter2')` put the password in the
|
|
8
|
+
* production logs, where the logger's redaction — by key name — never looks.
|
|
9
|
+
*
|
|
10
|
+
* A literal is a value the statement carries inline, which is exactly what the
|
|
11
|
+
* line already declines to write when it is bound as a parameter: the
|
|
12
|
+
* statement's shape is the audit signal, the values are whatever the operator
|
|
13
|
+
* was touching. So every literal goes, not only the ones beside a word that
|
|
14
|
+
* looks like `password` — a secret has no reliable neighbour. Identifiers,
|
|
15
|
+
* keywords, numbers and comments stay.
|
|
16
|
+
*
|
|
17
|
+
* Read with Postgres's own lexical rules, not a regular expression over the
|
|
18
|
+
* text: a quote inside a comment, a doubled quote, an `E'…\'…'` escape or a
|
|
19
|
+
* `$tag$` body must not shift where a literal is thought to end, or the mask
|
|
20
|
+
* covers the statement and leaves the secret.
|
|
21
|
+
*/
|
|
22
|
+
function redactSqlLiterals(sql) {
|
|
23
|
+
let out = "";
|
|
24
|
+
let i = 0;
|
|
25
|
+
while (i < sql.length) {
|
|
26
|
+
const char = sql[i];
|
|
27
|
+
const next = sql[i + 1];
|
|
28
|
+
if (char === "-" && next === "-") {
|
|
29
|
+
const end = sql.indexOf("\n", i);
|
|
30
|
+
const stop = end === -1 ? sql.length : end;
|
|
31
|
+
out += sql.slice(i, stop);
|
|
32
|
+
i = stop;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (char === "/" && next === "*") {
|
|
36
|
+
let depth = 1;
|
|
37
|
+
let j = i + 2;
|
|
38
|
+
while (j < sql.length && depth > 0) if (sql[j] === "/" && sql[j + 1] === "*") {
|
|
39
|
+
depth++;
|
|
40
|
+
j += 2;
|
|
41
|
+
} else if (sql[j] === "*" && sql[j + 1] === "/") {
|
|
42
|
+
depth--;
|
|
43
|
+
j += 2;
|
|
44
|
+
} else j++;
|
|
45
|
+
out += sql.slice(i, j);
|
|
46
|
+
i = j;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (char === "\"") {
|
|
50
|
+
const end = closingQuote(sql, i + 1, "\"", false);
|
|
51
|
+
out += sql.slice(i, end);
|
|
52
|
+
i = end;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (char === "'") {
|
|
56
|
+
const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? "";
|
|
57
|
+
out += "'***'";
|
|
58
|
+
i = closingQuote(sql, i + 1, "'", prefix.toUpperCase() === "E");
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (char === "$") {
|
|
62
|
+
const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
|
|
63
|
+
const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);
|
|
64
|
+
if (tag && !precededByIdentifier) {
|
|
65
|
+
const delimiter = tag[0];
|
|
66
|
+
const bodyStart = i + delimiter.length;
|
|
67
|
+
const bodyEnd = sql.indexOf(delimiter, bodyStart);
|
|
68
|
+
const stop = bodyEnd === -1 ? sql.length : bodyEnd;
|
|
69
|
+
const body = sql.slice(bodyStart, stop);
|
|
70
|
+
const isPassword = /\bpassword\s*$/i.test(out);
|
|
71
|
+
out += delimiter + (isPassword ? "***" : redactSqlLiterals(body)) + (bodyEnd === -1 ? "" : delimiter);
|
|
72
|
+
i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
out += char;
|
|
77
|
+
i++;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The index just past the quote that closes a literal or identifier opened
|
|
83
|
+
* before `from`. A doubled quote is one quote inside it; with `backslashEscapes`
|
|
84
|
+
* (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.
|
|
85
|
+
*/
|
|
86
|
+
function closingQuote(sql, from, quote, backslashEscapes) {
|
|
87
|
+
let j = from;
|
|
88
|
+
while (j < sql.length) {
|
|
89
|
+
if (backslashEscapes && sql[j] === "\\") {
|
|
90
|
+
j += 2;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (sql[j] === quote) {
|
|
94
|
+
if (sql[j + 1] === quote) {
|
|
95
|
+
j += 2;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
return j + 1;
|
|
99
|
+
}
|
|
100
|
+
j++;
|
|
101
|
+
}
|
|
102
|
+
return sql.length;
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
export { redactSqlLiterals };
|
|
106
|
+
|
|
107
|
+
//# sourceMappingURL=sql-redaction.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-redaction.es.js","names":[],"sources":["../../src/util/sql-redaction.ts"],"sourcesContent":["/**\n * SQL a person ran, as the audit log may keep it: every string literal masked.\n *\n * The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app\n * PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and\n * `dblink_connect('host=db password=hunter2')` put the password in the\n * production logs, where the logger's redaction — by key name — never looks.\n *\n * A literal is a value the statement carries inline, which is exactly what the\n * line already declines to write when it is bound as a parameter: the\n * statement's shape is the audit signal, the values are whatever the operator\n * was touching. So every literal goes, not only the ones beside a word that\n * looks like `password` — a secret has no reliable neighbour. Identifiers,\n * keywords, numbers and comments stay.\n *\n * Read with Postgres's own lexical rules, not a regular expression over the\n * text: a quote inside a comment, a doubled quote, an `E'…\\'…'` escape or a\n * `$tag$` body must not shift where a literal is thought to end, or the mask\n * covers the statement and leaves the secret.\n */\nexport function redactSqlLiterals(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const char = sql[i];\n const next = sql[i + 1];\n\n // -- line comment\n if (char === \"-\" && next === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n const stop = end === -1 ? sql.length : end;\n out += sql.slice(i, stop);\n i = stop;\n continue;\n }\n\n // /* block comment */ — nested, as Postgres reads them\n if (char === \"/\" && next === \"*\") {\n let depth = 1;\n let j = i + 2;\n while (j < sql.length && depth > 0) {\n if (sql[j] === \"/\" && sql[j + 1] === \"*\") { depth++; j += 2; } else if (sql[j] === \"*\" && sql[j + 1] === \"/\") { depth--; j += 2; } else j++;\n }\n out += sql.slice(i, j);\n i = j;\n continue;\n }\n\n // \"quoted identifier\"\n if (char === \"\\\"\") {\n const end = closingQuote(sql, i + 1, \"\\\"\", false);\n out += sql.slice(i, end);\n i = end;\n continue;\n }\n\n // 'string', E'string' with backslash escapes, and the B'', X'', N'',\n // U&'' prefixes — the prefix is kept, the content masked.\n if (char === \"'\") {\n const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? \"\";\n out += \"'***'\";\n i = closingQuote(sql, i + 1, \"'\", prefix.toUpperCase() === \"E\");\n continue;\n }\n\n // $tag$ … $tag$ — a dollar-quoted string. A function or DO body is SQL\n // in its own right, and its literals are masked as these are; a\n // password written as `PASSWORD $$hunter2$$` is masked whole.\n if (char === \"$\") {\n const tag = /^\\$([A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sql.slice(i));\n const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);\n if (tag && !precededByIdentifier) {\n const delimiter = tag[0];\n const bodyStart = i + delimiter.length;\n const bodyEnd = sql.indexOf(delimiter, bodyStart);\n const stop = bodyEnd === -1 ? sql.length : bodyEnd;\n const body = sql.slice(bodyStart, stop);\n const isPassword = /\\bpassword\\s*$/i.test(out);\n out += delimiter + (isPassword ? \"***\" : redactSqlLiterals(body)) + (bodyEnd === -1 ? \"\" : delimiter);\n i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;\n continue;\n }\n }\n\n out += char;\n i++;\n }\n return out;\n}\n\n/**\n * The index just past the quote that closes a literal or identifier opened\n * before `from`. A doubled quote is one quote inside it; with `backslashEscapes`\n * (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.\n */\nfunction closingQuote(sql: string, from: number, quote: string, backslashEscapes: boolean): number {\n let j = from;\n while (j < sql.length) {\n if (backslashEscapes && sql[j] === \"\\\\\") { j += 2; continue; }\n if (sql[j] === quote) {\n if (sql[j + 1] === quote) { j += 2; continue; }\n return j + 1;\n }\n j++;\n }\n return sql.length;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBAAkB,KAAqB;CACnD,IAAI,MAAM;CACV,IAAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACnB,MAAM,OAAO,IAAI;EACjB,MAAM,OAAO,IAAI,IAAI;EAGrB,IAAI,SAAS,OAAO,SAAS,KAAK;GAC9B,MAAM,MAAM,IAAI,QAAQ,MAAM,CAAC;GAC/B,MAAM,OAAO,QAAQ,KAAK,IAAI,SAAS;GACvC,OAAO,IAAI,MAAM,GAAG,IAAI;GACxB,IAAI;GACJ;EACJ;EAGA,IAAI,SAAS,OAAO,SAAS,KAAK;GAC9B,IAAI,QAAQ;GACZ,IAAI,IAAI,IAAI;GACZ,OAAO,IAAI,IAAI,UAAU,QAAQ,GAC7B,IAAI,IAAI,OAAO,OAAO,IAAI,IAAI,OAAO,KAAK;IAAE;IAAS,KAAK;GAAG,OAAO,IAAI,IAAI,OAAO,OAAO,IAAI,IAAI,OAAO,KAAK;IAAE;IAAS,KAAK;GAAG,OAAO;GAE5I,OAAO,IAAI,MAAM,GAAG,CAAC;GACrB,IAAI;GACJ;EACJ;EAGA,IAAI,SAAS,MAAM;GACf,MAAM,MAAM,aAAa,KAAK,IAAI,GAAG,MAAM,KAAK;GAChD,OAAO,IAAI,MAAM,GAAG,GAAG;GACvB,IAAI;GACJ;EACJ;EAIA,IAAI,SAAS,KAAK;GACd,MAAM,SAAS,0CAA0C,KAAK,GAAG,CAAC,GAAG,MAAM;GAC3E,OAAO;GACP,IAAI,aAAa,KAAK,IAAI,GAAG,KAAK,OAAO,YAAY,MAAM,GAAG;GAC9D;EACJ;EAKA,IAAI,SAAS,KAAK;GACd,MAAM,MAAM,iCAAiC,KAAK,IAAI,MAAM,CAAC,CAAC;GAC9D,MAAM,uBAAuB,gBAAgB,KAAK,GAAG;GACrD,IAAI,OAAO,CAAC,sBAAsB;IAC9B,MAAM,YAAY,IAAI;IACtB,MAAM,YAAY,IAAI,UAAU;IAChC,MAAM,UAAU,IAAI,QAAQ,WAAW,SAAS;IAChD,MAAM,OAAO,YAAY,KAAK,IAAI,SAAS;IAC3C,MAAM,OAAO,IAAI,MAAM,WAAW,IAAI;IACtC,MAAM,aAAa,kBAAkB,KAAK,GAAG;IAC7C,OAAO,aAAa,aAAa,QAAQ,kBAAkB,IAAI,MAAM,YAAY,KAAK,KAAK;IAC3F,IAAI,YAAY,KAAK,IAAI,SAAS,UAAU,UAAU;IACtD;GACJ;EACJ;EAEA,OAAO;EACP;CACJ;CACA,OAAO;AACX;;;;;;AAOA,SAAS,aAAa,KAAa,MAAc,OAAe,kBAAmC;CAC/F,IAAI,IAAI;CACR,OAAO,IAAI,IAAI,QAAQ;EACnB,IAAI,oBAAoB,IAAI,OAAO,MAAM;GAAE,KAAK;GAAG;EAAU;EAC7D,IAAI,IAAI,OAAO,OAAO;GAClB,IAAI,IAAI,IAAI,OAAO,OAAO;IAAE,KAAK;IAAG;GAAU;GAC9C,OAAO,IAAI;EACf;EACA;CACJ;CACA,OAAO,IAAI;AACf"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/util/sql-rows.ts
|
|
2
|
+
/**
|
|
3
|
+
* Read the rows out of whatever a SQL driver actually returned.
|
|
4
|
+
*
|
|
5
|
+
* Two shapes reach this repository's stores through the same call, and which
|
|
6
|
+
* one arrives is a property of the driver rather than of the query:
|
|
7
|
+
* node-postgres hands back a `{ rows }` envelope, and the other paths — a bare
|
|
8
|
+
* `executeSql`, Drizzle's `db.execute()` on some builds — hand back an array.
|
|
9
|
+
* `@rebasepro/server`'s `SqlExec` type declares the array, so the envelope is
|
|
10
|
+
* off-contract every time it turns up, and it still turns up.
|
|
11
|
+
*
|
|
12
|
+
* Reading one shape only is how a store silently sees nothing: the rate limiter
|
|
13
|
+
* that did it counted every caller as being on their first request — a limiter
|
|
14
|
+
* that never limits, with no error anywhere to say so.
|
|
15
|
+
*
|
|
16
|
+
* Written inline it came to `result as unknown as { rows?: T[] } | T[]`, five
|
|
17
|
+
* times across three packages. That is the problem restated as an assertion: a
|
|
18
|
+
* union the caller has to re-test at runtime anyway, with `unknown` in the
|
|
19
|
+
* middle only because neither half overlaps what the signature promised. The
|
|
20
|
+
* `Array.isArray` below is that same test done once, and it *narrows* — so
|
|
21
|
+
* these branches are checked rather than claimed.
|
|
22
|
+
*
|
|
23
|
+
* The element type is the one claim that stays a claim: these are rows from
|
|
24
|
+
* hand-written SQL, and nothing at this layer can check a column list.
|
|
25
|
+
*/
|
|
26
|
+
function sqlRows(result) {
|
|
27
|
+
if (Array.isArray(result)) return result;
|
|
28
|
+
if (result !== null && typeof result === "object") {
|
|
29
|
+
const rows = result.rows;
|
|
30
|
+
if (Array.isArray(rows)) return rows;
|
|
31
|
+
}
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
/** The first row of {@link sqlRows}, or `undefined` when there were none. */
|
|
35
|
+
function firstSqlRow(result) {
|
|
36
|
+
return sqlRows(result)[0];
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
export { firstSqlRow, sqlRows };
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=sql-rows.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-rows.es.js","names":[],"sources":["../../src/util/sql-rows.ts"],"sourcesContent":["/**\n * Read the rows out of whatever a SQL driver actually returned.\n *\n * Two shapes reach this repository's stores through the same call, and which\n * one arrives is a property of the driver rather than of the query:\n * node-postgres hands back a `{ rows }` envelope, and the other paths — a bare\n * `executeSql`, Drizzle's `db.execute()` on some builds — hand back an array.\n * `@rebasepro/server`'s `SqlExec` type declares the array, so the envelope is\n * off-contract every time it turns up, and it still turns up.\n *\n * Reading one shape only is how a store silently sees nothing: the rate limiter\n * that did it counted every caller as being on their first request — a limiter\n * that never limits, with no error anywhere to say so.\n *\n * Written inline it came to `result as unknown as { rows?: T[] } | T[]`, five\n * times across three packages. That is the problem restated as an assertion: a\n * union the caller has to re-test at runtime anyway, with `unknown` in the\n * middle only because neither half overlaps what the signature promised. The\n * `Array.isArray` below is that same test done once, and it *narrows* — so\n * these branches are checked rather than claimed.\n *\n * The element type is the one claim that stays a claim: these are rows from\n * hand-written SQL, and nothing at this layer can check a column list.\n */\nexport function sqlRows<T = Record<string, unknown>>(result: unknown): T[] {\n if (Array.isArray(result)) return result as T[];\n if (result !== null && typeof result === \"object\") {\n const rows = (result as { rows?: unknown }).rows;\n if (Array.isArray(rows)) return rows as T[];\n }\n return [];\n}\n\n/** The first row of {@link sqlRows}, or `undefined` when there were none. */\nexport function firstSqlRow<T = Record<string, unknown>>(result: unknown): T | undefined {\n return sqlRows<T>(result)[0];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,QAAqC,QAAsB;CACvE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;EAC/C,MAAM,OAAQ,OAA8B;EAC5C,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO;CACpC;CACA,OAAO,CAAC;AACZ;;AAGA,SAAgB,YAAyC,QAAgC;CACrF,OAAO,QAAW,MAAM,CAAC,CAAC;AAC9B"}
|
package/dist/util/storage.d.ts
CHANGED
|
@@ -4,10 +4,20 @@ import { ArrayProperty, EntityValues, StorageConfig, StorageSource, StorageSourc
|
|
|
4
4
|
* referenced by `StorageConfig.storageSource`.
|
|
5
5
|
*
|
|
6
6
|
* Resolution priority:
|
|
7
|
-
* 1. No `sourceKey` → the default source
|
|
8
|
-
* 2. An explicit {@link StorageSourceRegistry} (e.g. `client.storageRegistry`).
|
|
7
|
+
* 1. No `sourceKey` → the default source.
|
|
8
|
+
* 2. An explicit {@link StorageSourceRegistry} that has the key (e.g. `client.storageRegistry`).
|
|
9
9
|
* 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).
|
|
10
|
-
* 4.
|
|
10
|
+
* 4. `(default)` → the default source.
|
|
11
|
+
* 5. `createSource(key)` — a server-routed source carrying `storageId`, so the
|
|
12
|
+
* server decides: it serves the source, or answers 400/501 naming it.
|
|
13
|
+
* 6. Otherwise a source that refuses every call, naming the key.
|
|
14
|
+
*
|
|
15
|
+
* Never the default source for a key that names another. It used to be: a
|
|
16
|
+
* named source enters the panel's map only once `GET /storage/sources` has
|
|
17
|
+
* answered, so one failed fetch (or a typo, or a `direct` source the app did
|
|
18
|
+
* not pass) silently uploaded the property's files into the default bucket —
|
|
19
|
+
* with the authorize hook asked about `(default)` and the preview looking in
|
|
20
|
+
* the wrong place. The server stopped falling back for the same reason.
|
|
11
21
|
*
|
|
12
22
|
* Shared by the upload hook, the markdown editor, and the read-only previews
|
|
13
23
|
* so the resolution logic lives in one place.
|
|
@@ -21,9 +31,21 @@ export declare function resolveStorageSource(params: {
|
|
|
21
31
|
sources?: Record<string, StorageSource>;
|
|
22
32
|
/** Optional explicit registry — takes precedence over `sources`. */
|
|
23
33
|
registry?: StorageSourceRegistry;
|
|
24
|
-
/** Default source, used when no key is set
|
|
34
|
+
/** Default source, used when no key is set. */
|
|
25
35
|
defaultSource: StorageSource;
|
|
36
|
+
/**
|
|
37
|
+
* Builds a server-routed source for a key nothing else resolves
|
|
38
|
+
* (`client.createStorageSource`).
|
|
39
|
+
*/
|
|
40
|
+
createSource?: (key: string) => StorageSource;
|
|
26
41
|
}): StorageSource;
|
|
42
|
+
/**
|
|
43
|
+
* A storage source for a key this app cannot reach: every call fails, naming
|
|
44
|
+
* the key — so an upload is refused instead of landing in another bucket.
|
|
45
|
+
*
|
|
46
|
+
* @group Storage
|
|
47
|
+
*/
|
|
48
|
+
export declare function unavailableStorageSource(key: string): StorageSource;
|
|
27
49
|
interface ResolveFilenameStringParams<M extends Record<string, unknown>> {
|
|
28
50
|
input: string | ((context: UploadedFileContext) => (Promise<string> | string));
|
|
29
51
|
storage: StorageConfig;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { DEFAULT_STORAGE_SOURCE_KEY } from "@rebasepro/types";
|
|
2
|
+
import { randomString } from "@rebasepro/utils";
|
|
3
|
+
//#region src/util/storage.ts
|
|
4
|
+
/**
|
|
5
|
+
* Resolve the {@link StorageSource} to use for a property, given the key
|
|
6
|
+
* referenced by `StorageConfig.storageSource`.
|
|
7
|
+
*
|
|
8
|
+
* Resolution priority:
|
|
9
|
+
* 1. No `sourceKey` → the default source.
|
|
10
|
+
* 2. An explicit {@link StorageSourceRegistry} that has the key (e.g. `client.storageRegistry`).
|
|
11
|
+
* 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).
|
|
12
|
+
* 4. `(default)` → the default source.
|
|
13
|
+
* 5. `createSource(key)` — a server-routed source carrying `storageId`, so the
|
|
14
|
+
* server decides: it serves the source, or answers 400/501 naming it.
|
|
15
|
+
* 6. Otherwise a source that refuses every call, naming the key.
|
|
16
|
+
*
|
|
17
|
+
* Never the default source for a key that names another. It used to be: a
|
|
18
|
+
* named source enters the panel's map only once `GET /storage/sources` has
|
|
19
|
+
* answered, so one failed fetch (or a typo, or a `direct` source the app did
|
|
20
|
+
* not pass) silently uploaded the property's files into the default bucket —
|
|
21
|
+
* with the authorize hook asked about `(default)` and the preview looking in
|
|
22
|
+
* the wrong place. The server stopped falling back for the same reason.
|
|
23
|
+
*
|
|
24
|
+
* Shared by the upload hook, the markdown editor, and the read-only previews
|
|
25
|
+
* so the resolution logic lives in one place.
|
|
26
|
+
*
|
|
27
|
+
* @group Storage
|
|
28
|
+
*/
|
|
29
|
+
function resolveStorageSource(params) {
|
|
30
|
+
const { sourceKey, sources, registry, defaultSource, createSource } = params;
|
|
31
|
+
if (!sourceKey) return defaultSource;
|
|
32
|
+
if (registry?.has(sourceKey)) return registry.getOrDefault(sourceKey);
|
|
33
|
+
const fromSources = sources?.[sourceKey];
|
|
34
|
+
if (fromSources) return fromSources;
|
|
35
|
+
if (sourceKey === DEFAULT_STORAGE_SOURCE_KEY) return defaultSource;
|
|
36
|
+
if (createSource) return createSource(sourceKey);
|
|
37
|
+
return unavailableStorageSource(sourceKey);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A storage source for a key this app cannot reach: every call fails, naming
|
|
41
|
+
* the key — so an upload is refused instead of landing in another bucket.
|
|
42
|
+
*
|
|
43
|
+
* @group Storage
|
|
44
|
+
*/
|
|
45
|
+
function unavailableStorageSource(key) {
|
|
46
|
+
const refuse = () => Promise.reject(/* @__PURE__ */ new Error(`Storage source "${key}" is not available in this app. Check the property's \`storageSource\`, that the backend serves it (GET /api/storage/sources), and that a \`direct\` source is passed to <Rebase storageSources>.`));
|
|
47
|
+
return {
|
|
48
|
+
putObject: refuse,
|
|
49
|
+
getSignedUrl: refuse,
|
|
50
|
+
getObject: refuse,
|
|
51
|
+
deleteObject: refuse,
|
|
52
|
+
listObjects: refuse
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async function resolveStorageFilenameString({ input, storage, values, entityId, path, property, file, propertyKey }) {
|
|
56
|
+
let result;
|
|
57
|
+
if (typeof input === "function") {
|
|
58
|
+
result = await input({
|
|
59
|
+
path,
|
|
60
|
+
entityId,
|
|
61
|
+
values,
|
|
62
|
+
property,
|
|
63
|
+
file,
|
|
64
|
+
storage,
|
|
65
|
+
propertyKey
|
|
66
|
+
});
|
|
67
|
+
if (!result) console.warn("Storage callback returned empty result. Using default name value");
|
|
68
|
+
} else result = replacePlaceholders({
|
|
69
|
+
file,
|
|
70
|
+
input,
|
|
71
|
+
entityId,
|
|
72
|
+
propertyKey,
|
|
73
|
+
path
|
|
74
|
+
});
|
|
75
|
+
if (!result) result = randomString() + "_" + file.name;
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
function resolveStoragePathString({ input, storage, values, entityId, path, property, file, propertyKey }) {
|
|
79
|
+
let result;
|
|
80
|
+
if (typeof input === "function") {
|
|
81
|
+
result = input({
|
|
82
|
+
path,
|
|
83
|
+
entityId,
|
|
84
|
+
values,
|
|
85
|
+
property,
|
|
86
|
+
file,
|
|
87
|
+
storage,
|
|
88
|
+
propertyKey
|
|
89
|
+
});
|
|
90
|
+
if (!result) console.warn("Storage callback returned empty result. Using default name value");
|
|
91
|
+
} else result = replacePlaceholders({
|
|
92
|
+
file,
|
|
93
|
+
input,
|
|
94
|
+
entityId,
|
|
95
|
+
propertyKey,
|
|
96
|
+
path
|
|
97
|
+
});
|
|
98
|
+
if (!result) result = randomString() + "_" + file.name;
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
function replacePlaceholders({ file, input, entityId, propertyKey, path }) {
|
|
102
|
+
const ext = file.name.split(".").pop();
|
|
103
|
+
let result = input.replace("{propertyKey}", propertyKey).replace("{rand}", randomString()).replace("{file}", file.name).replace("{file.type}", file.type);
|
|
104
|
+
if (entityId) result = result.replace("{entityId}", String(entityId));
|
|
105
|
+
if (path) result = result.replace("{path}", path);
|
|
106
|
+
if (ext) {
|
|
107
|
+
result = result.replace("{file.ext}", ext);
|
|
108
|
+
const name = file.name.replace(`.${ext}`, "");
|
|
109
|
+
result = result.replace("{file.name}", name);
|
|
110
|
+
}
|
|
111
|
+
if (!result) result = randomString() + "_" + file.name;
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
export { resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, unavailableStorageSource };
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=storage.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.es.js","names":[],"sources":["../../src/util/storage.ts"],"sourcesContent":["import { ArrayProperty, DEFAULT_STORAGE_SOURCE_KEY, EntityValues, StorageConfig, StorageSource, StorageSourceRegistry, StringProperty, UploadedFileContext } from \"@rebasepro/types\";\nimport { randomString } from \"@rebasepro/utils\";\n\n/**\n * Resolve the {@link StorageSource} to use for a property, given the key\n * referenced by `StorageConfig.storageSource`.\n *\n * Resolution priority:\n * 1. No `sourceKey` → the default source.\n * 2. An explicit {@link StorageSourceRegistry} that has the key (e.g. `client.storageRegistry`).\n * 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).\n * 4. `(default)` → the default source.\n * 5. `createSource(key)` — a server-routed source carrying `storageId`, so the\n * server decides: it serves the source, or answers 400/501 naming it.\n * 6. Otherwise a source that refuses every call, naming the key.\n *\n * Never the default source for a key that names another. It used to be: a\n * named source enters the panel's map only once `GET /storage/sources` has\n * answered, so one failed fetch (or a typo, or a `direct` source the app did\n * not pass) silently uploaded the property's files into the default bucket —\n * with the authorize hook asked about `(default)` and the preview looking in\n * the wrong place. The server stopped falling back for the same reason.\n *\n * Shared by the upload hook, the markdown editor, and the read-only previews\n * so the resolution logic lives in one place.\n *\n * @group Storage\n */\nexport function resolveStorageSource(params: {\n /** Key from `StorageConfig.storageSource`. */\n sourceKey?: string | null;\n /** Built sources keyed by storage-source key (e.g. from context). */\n sources?: Record<string, StorageSource>;\n /** Optional explicit registry — takes precedence over `sources`. */\n registry?: StorageSourceRegistry;\n /** Default source, used when no key is set. */\n defaultSource: StorageSource;\n /**\n * Builds a server-routed source for a key nothing else resolves\n * (`client.createStorageSource`).\n */\n createSource?: (key: string) => StorageSource;\n}): StorageSource {\n const { sourceKey, sources, registry, defaultSource, createSource } = params;\n if (!sourceKey) return defaultSource;\n if (registry?.has(sourceKey)) return registry.getOrDefault(sourceKey);\n const fromSources = sources?.[sourceKey];\n if (fromSources) return fromSources;\n if (sourceKey === DEFAULT_STORAGE_SOURCE_KEY) return defaultSource;\n if (createSource) return createSource(sourceKey);\n return unavailableStorageSource(sourceKey);\n}\n\n/**\n * A storage source for a key this app cannot reach: every call fails, naming\n * the key — so an upload is refused instead of landing in another bucket.\n *\n * @group Storage\n */\nexport function unavailableStorageSource(key: string): StorageSource {\n const refuse = (): Promise<never> => Promise.reject(new Error(\n `Storage source \"${key}\" is not available in this app. Check the property's ` +\n \"`storageSource`, that the backend serves it (GET /api/storage/sources), and that a \" +\n \"`direct` source is passed to <Rebase storageSources>.\"\n ));\n return {\n putObject: refuse,\n getSignedUrl: refuse,\n getObject: refuse,\n deleteObject: refuse,\n listObjects: refuse\n };\n}\n\ninterface ResolveFilenameStringParams<M extends Record<string, unknown>> {\n input: string | ((context: UploadedFileContext) => (Promise<string> | string));\n storage: StorageConfig;\n values: EntityValues<M>;\n entityId?: string | number;\n path?: string;\n property: StringProperty | ArrayProperty,\n file: File;\n propertyKey: string;\n}\n\nexport async function resolveStorageFilenameString<M extends Record<string, unknown>>(\n {\n input,\n storage,\n values,\n entityId,\n path,\n property,\n file,\n propertyKey\n }: ResolveFilenameStringParams<M>): Promise<string> {\n let result;\n\n if (typeof input === \"function\") {\n result = await input({\n path,\n entityId,\n values,\n property,\n file,\n storage,\n propertyKey\n });\n if (!result)\n console.warn(\"Storage callback returned empty result. Using default name value\")\n } else {\n result = replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n });\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n\ninterface ResolveStoragePathStringParams<M extends Record<string, unknown>> {\n input: string | ((context: UploadedFileContext) => string);\n storage: StorageConfig;\n values: EntityValues<M>;\n entityId?: string | number;\n path?: string;\n property: StringProperty | ArrayProperty;\n file: File;\n propertyKey: string;\n}\n\nexport function resolveStoragePathString<M extends Record<string, unknown>>(\n {\n input,\n storage,\n values,\n entityId,\n path,\n property,\n file,\n propertyKey\n }: ResolveStoragePathStringParams<M>): string {\n let result;\n if (typeof input === \"function\") {\n result = input({\n path,\n entityId,\n values,\n property,\n file,\n storage,\n propertyKey\n });\n if (!result)\n console.warn(\"Storage callback returned empty result. Using default name value\")\n } else {\n result = replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n });\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n\ninterface Placeholders {\n file: File;\n input: string;\n entityId?: string | number;\n propertyKey: string;\n path?: string;\n}\n\nfunction replacePlaceholders({\n file,\n input,\n entityId,\n propertyKey,\n path\n}: Placeholders) {\n const ext = file.name.split(\".\").pop();\n let result = input\n .replace(\"{propertyKey}\", propertyKey)\n .replace(\"{rand}\", randomString())\n .replace(\"{file}\", file.name)\n .replace(\"{file.type}\", file.type);\n if (entityId) {\n result = result.replace(\"{entityId}\", String(entityId));\n }\n if (path) {\n result = result.replace(\"{path}\", path);\n }\n if (ext) {\n result = result.replace(\"{file.ext}\", ext);\n const name = file.name.replace(`.${ext}`, \"\");\n result = result.replace(\"{file.name}\", name)\n }\n\n if (!result)\n result = randomString() + \"_\" + file.name;\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,qBAAqB,QAcnB;CACd,MAAM,EAAE,WAAW,SAAS,UAAU,eAAe,iBAAiB;CACtE,IAAI,CAAC,WAAW,OAAO;CACvB,IAAI,UAAU,IAAI,SAAS,GAAG,OAAO,SAAS,aAAa,SAAS;CACpE,MAAM,cAAc,UAAU;CAC9B,IAAI,aAAa,OAAO;CACxB,IAAI,cAAc,4BAA4B,OAAO;CACrD,IAAI,cAAc,OAAO,aAAa,SAAS;CAC/C,OAAO,yBAAyB,SAAS;AAC7C;;;;;;;AAQA,SAAgB,yBAAyB,KAA4B;CACjE,MAAM,eAA+B,QAAQ,uBAAO,IAAI,MACpD,mBAAmB,IAAI,kMAG3B,CAAC;CACD,OAAO;EACH,WAAW;EACX,cAAc;EACd,WAAW;EACX,cAAc;EACd,aAAa;CACjB;AACJ;AAaA,eAAsB,6BAClB,EACI,OACA,SACA,QACA,UACA,MACA,UACA,MACA,eACgD;CACpD,IAAI;CAEJ,IAAI,OAAO,UAAU,YAAY;EAC7B,SAAS,MAAM,MAAM;GACjB;GACA;GACA;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,IAAI,CAAC,QACD,QAAQ,KAAK,kEAAkE;CACvF,OACI,SAAS,oBAAoB;EACzB;EACA;EACA;EACA;EACA;CACJ,CAAC;CAGL,IAAI,CAAC,QACD,SAAS,aAAa,IAAI,MAAM,KAAK;CAEzC,OAAO;AACX;AAaA,SAAgB,yBACZ,EACI,OACA,SACA,QACA,UACA,MACA,UACA,MACA,eAC0C;CAC9C,IAAI;CACJ,IAAI,OAAO,UAAU,YAAY;EAC7B,SAAS,MAAM;GACX;GACA;GACA;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,IAAI,CAAC,QACD,QAAQ,KAAK,kEAAkE;CACvF,OACI,SAAS,oBAAoB;EACzB;EACA;EACA;EACA;EACA;CACJ,CAAC;CAGL,IAAI,CAAC,QACD,SAAS,aAAa,IAAI,MAAM,KAAK;CAEzC,OAAO;AACX;AAUA,SAAS,oBAAoB,EACzB,MACA,OACA,UACA,aACA,QACa;CACb,MAAM,MAAM,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI;CACrC,IAAI,SAAS,MACR,QAAQ,iBAAiB,WAAW,CAAC,CACrC,QAAQ,UAAU,aAAa,CAAC,CAAC,CACjC,QAAQ,UAAU,KAAK,IAAI,CAAC,CAC5B,QAAQ,eAAe,KAAK,IAAI;CACrC,IAAI,UACA,SAAS,OAAO,QAAQ,cAAc,OAAO,QAAQ,CAAC;CAE1D,IAAI,MACA,SAAS,OAAO,QAAQ,UAAU,IAAI;CAE1C,IAAI,KAAK;EACL,SAAS,OAAO,QAAQ,cAAc,GAAG;EACzC,MAAM,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,EAAE;EAC5C,SAAS,OAAO,QAAQ,eAAe,IAAI;CAC/C;CAEA,IAAI,CAAC,QACD,SAAS,aAAa,IAAI,MAAM,KAAK;CAEzC,OAAO;AACX"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/util/string-column-length.ts
|
|
2
|
+
/**
|
|
3
|
+
* The length a bounded string column is declared with when the property does
|
|
4
|
+
* not say. Historical: it is what the DDL generator hardcoded, kept so that
|
|
5
|
+
* regenerating an existing schema does not silently redefine its columns.
|
|
6
|
+
*/
|
|
7
|
+
var DEFAULT_STRING_COLUMN_LENGTH = 255;
|
|
8
|
+
/**
|
|
9
|
+
* How wide a `varchar`/`char` column should be for a given property.
|
|
10
|
+
*
|
|
11
|
+
* One definition, three call sites, because they used to disagree. For the same
|
|
12
|
+
* `columnType: "varchar"` property the DDL generator emitted `VARCHAR(255)`
|
|
13
|
+
* while the Drizzle generator emitted a bare `varchar("col")` — which Postgres
|
|
14
|
+
* reads as *unbounded* — so which of the two you ran decided whether the column
|
|
15
|
+
* had a limit at all. Introspection then dropped the length entirely, so reading
|
|
16
|
+
* an existing `character varying(500)` column back and regenerating it produced
|
|
17
|
+
* a `VARCHAR(255)`: a silent narrowing of a column with data already in it.
|
|
18
|
+
*
|
|
19
|
+
* `validation.max` is the property's own statement about how long the value may
|
|
20
|
+
* be, so it is the only sensible source for the column's width — and it keeps
|
|
21
|
+
* the constraint the database enforces in step with the one the app enforces,
|
|
22
|
+
* rather than inventing a second, different limit underneath it.
|
|
23
|
+
*/
|
|
24
|
+
function resolveStringColumnLength(prop) {
|
|
25
|
+
const max = prop.validation?.max;
|
|
26
|
+
return typeof max === "number" && Number.isInteger(max) && max > 0 ? max : DEFAULT_STRING_COLUMN_LENGTH;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { DEFAULT_STRING_COLUMN_LENGTH, resolveStringColumnLength };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=string-column-length.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"string-column-length.es.js","names":[],"sources":["../../src/util/string-column-length.ts"],"sourcesContent":["import type { StringProperty } from \"@rebasepro/types\";\n\n/**\n * The length a bounded string column is declared with when the property does\n * not say. Historical: it is what the DDL generator hardcoded, kept so that\n * regenerating an existing schema does not silently redefine its columns.\n */\nexport const DEFAULT_STRING_COLUMN_LENGTH = 255;\n\n/**\n * How wide a `varchar`/`char` column should be for a given property.\n *\n * One definition, three call sites, because they used to disagree. For the same\n * `columnType: \"varchar\"` property the DDL generator emitted `VARCHAR(255)`\n * while the Drizzle generator emitted a bare `varchar(\"col\")` — which Postgres\n * reads as *unbounded* — so which of the two you ran decided whether the column\n * had a limit at all. Introspection then dropped the length entirely, so reading\n * an existing `character varying(500)` column back and regenerating it produced\n * a `VARCHAR(255)`: a silent narrowing of a column with data already in it.\n *\n * `validation.max` is the property's own statement about how long the value may\n * be, so it is the only sensible source for the column's width — and it keeps\n * the constraint the database enforces in step with the one the app enforces,\n * rather than inventing a second, different limit underneath it.\n */\nexport function resolveStringColumnLength(prop: Pick<StringProperty, \"validation\">): number {\n const max = prop.validation?.max;\n return typeof max === \"number\" && Number.isInteger(max) && max > 0\n ? max\n : DEFAULT_STRING_COLUMN_LENGTH;\n}\n"],"mappings":";;;;;;AAOA,IAAa,+BAA+B;;;;;;;;;;;;;;;;;AAkB5C,SAAgB,0BAA0B,MAAkD;CACxF,MAAM,MAAM,KAAK,YAAY;CAC7B,OAAO,OAAO,QAAQ,YAAY,OAAO,UAAU,GAAG,KAAK,MAAM,IAC3D,MACA;AACV"}
|