@gusto/baerly-storage 0.5.0 → 0.6.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 (102) hide show
  1. package/dist/API.md +3 -2
  2. package/dist/CHANGELOG.md +82 -0
  3. package/dist/THIRD-PARTY-LICENSES.txt +1 -1
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/aws4fetch.esm-CXE5ZbAa.js +460 -0
  6. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +1 -0
  7. package/dist/baerly.js +10 -10
  8. package/dist/baerly.spec.json +1 -1
  9. package/dist/client-react.d.ts +2 -2
  10. package/dist/{client-Fe8CwB73.d.ts → client-ypCm3zjt.d.ts} +2 -2
  11. package/dist/client.d.ts +2 -2
  12. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-wrVYf4bb.js} +457 -56
  13. package/dist/cloudflare-wrVYf4bb.js.map +1 -0
  14. package/dist/cloudflare.d.ts +3 -3
  15. package/dist/cloudflare.js +5 -5
  16. package/dist/{config-1tv0-Yzm.js → config-B6nTy8e2.js} +435 -33
  17. package/dist/config-B6nTy8e2.js.map +1 -0
  18. package/dist/constants-CfeMWQWk.js.map +1 -1
  19. package/dist/{cost-DSMIVqzL.js → cost-_SE_SVgZ.js} +4 -4
  20. package/dist/{cost-DSMIVqzL.js.map → cost-_SE_SVgZ.js.map} +1 -1
  21. package/dist/{db-DsPkOVEH.d.ts → db-DjjthkTi.d.ts} +2 -2
  22. package/dist/{deploy-DonTr-CV.js → deploy-Di_Q01qx.js} +5 -5
  23. package/dist/deploy-Di_Q01qx.js.map +1 -0
  24. package/dist/dev-vite.d.ts +31 -27
  25. package/dist/dev-vite.js +60 -30
  26. package/dist/dev-vite.js.map +1 -1
  27. package/dist/dev.d.ts +1 -1
  28. package/dist/doctor-RWVRpvat.js +102 -0
  29. package/dist/doctor-RWVRpvat.js.map +1 -0
  30. package/dist/{dump-Bh5k26VQ.js → dump-m2vEYDNY.js} +4 -4
  31. package/dist/{dump-Bh5k26VQ.js.map → dump-m2vEYDNY.js.map} +1 -1
  32. package/dist/{export-DtF5tDIM.js → export-DenKwEQu.js} +4 -4
  33. package/dist/{export-DtF5tDIM.js.map → export-DenKwEQu.js.map} +1 -1
  34. package/dist/{fsck-D_djMO5D.js → fsck-2Vq-7-e2.js} +5 -5
  35. package/dist/{fsck-D_djMO5D.js.map → fsck-2Vq-7-e2.js.map} +1 -1
  36. package/dist/gcs-admin-Bx6xSNJj.d.ts +123 -0
  37. package/dist/gcs.d.ts +18 -0
  38. package/dist/gcs.js +2 -0
  39. package/dist/goog4-signer-Z7KnJ1su.js +321 -0
  40. package/dist/goog4-signer-Z7KnJ1su.js.map +1 -0
  41. package/dist/{http-DGd5tbNs.js → http-7zT29K3P.js} +4 -4
  42. package/dist/{http-DGd5tbNs.js.map → http-7zT29K3P.js.map} +1 -1
  43. package/dist/{aws4fetch.esm-p7eEzLCs.js → http-transport-BTgVCY5r.js} +24 -476
  44. package/dist/http-transport-BTgVCY5r.js.map +1 -0
  45. package/dist/http.d.ts +2 -2
  46. package/dist/http.js +2 -2
  47. package/dist/{index-BNRh23K9.d.ts → index-BHz92Acj.d.ts} +2 -2
  48. package/dist/{index-BYk9oCNf.d.ts → index-CEZKQsKt.d.ts} +3 -2
  49. package/dist/{index-CuA9Mi3K.d.ts → index-DP3ClvcA.d.ts} +7 -7
  50. package/dist/{index-0rZcMBwy.d.ts → index-uE-w2dgj.d.ts} +2 -2
  51. package/dist/index.d.ts +3 -3
  52. package/dist/index.js +3 -3
  53. package/dist/{inspect-6WZ-pC7-.js → inspect-BpYbH1DM.js} +5 -5
  54. package/dist/{inspect-6WZ-pC7-.js.map → inspect-BpYbH1DM.js.map} +1 -1
  55. package/dist/{log-tail-D98U1JBo.js → log-tail-QWU4wlu-.js} +3 -11
  56. package/dist/log-tail-QWU4wlu-.js.map +1 -0
  57. package/dist/{maintenance-B_e0T99L.d.ts → maintenance-BGHGt2Yg.d.ts} +2 -2
  58. package/dist/{maintenance-B4Dki6Ig.js → maintenance-DULFcpd1.js} +4 -17
  59. package/dist/maintenance-DULFcpd1.js.map +1 -0
  60. package/dist/{maintenance-C7coQp4c.js → maintenance-fEi-UZ2o.js} +5 -11
  61. package/dist/maintenance-fEi-UZ2o.js.map +1 -0
  62. package/dist/maintenance.d.ts +1 -1
  63. package/dist/maintenance.js +1 -1
  64. package/dist/node.d.ts +21 -60
  65. package/dist/node.js +4 -3
  66. package/dist/{observability-BmflLCdF.js → observability-Ch-VQJyE.js} +38 -16
  67. package/dist/{observability-BmflLCdF.js.map → observability-Ch-VQJyE.js.map} +1 -1
  68. package/dist/observability.d.ts +2 -2
  69. package/dist/observability.js +1 -1
  70. package/dist/{plan-a7PJHBCy.js → plan-C4qgiXSg.js} +2 -2
  71. package/dist/{plan-a7PJHBCy.js.map → plan-C4qgiXSg.js.map} +1 -1
  72. package/dist/{query-rAtXNQQB.js → query-C43r-6ib.js} +2 -2
  73. package/dist/{query-rAtXNQQB.js.map → query-C43r-6ib.js.map} +1 -1
  74. package/dist/{rebuild-index-BVzQSZlm.js → rebuild-index-BH1dc1p6.js} +4 -4
  75. package/dist/{rebuild-index-BVzQSZlm.js.map → rebuild-index-BH1dc1p6.js.map} +1 -1
  76. package/dist/{restore-R-4rbciV.js → restore-D0VYWzfP.js} +5 -5
  77. package/dist/{restore-R-4rbciV.js.map → restore-D0VYWzfP.js.map} +1 -1
  78. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec--LykAdl1.js} +2 -2
  79. package/dist/{runtime-spec-Dsw2-n8S.js.map → runtime-spec--LykAdl1.js.map} +1 -1
  80. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DD5gDc7t.d.ts} +6 -4
  81. package/dist/s3.d.ts +1 -1
  82. package/dist/s3.js +1 -1
  83. package/dist/sha256-CqcKTjw9.js +22 -0
  84. package/dist/sha256-CqcKTjw9.js.map +1 -0
  85. package/dist/{src-BL_JoPTn.js → src-BMFfDUI2.js} +68 -28
  86. package/dist/{src-BL_JoPTn.js.map → src-BMFfDUI2.js.map} +1 -1
  87. package/dist/{src-CYHFDrKz.js → src-DvbTEya2.js} +3 -3
  88. package/dist/{src-CYHFDrKz.js.map → src-DvbTEya2.js.map} +1 -1
  89. package/dist/{subcommand-DoDA-K7d.js → subcommand-BV68pqwJ.js} +2 -2
  90. package/dist/{subcommand-DoDA-K7d.js.map → subcommand-BV68pqwJ.js.map} +1 -1
  91. package/dist/{usage-DBV1eQHC.js → usage-BMZR8o6U.js} +3 -3
  92. package/dist/{usage-DBV1eQHC.js.map → usage-BMZR8o6U.js.map} +1 -1
  93. package/package.json +10 -4
  94. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  95. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  96. package/dist/config-1tv0-Yzm.js.map +0 -1
  97. package/dist/deploy-DonTr-CV.js.map +0 -1
  98. package/dist/doctor-DSIyCDg_.js +0 -346
  99. package/dist/doctor-DSIyCDg_.js.map +0 -1
  100. package/dist/log-tail-D98U1JBo.js.map +0 -1
  101. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  102. package/dist/maintenance-C7coQp4c.js.map +0 -1
@@ -166,6 +166,25 @@ const AUTH_CONFIG_VALUES = ["none", "shared-secret"];
166
166
  */
167
167
  const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
168
168
  //#endregion
169
+ //#region ../protocol/src/sha256.ts
170
+ /**
171
+ * SHA-256 of `bytes` as a 64-char lowercase hex string.
172
+ *
173
+ * Zero-import leaf module on purpose: co-locating this with heavier
174
+ * runtime (snapshot-hash.ts / hashing.ts) would drag that module into
175
+ * every consumer's bundle closure. Callers that want a truncated form
176
+ * (e.g. {@link versionFromContent}'s content keys) slice the return.
177
+ */
178
+ const sha256Hex = async (bytes) => {
179
+ const view = new Uint8Array(bytes.byteLength);
180
+ view.set(bytes);
181
+ const digest = await crypto.subtle.digest("SHA-256", view);
182
+ const out = new Uint8Array(digest);
183
+ let hex = "";
184
+ for (let i = 0; i < out.length; i++) hex += out[i].toString(16).padStart(2, "0");
185
+ return hex;
186
+ };
187
+ //#endregion
169
188
  //#region ../protocol/src/env.ts
170
189
  const PAAS_MARKERS = [
171
190
  "RAILWAY_ENVIRONMENT",
@@ -1723,14 +1742,15 @@ const parseListObjectsV2CommandOutput = (xml) => {
1723
1742
  return {
1724
1743
  ETag: rawXmlVal(contentEl, "ETag"),
1725
1744
  Key: xmlVal(contentEl, "Key"),
1726
- LastModified: parseLastModified(rawXmlVal(contentEl, "LastModified"))
1745
+ LastModified: parseLastModified(rawXmlVal(contentEl, "LastModified")),
1746
+ Generation: rawXmlVal(contentEl, "Generation")
1727
1747
  };
1728
1748
  }),
1729
1749
  NextContinuationToken: rawXmlVal(root, "NextContinuationToken")
1730
1750
  };
1731
1751
  };
1732
1752
  //#endregion
1733
- //#region ../adapter-node/src/s3-http.ts
1753
+ //#region ../adapter-node/src/http-transport.ts
1734
1754
  /**
1735
1755
  * Permanent {@link BaerlyError} codes that must short-circuit `retry`.
1736
1756
  * These represent caller- or environment-level faults where retrying
@@ -1782,7 +1802,7 @@ const retryAfterCause = (res) => {
1782
1802
  const hint = parseRetryAfter(res.headers.get("Retry-After"));
1783
1803
  return hint !== void 0 ? { retryAfterSeconds: hint } : {};
1784
1804
  };
1785
- const s3ErrorDetail = (status, body) => {
1805
+ const xmlErrorDetail = (status, body) => {
1786
1806
  const parsed = parseS3Error(body);
1787
1807
  if (parsed !== void 0) {
1788
1808
  const code = parsed.Code ?? "UnknownError";
@@ -1790,6 +1810,23 @@ const s3ErrorDetail = (status, body) => {
1790
1810
  }
1791
1811
  return `${status} ${body}`;
1792
1812
  };
1813
+ /**
1814
+ * Shared status→{@link BaerlyError} mapping for the S3/GCS XML adapters, so
1815
+ * the retryable set (`429`/`≥500`) can't drift between them. Store-specific
1816
+ * statuses (GCS `412`; S3 `409`/`404`-with-`If-Match`) are handled inline
1817
+ * first; the rest route here: `403`→AccessDenied (permanent), `429`/`≥500`→
1818
+ * retryable NetworkError carrying `{status, retryAfterSeconds?}`, else
1819
+ * InvalidResponse. Callers `throw` the result; consumes `res.text()` on the
1820
+ * non-`403` paths.
1821
+ */
1822
+ const mapStorageError = async (res, verb, key) => {
1823
+ if (res.status === 403) return new BaerlyError("AccessDenied", `${verb} ${key}: 403`);
1824
+ if (res.status === 429 || res.status >= 500) return new BaerlyError("NetworkError", `${verb} ${key}: ${res.status} ${await res.text()}`, {
1825
+ status: res.status,
1826
+ ...retryAfterCause(res)
1827
+ });
1828
+ return new BaerlyError("InvalidResponse", `${verb} ${key}: ${xmlErrorDetail(res.status, await res.text())}`);
1829
+ };
1793
1830
  const retry = async (fn, { retries = 8, backoffMs = 100, maxDelayMs = 1e4 } = {}) => {
1794
1831
  let wait = backoffMs;
1795
1832
  for (let attempt = 0; attempt <= retries; attempt++) try {
@@ -1802,7 +1839,7 @@ const retry = async (fn, { retries = 8, backoffMs = 100, maxDelayMs = 1e4 } = {}
1802
1839
  if (hintMs === void 0) wait = Math.min(wait * 1.5, maxDelayMs);
1803
1840
  else wait = backoffMs;
1804
1841
  }
1805
- throw new BaerlyError("Internal", "s3-http retry loop exited without returning or throwing");
1842
+ throw new BaerlyError("Internal", "http-transport retry loop exited without returning or throwing");
1806
1843
  };
1807
1844
  const retryAfterHintMs = (e, maxDelayMs) => {
1808
1845
  if (!(e instanceof BaerlyError)) return;
@@ -1810,10 +1847,326 @@ const retryAfterHintMs = (e, maxDelayMs) => {
1810
1847
  if (cause?.retryAfterSeconds === void 0) return;
1811
1848
  return Math.min(cause.retryAfterSeconds * 1e3, maxDelayMs);
1812
1849
  };
1850
+ //#endregion
1851
+ //#region ../adapter-node/src/gcs-http.ts
1852
+ /** Default GCS native XML API endpoint. */
1853
+ const DEFAULT_GCS_ENDPOINT = "https://storage.googleapis.com";
1854
+ /**
1855
+ * `Storage` impl that speaks the GCS native XML API and drives GCS's own
1856
+ * `x-goog-if-generation-match` conditional writes. Unlike GCS's S3-interop
1857
+ * endpoint (which treats `If-Match`/`If-None-Match` as read-scoped and can
1858
+ * never linearize the log), the native API returns 412 on any precondition
1859
+ * miss and the object `generation` in `x-goog-generation`. That generation
1860
+ * is carried verbatim in the opaque `Storage` etag.
1861
+ *
1862
+ * Authentication is plugged in via `sign` (GOOG4-HMAC-SHA256); this class
1863
+ * does no signing itself.
1864
+ */
1865
+ var GcsHttpStorage = class {
1866
+ #endpoint;
1867
+ #bucket;
1868
+ #fetch;
1869
+ #sign;
1870
+ #retries;
1871
+ #backoffMs;
1872
+ constructor(options) {
1873
+ this.#endpoint = (options.endpoint ?? "https://storage.googleapis.com").replace(/\/+$/, "");
1874
+ this.#bucket = options.bucket;
1875
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1876
+ this.#sign = options.sign;
1877
+ this.#retries = options.retries ?? 8;
1878
+ this.#backoffMs = options.backoffMs ?? 100;
1879
+ }
1880
+ #objectUrl(key, generation) {
1881
+ assertValidStorageKey(key);
1882
+ const base = `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;
1883
+ return generation !== void 0 ? `${base}?generation=${encodeURIComponent(generation)}` : base;
1884
+ }
1885
+ async #dispatch(req) {
1886
+ const signed = this.#sign ? await this.#sign(req) : req;
1887
+ try {
1888
+ return await this.#fetch(signed);
1889
+ } catch (error) {
1890
+ if (error instanceof BaerlyError) throw error;
1891
+ throw new BaerlyError("NetworkError", error instanceof Error ? error.message : String(error), error);
1892
+ }
1893
+ }
1894
+ #retry(fn) {
1895
+ return retry(fn, {
1896
+ retries: this.#retries,
1897
+ backoffMs: this.#backoffMs
1898
+ });
1899
+ }
1900
+ async get(key, opts) {
1901
+ opts?.signal?.throwIfAborted();
1902
+ const url = this.#objectUrl(key, opts?.versionId);
1903
+ return this.#retry(async () => {
1904
+ const res = await this.#dispatch(new Request(url, {
1905
+ method: "GET",
1906
+ signal: opts?.signal ?? null
1907
+ }));
1908
+ switch (res.status) {
1909
+ case 200: {
1910
+ const etag = res.headers.get("x-goog-generation");
1911
+ if (etag === null) throw new BaerlyError("InvalidResponse", `GET ${key}: missing x-goog-generation`);
1912
+ return {
1913
+ body: new Uint8Array(await res.arrayBuffer()),
1914
+ etag
1915
+ };
1916
+ }
1917
+ case 304:
1918
+ case 404: return null;
1919
+ default: throw await mapStorageError(res, "GET", key);
1920
+ }
1921
+ });
1922
+ }
1923
+ async put(key, body, opts) {
1924
+ opts?.signal?.throwIfAborted();
1925
+ const url = this.#objectUrl(key);
1926
+ const headers = new Headers();
1927
+ headers.set("Content-Type", opts?.contentType ?? "application/octet-stream");
1928
+ if (opts?.ifNoneMatch === "*") headers.set("x-goog-if-generation-match", "0");
1929
+ else if (opts?.ifMatch !== void 0) headers.set("x-goog-if-generation-match", opts.ifMatch);
1930
+ return this.#retry(async () => {
1931
+ const res = await this.#dispatch(new Request(url, {
1932
+ method: "PUT",
1933
+ headers,
1934
+ body,
1935
+ signal: opts?.signal ?? null
1936
+ }));
1937
+ if (res.status === 412) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed`);
1938
+ if (res.status !== 200 && res.status !== 204) throw await mapStorageError(res, "PUT", key);
1939
+ const etag = res.headers.get("x-goog-generation");
1940
+ if (etag === null) throw new BaerlyError("InvalidResponse", `PUT ${key}: missing x-goog-generation`);
1941
+ const dateStr = res.headers.get("Date");
1942
+ const result = { etag };
1943
+ if (dateStr !== null) result.serverDate = new Date(dateStr);
1944
+ return result;
1945
+ });
1946
+ }
1947
+ async delete(key, opts) {
1948
+ opts?.signal?.throwIfAborted();
1949
+ const url = this.#objectUrl(key);
1950
+ await this.#retry(async () => {
1951
+ const res = await this.#dispatch(new Request(url, {
1952
+ method: "DELETE",
1953
+ signal: opts?.signal ?? null
1954
+ }));
1955
+ if (res.status !== 200 && res.status !== 204 && res.status !== 404) throw await mapStorageError(res, "DELETE", key);
1956
+ });
1957
+ }
1958
+ async *list(prefix, opts) {
1959
+ opts?.signal?.throwIfAborted();
1960
+ let yielded = 0;
1961
+ let continuationToken;
1962
+ const startAfter = opts?.startAfter ?? "";
1963
+ while (true) {
1964
+ opts?.signal?.throwIfAborted();
1965
+ const params = new URLSearchParams();
1966
+ params.set("list-type", "2");
1967
+ params.set("prefix", prefix);
1968
+ params.set("encoding-type", "url");
1969
+ if (continuationToken !== void 0) params.set("continuation-token", continuationToken);
1970
+ else if (startAfter !== "") params.set("start-after", startAfter);
1971
+ if (opts?.maxKeys !== void 0) {
1972
+ const remaining = opts.maxKeys - yielded;
1973
+ params.set("max-keys", String(Math.min(remaining, 1e3)));
1974
+ }
1975
+ const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;
1976
+ let parsed;
1977
+ let lastHint;
1978
+ for (let attempt = 0; attempt < 10; attempt++) {
1979
+ const outcome = await this.#retry(async () => {
1980
+ const res = await this.#dispatch(new Request(url, {
1981
+ method: "GET",
1982
+ signal: opts?.signal ?? null
1983
+ }));
1984
+ if (res.status === 200) return {
1985
+ kind: "ok",
1986
+ body: await res.text()
1987
+ };
1988
+ if (res.status === 429) return {
1989
+ kind: "ratelimited",
1990
+ retryAfterSeconds: parseRetryAfter(res.headers.get("Retry-After"))
1991
+ };
1992
+ throw await mapStorageError(res, "LIST", prefix);
1993
+ });
1994
+ if (outcome.kind === "ok") {
1995
+ parsed = parseListObjectsV2CommandOutput(outcome.body);
1996
+ break;
1997
+ }
1998
+ lastHint = outcome.retryAfterSeconds;
1999
+ const hintMs = outcome.retryAfterSeconds !== void 0 ? outcome.retryAfterSeconds * 1e3 : 0;
2000
+ await delay(Math.max(hintMs, RATE_LIMIT_BACKOFF_MILLIS));
2001
+ }
2002
+ if (parsed === void 0) throw new BaerlyError("NetworkError", `LIST ${prefix}: rate-limited`, {
2003
+ status: 429,
2004
+ ...lastHint !== void 0 ? { retryAfterSeconds: lastHint } : {}
2005
+ });
2006
+ for (const entry of parsed.Contents ?? []) {
2007
+ if (entry.Key === void 0) continue;
2008
+ yield {
2009
+ key: entry.Key,
2010
+ etag: entry.Generation ?? "",
2011
+ ...entry.LastModified !== void 0 && { lastModified: entry.LastModified }
2012
+ };
2013
+ yielded += 1;
2014
+ if (opts?.maxKeys !== void 0 && yielded >= opts.maxKeys) return;
2015
+ }
2016
+ continuationToken = parsed.NextContinuationToken;
2017
+ if (continuationToken === void 0 || continuationToken === "") return;
2018
+ }
2019
+ }
2020
+ };
2021
+ //#endregion
2022
+ //#region ../adapter-node/src/credentials/goog4-signer.ts
2023
+ /** GOOG4 signing-key prefix (vs AWS SigV4's "AWS4"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */
2024
+ const GOOG4_KEY_PREFIX = "GOOG4";
2025
+ /** Credential-scope terminator (vs SigV4's "aws4_request"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */
2026
+ const GOOG4_REQUEST = "goog4_request";
2027
+ /** Signing algorithm string. @see https://docs.cloud.google.com/storage/docs/authentication/signatures */
2028
+ const GOOG4_ALGORITHM = "GOOG4-HMAC-SHA256";
2029
+ /** GCS storage service name in the credential scope (vs SigV4's "s3"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */
2030
+ const GOOG4_SERVICE = "storage";
2031
+ /** GCS accepts "auto" as the signing region. @see https://docs.cloud.google.com/storage/docs/authentication/signatures */
2032
+ const GOOG4_REGION = "auto";
2033
+ const encoder$1 = new TextEncoder();
2034
+ function toHex(bytes) {
2035
+ let hex = "";
2036
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
2037
+ return hex;
2038
+ }
2039
+ /** RFC-3986-strict percent-encoding for canonical query components: encodes
2040
+ * everything except the unreserved set A-Za-z0-9-._~. encodeURIComponent
2041
+ * already handles that set but leaves !'()* unescaped, so escape those too.
2042
+ * @see https://docs.cloud.google.com/storage/docs/authentication/canonical-requests */
2043
+ function uriEncode(s) {
2044
+ return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2045
+ }
2046
+ /** Canonical-URI encoding for the request path. `URL.pathname` already
2047
+ * percent-encodes spaces / non-ASCII / control chars (and `^` `` ` `` `{` `}`),
2048
+ * but leaves GCS's enumerated reserved set raw — the sub-delims, `:@`, and
2049
+ * `[]`. GCS canonicalizes the path it receives by percent-encoding exactly
2050
+ * that set (`?=!#$&'()*+,:;@[]"`; `?#"` can't survive in `pathname`), so we
2051
+ * must reproduce the same delta or a `[`/`]`-bearing key signs differently
2052
+ * than GCS computes it (403 SignatureDoesNotMatch). Target only the delta so
2053
+ * already-encoded `%XX` and the unreserved set stay intact (no double-encode).
2054
+ * This is a denylist, not an allow-list, on purpose: over-encoding chars GCS
2055
+ * leaves raw (`|` `` ` `` `{}` …) would itself cause a mismatch.
2056
+ * @see https://docs.cloud.google.com/storage/docs/authentication/canonical-requests */
2057
+ function canonicalUri(pathname) {
2058
+ return pathname.replace(/[!$&'()*+,;=:@[\]]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2059
+ }
2060
+ async function hmac$1(key, data) {
2061
+ const view = new Uint8Array(key.byteLength);
2062
+ view.set(key);
2063
+ const cryptoKey = await crypto.subtle.importKey("raw", view, {
2064
+ name: "HMAC",
2065
+ hash: "SHA-256"
2066
+ }, false, ["sign"]);
2067
+ const sig = await crypto.subtle.sign("HMAC", cryptoKey, encoder$1.encode(data));
2068
+ return new Uint8Array(sig);
2069
+ }
2070
+ /** Pure: build the GOOG4 canonical request string. Exported for the intermediates test. */
2071
+ function goog4CanonicalRequest(input) {
2072
+ const u = new URL(input.url);
2073
+ const normalized = {};
2074
+ for (const [name, value] of Object.entries(input.signedHeaders)) normalized[name.toLowerCase()] = value;
2075
+ const names = Object.keys(normalized).toSorted();
2076
+ const canonicalHeaders = names.map((n) => `${n}:${normalized[n].trim()}\n`).join("");
2077
+ const signedHeaderList = names.join(";");
2078
+ const query = [...u.searchParams].map(([k, v]) => [uriEncode(k), uriEncode(v)]).toSorted((a, b) => {
2079
+ const ka = `${a[0]}\0${a[1]}`;
2080
+ const kb = `${b[0]}\0${b[1]}`;
2081
+ if (ka < kb) return -1;
2082
+ return ka > kb ? 1 : 0;
2083
+ }).map(([k, v]) => `${k}=${v}`).join("&");
2084
+ return [
2085
+ input.method,
2086
+ canonicalUri(u.pathname),
2087
+ query,
2088
+ canonicalHeaders,
2089
+ signedHeaderList,
2090
+ input.hashedPayload
2091
+ ].join("\n");
2092
+ }
2093
+ /** Pure: build the SigV4-family string-to-sign. Async because it hashes the canonical request. */
2094
+ async function goog4StringToSign(input) {
2095
+ const hash = await sha256Hex(encoder$1.encode(input.canonicalRequest));
2096
+ return [
2097
+ input.algorithm,
2098
+ input.amzDate,
2099
+ input.scope,
2100
+ hash
2101
+ ].join("\n");
2102
+ }
2103
+ /**
2104
+ * The SigV4-family signing machinery: four-stage HMAC key chain + final HMAC.
2105
+ * Identical between GOOG4 and AWS SigV4 modulo the {keyPrefix, terminator,
2106
+ * service, region} constants — which is exactly what the AWS-vector oracle
2107
+ * exploits to prove this in CI. Exported for oracle 1.
2108
+ */
2109
+ async function sigV4Signature(input) {
2110
+ return toHex(await hmac$1(await hmac$1(await hmac$1(await hmac$1(await hmac$1(encoder$1.encode(input.keyPrefix + input.secretAccessKey), input.yyyymmdd), input.region), input.service), input.terminator), input.stringToSign));
2111
+ }
2112
+ function amzDateFrom(ms) {
2113
+ const amzDate = new Date(ms).toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z");
2114
+ return {
2115
+ amzDate,
2116
+ yyyymmdd: amzDate.slice(0, 8)
2117
+ };
2118
+ }
2119
+ function goog4Signer(opts) {
2120
+ const now = opts.now ?? (() => Date.now());
2121
+ const resolve = async () => typeof opts.credentials === "function" ? opts.credentials() : opts.credentials;
2122
+ return async (req) => {
2123
+ const creds = await resolve();
2124
+ const { amzDate, yyyymmdd } = amzDateFrom(now());
2125
+ const scope = `${yyyymmdd}/${GOOG4_REGION}/${GOOG4_SERVICE}/${GOOG4_REQUEST}`;
2126
+ const payloadHash = await sha256Hex(new Uint8Array(await req.clone().arrayBuffer()));
2127
+ const url = new URL(req.url);
2128
+ const headers = new Headers(req.headers);
2129
+ headers.set("host", url.host);
2130
+ headers.set("x-goog-date", amzDate);
2131
+ headers.set("x-goog-content-sha256", payloadHash);
2132
+ const signedHeaders = {};
2133
+ for (const [name, value] of headers) {
2134
+ const lower = name.toLowerCase();
2135
+ if (lower === "host" || lower === "content-type" || lower.startsWith("x-goog-")) signedHeaders[lower] = value;
2136
+ }
2137
+ const stringToSign = await goog4StringToSign({
2138
+ algorithm: GOOG4_ALGORITHM,
2139
+ amzDate,
2140
+ scope,
2141
+ canonicalRequest: goog4CanonicalRequest({
2142
+ method: req.method,
2143
+ url: req.url,
2144
+ signedHeaders,
2145
+ hashedPayload: payloadHash
2146
+ })
2147
+ });
2148
+ const signature = await sigV4Signature({
2149
+ keyPrefix: GOOG4_KEY_PREFIX,
2150
+ terminator: GOOG4_REQUEST,
2151
+ service: GOOG4_SERVICE,
2152
+ region: GOOG4_REGION,
2153
+ secretAccessKey: creds.secretAccessKey,
2154
+ yyyymmdd,
2155
+ stringToSign
2156
+ });
2157
+ const signedHeaderList = Object.keys(signedHeaders).map((n) => n.toLowerCase()).toSorted().join(";");
2158
+ headers.set("Authorization", `${GOOG4_ALGORITHM} Credential=${creds.accessKeyId}/${scope}, SignedHeaders=${signedHeaderList}, Signature=${signature}`);
2159
+ return new Request(req, { headers });
2160
+ };
2161
+ }
2162
+ //#endregion
2163
+ //#region ../adapter-node/src/s3-http.ts
1813
2164
  /**
1814
2165
  * `Storage` impl that speaks the S3 REST API directly. Works against
1815
- * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),
1816
- * Minio. Does not depend on any AWS SDK.
2166
+ * any S3-compatible endpoint — AWS S3, R2 (S3-compat), Minio. Does not
2167
+ * depend on any AWS SDK. GCS is NOT supported over this S3-interop path
2168
+ * (its conditional-write semantics can't linearize the commit log); use
2169
+ * the native `GcsHttpStorage` adapter instead.
1817
2170
  *
1818
2171
  * Authentication is plugged in via the `sign` callback; this class
1819
2172
  * itself does no SigV4. For Cloudflare Workers, the R2 binding fast
@@ -1882,13 +2235,7 @@ var S3HttpStorage = class {
1882
2235
  }
1883
2236
  case 304:
1884
2237
  case 404: return null;
1885
- case 403: throw new BaerlyError("AccessDenied", `GET ${key}: 403`);
1886
- default:
1887
- if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `GET ${key}: ${res.status} ${await res.text()}`, {
1888
- status: res.status,
1889
- ...retryAfterCause(res)
1890
- });
1891
- throw new BaerlyError("InvalidResponse", `GET ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
2238
+ default: throw await mapStorageError(res, "GET", key);
1892
2239
  }
1893
2240
  });
1894
2241
  }
@@ -1912,12 +2259,7 @@ var S3HttpStorage = class {
1912
2259
  ...retryAfterCause(res)
1913
2260
  });
1914
2261
  if (res.status === 404 && opts?.ifMatch !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
1915
- if (res.status === 403) throw new BaerlyError("AccessDenied", `PUT ${key}: 403`);
1916
- if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `PUT ${key}: ${res.status} ${await res.text()}`, {
1917
- status: res.status,
1918
- ...retryAfterCause(res)
1919
- });
1920
- if (res.status !== 200 && res.status !== 204) throw new BaerlyError("InvalidResponse", `PUT ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
2262
+ if (res.status !== 200 && res.status !== 204) throw await mapStorageError(res, "PUT", key);
1921
2263
  const etag = res.headers.get("ETag");
1922
2264
  if (etag === null) throw new BaerlyError("InvalidResponse", `PUT ${key}: missing ETag`);
1923
2265
  const dateStr = res.headers.get("Date");
@@ -1936,11 +2278,7 @@ var S3HttpStorage = class {
1936
2278
  method: "DELETE",
1937
2279
  signal: opts?.signal ?? null
1938
2280
  }));
1939
- if (res.status === 403) throw new BaerlyError("AccessDenied", `DELETE ${key}: 403`);
1940
- if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `DELETE ${key}: ${res.status} ${await res.text()}`, {
1941
- status: res.status,
1942
- ...retryAfterCause(res)
1943
- });
2281
+ if (res.status !== 200 && res.status !== 204 && res.status !== 404) throw await mapStorageError(res, "DELETE", key);
1944
2282
  });
1945
2283
  }
1946
2284
  async *list(prefix, opts) {
@@ -1977,12 +2315,7 @@ var S3HttpStorage = class {
1977
2315
  kind: "ratelimited",
1978
2316
  retryAfterSeconds: parseRetryAfter(res.headers.get("Retry-After"))
1979
2317
  };
1980
- if (res.status === 403) throw new BaerlyError("AccessDenied", `LIST ${prefix}: 403`);
1981
- if (res.status >= 500) throw new BaerlyError("NetworkError", `LIST ${prefix}: ${res.status} ${await res.text()}`, {
1982
- status: res.status,
1983
- ...retryAfterCause(res)
1984
- });
1985
- throw new BaerlyError("InvalidResponse", `LIST ${prefix}: ${s3ErrorDetail(res.status, await res.text())}`);
2318
+ throw await mapStorageError(res, "LIST", prefix);
1986
2319
  });
1987
2320
  if (outcome.kind === "ok") {
1988
2321
  parsed = parseListObjectsV2CommandOutput(outcome.body);
@@ -2435,6 +2768,42 @@ function minioStorage(opts) {
2435
2768
  credentials: opts.credentials
2436
2769
  });
2437
2770
  }
2771
+ /**
2772
+ * Google Cloud Storage `Storage` factory over the native GCS XML API
2773
+ * at `https://storage.googleapis.com`. Wraps {@link GcsHttpStorage} with
2774
+ * a GOOG4-HMAC-SHA256 signer, driving GCS's own generation-precondition
2775
+ * conditional writes (`x-goog-if-generation-match: 0` for create-if-absent,
2776
+ * `x-goog-if-generation-match: <generation>` for compare-and-swap), which
2777
+ * return `412` on a lost write. The object `generation` is carried verbatim
2778
+ * as the opaque `Storage` etag. This is the sanctioned GCS path — the
2779
+ * S3-interop endpoint treats `If-Match`/`If-None-Match` as read-scoped only
2780
+ * and cannot linearize the log, so it is not supported.
2781
+ *
2782
+ * Authentication uses GCS HMAC keys (Console → Settings → Interoperability)
2783
+ * — mint an interop key, put the HMAC access key in `credentials.accessKeyId`
2784
+ * and the HMAC secret in `credentials.secretAccessKey`.
2785
+ *
2786
+ * @example
2787
+ * ```ts
2788
+ * import { gcsStorage } from "@gusto/baerly-storage/node";
2789
+ *
2790
+ * const storage = gcsStorage({
2791
+ * bucket: process.env["BUCKET"]!,
2792
+ * credentials: {
2793
+ * accessKeyId: process.env["GCS_HMAC_ACCESS_KEY_ID"]!,
2794
+ * secretAccessKey: process.env["GCS_HMAC_SECRET"]!,
2795
+ * },
2796
+ * });
2797
+ * ```
2798
+ */
2799
+ function gcsStorage(opts) {
2800
+ const sign = goog4Signer({ credentials: opts.credentials });
2801
+ return new GcsHttpStorage({
2802
+ bucket: opts.bucket,
2803
+ sign,
2804
+ ...opts.endpoint !== void 0 && { endpoint: opts.endpoint }
2805
+ });
2806
+ }
2438
2807
  //#endregion
2439
2808
  //#region src/bucket-uri.ts
2440
2809
  /**
@@ -2446,6 +2815,12 @@ function minioStorage(opts) {
2446
2815
  * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,
2447
2816
  * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region
2448
2817
  * defaults to `us-east-1`).
2818
+ * - `gcs://<bucket>[/<prefix>]` — native GCS XML API. Creds via
2819
+ * env vars `BAERLY_GCS_HMAC_ACCESS_KEY_ID` + `BAERLY_GCS_HMAC_SECRET`
2820
+ * (GCS HMAC interop keys: Console → Cloud Storage → Settings →
2821
+ * Interoperability). Drives GCS's native generation-precondition
2822
+ * path (`x-goog-if-generation-match`); the S3-interop endpoint is
2823
+ * NOT supported (it treats If-Match/If-None-Match as read-only).
2449
2824
  * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.
2450
2825
  * Relative paths are rejected by the three-slash prefix.
2451
2826
  * - `memory://<bucket>` — `MemoryStorage` keyed via
@@ -2456,7 +2831,7 @@ function minioStorage(opts) {
2456
2831
  * key prefix.
2457
2832
  *
2458
2833
  * @throws BaerlyError code="InvalidConfig" — unsupported scheme, or an
2459
- * `s3://` URI with a missing env var.
2834
+ * `s3://` / `gcs://` URI with a missing env var.
2460
2835
  */
2461
2836
  const parseBucketUri = async (uri) => {
2462
2837
  if (uri.startsWith("s3://")) {
@@ -2482,6 +2857,33 @@ const parseBucketUri = async (uri) => {
2482
2857
  keyPrefix: normalizeKeyPrefix(prefix)
2483
2858
  };
2484
2859
  }
2860
+ if (uri.startsWith("gcs://")) {
2861
+ const rest = uri.slice(6);
2862
+ const slash = rest.indexOf("/");
2863
+ const bucket = slash === -1 ? rest : rest.slice(0, slash);
2864
+ const prefix = slash === -1 ? "" : rest.slice(slash + 1);
2865
+ if (bucket.length === 0) throw new BaerlyError("InvalidConfig", `bucket URI: gcs:// URI requires a bucket name (got ${JSON.stringify(uri)})`);
2866
+ const accessKeyId = requireEnv("BAERLY_GCS_HMAC_ACCESS_KEY_ID");
2867
+ const secretAccessKey = requireEnv("BAERLY_GCS_HMAC_SECRET");
2868
+ const endpoint = DEFAULT_GCS_ENDPOINT;
2869
+ const credentials = {
2870
+ accessKeyId,
2871
+ secretAccessKey
2872
+ };
2873
+ return {
2874
+ storage: gcsStorage({
2875
+ endpoint,
2876
+ bucket,
2877
+ credentials
2878
+ }),
2879
+ keyPrefix: normalizeKeyPrefix(prefix),
2880
+ gcs: {
2881
+ endpoint,
2882
+ bucket,
2883
+ credentials
2884
+ }
2885
+ };
2886
+ }
2485
2887
  if (uri.startsWith("file:///")) return {
2486
2888
  storage: new LocalFsStorage({ root: uri.slice(7) }),
2487
2889
  keyPrefix: ""
@@ -2688,6 +3090,6 @@ const loadCollectionIndexes = async (configPath, collection, commandName) => {
2688
3090
  return cfg.collections?.[collection]?.indexes ?? [];
2689
3091
  };
2690
3092
  //#endregion
2691
- export { SHARED_SECRET_MISSING_MESSAGE as _, countKey as a, GC_GRACE_PERIOD_MILLIS as c, LOG_FORWARD_PROBE_CAP as d, MAINTENANCE_MIN_LIVE_BYTES as f, MAX_KEY_BYTES as g, MAINTENANCE_WARN_INTERVAL_WRITES as h, timestamp as i, GC_MAX_PENDING_CANDIDATES as l, MAINTENANCE_PROFILE_CF_PAID as m, loadCollectionIndexes as n, uuid as o, MAINTENANCE_PROFILE_CF_FREE as p, parseBucketUri as r, CURRENT_JSON_CONTENT_TYPE as s, loadAppConfig as t, GC_PENDING_CONTENT_TYPE as u };
3093
+ export { MAINTENANCE_PROFILE_CF_PAID as _, DEFAULT_GCS_ENDPOINT as a, SHARED_SECRET_MISSING_MESSAGE as b, uuid as c, GC_GRACE_PERIOD_MILLIS as d, GC_MAX_PENDING_CANDIDATES as f, MAINTENANCE_PROFILE_CF_FREE as g, MAINTENANCE_MIN_LIVE_BYTES as h, goog4Signer as i, sha256Hex as l, LOG_FORWARD_PROBE_CAP as m, loadCollectionIndexes as n, timestamp as o, GC_PENDING_CONTENT_TYPE as p, parseBucketUri as r, countKey as s, loadAppConfig as t, CURRENT_JSON_CONTENT_TYPE as u, MAINTENANCE_WARN_INTERVAL_WRITES as v, MAX_KEY_BYTES as y };
2692
3094
 
2693
- //# sourceMappingURL=config-1tv0-Yzm.js.map
3095
+ //# sourceMappingURL=config-B6nTy8e2.js.map