@niledatabase/server 5.3.1 → 5.3.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -526,6 +526,30 @@ function headersToMap(headers) {
526
526
  }
527
527
 
528
528
  // src/api/utils/request.ts
529
+ var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
530
+ function stripDecodedResponseHeaders(res) {
531
+ if (!(res instanceof Response) || res.status < 200 || res.status > 599) {
532
+ return res;
533
+ }
534
+ const hasContentEncoding = res.headers.has("content-encoding");
535
+ const hasTransferEncoding = res.headers.has("transfer-encoding");
536
+ if (!hasContentEncoding && !hasTransferEncoding) {
537
+ return res;
538
+ }
539
+ const headers = new Headers(res.headers);
540
+ if (hasContentEncoding) {
541
+ headers.delete("content-encoding");
542
+ headers.delete("content-length");
543
+ }
544
+ if (hasTransferEncoding) {
545
+ headers.delete("transfer-encoding");
546
+ }
547
+ return new Response(NULL_BODY_STATUSES.has(res.status) ? null : res.body, {
548
+ status: res.status,
549
+ statusText: res.statusText,
550
+ headers
551
+ });
552
+ }
529
553
  async function request(url, _init, config) {
530
554
  const { debug, info, error } = config.logger("[REQUEST]");
531
555
  const { request: request2, ...init } = _init;
@@ -614,7 +638,7 @@ async function request(url, _init, config) {
614
638
  _init
615
639
  );
616
640
  try {
617
- const res = await fetch(fullUrl, {
641
+ const fetchedRes = await fetch(fullUrl, {
618
642
  ...params
619
643
  }).catch((e) => {
620
644
  error("An error has occurred in the fetch", {
@@ -626,6 +650,7 @@ async function request(url, _init, config) {
626
650
  { status: 500 }
627
651
  );
628
652
  });
653
+ const res = stripDecodedResponseHeaders(fetchedRes);
629
654
  const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
630
655
  info(`[${params.method ?? "GET"}] ${fullUrl}`, {
631
656
  status: res?.status,
@@ -747,27 +772,20 @@ async function GET(url, init, config) {
747
772
 
748
773
  // src/utils/fetch.ts
749
774
  function getTokenFromCookie(headers, cookieKey) {
750
- const cookie = headers.get("cookie")?.split("; ");
751
- const _cookies = {};
752
- if (cookie) {
753
- for (const parts of cookie) {
754
- const cookieParts = parts.split("=");
755
- const _cookie = cookieParts.slice(1).join("=");
756
- const name = cookieParts[0];
757
- _cookies[name] = _cookie;
758
- }
775
+ const cookieHeader = headers.get("cookie");
776
+ if (!cookieHeader) {
777
+ return null;
759
778
  }
760
- if (cookie) {
761
- for (const parts of cookie) {
762
- const cookieParts = parts.split("=");
763
- const _cookie = cookieParts.slice(1).join("=");
764
- const name = cookieParts[0];
765
- _cookies[name] = _cookie;
779
+ const cookies = cookieHeader.split("; ");
780
+ for (const parts of cookies) {
781
+ const cookieParts = parts.split("=");
782
+ const name = cookieParts[0];
783
+ const value = cookieParts.slice(1).join("=");
784
+ if (name === cookieKey) {
785
+ return value;
766
786
  }
767
787
  }
768
- {
769
- return _cookies[cookieKey];
770
- }
788
+ return null;
771
789
  }
772
790
  function getTenantFromHttp(headers, context) {
773
791
  const cookieTenant = getTokenFromCookie(headers, TENANT_COOKIE);
@@ -2262,43 +2280,45 @@ var updateHeaders = (val) => {
2262
2280
  eventer.publish("headers" /* Headers */, val);
2263
2281
  };
2264
2282
  var watchHeaders = (cb) => eventer.subscribe("headers" /* Headers */, cb);
2265
-
2266
- // src/db/PoolProxy.ts
2267
- function createProxyForPool(pool, config, logger, context) {
2268
- const { info, error } = logger("[pool]");
2269
- return new Proxy(pool, {
2270
- get(target, property) {
2271
- if (property === "query") {
2272
- if (!config.connectionString) {
2273
- if (!config.user || !config.password) {
2274
- error(
2275
- "Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev"
2276
- );
2277
- } else if (!config.database) {
2278
- error(
2279
- "Unable to obtain database name. Is process.env.NILEDB_POSTGRES_URL set?"
2280
- );
2281
- }
2282
- }
2283
- const caller = target[property];
2284
- return function query(...args) {
2285
- let log = "[QUERY]";
2286
- const [tenantId, userId] = context;
2287
- if (tenantId) {
2288
- log = `${log}[TENANT:${tenantId}]`;
2289
- }
2290
- if (userId) {
2291
- log = `${log}[USER:${userId}]`;
2292
- }
2293
- info(log, ...args);
2294
- const called = caller.apply(this, args);
2295
- return called;
2296
- };
2283
+ var PoolWithLogger = class extends pg.Pool {
2284
+ nileConfig;
2285
+ logger;
2286
+ context;
2287
+ info;
2288
+ error;
2289
+ constructor(config, logger, context) {
2290
+ super(config);
2291
+ this.nileConfig = config;
2292
+ this.logger = logger;
2293
+ this.context = context;
2294
+ const { info, error } = this.logger("[pool]");
2295
+ this.info = info;
2296
+ this.error = error;
2297
+ }
2298
+ query(...args) {
2299
+ if (!this.nileConfig.connectionString) {
2300
+ if (!this.nileConfig.user || !this.nileConfig.password) {
2301
+ this.error(
2302
+ "Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev"
2303
+ );
2304
+ } else if (!this.nileConfig.database) {
2305
+ this.error(
2306
+ "Unable to obtain database name. Is process.env.NILEDB_POSTGRES_URL set?"
2307
+ );
2297
2308
  }
2298
- return target[property];
2299
2309
  }
2300
- });
2301
- }
2310
+ let log = "[QUERY]";
2311
+ const [tenantId, userId] = this.context;
2312
+ if (tenantId) {
2313
+ log = `${log}[TENANT:${tenantId}]`;
2314
+ }
2315
+ if (userId) {
2316
+ log = `${log}[USER:${userId}]`;
2317
+ }
2318
+ this.info(log, ...args);
2319
+ return super.query(...args);
2320
+ }
2321
+ };
2302
2322
 
2303
2323
  // src/db/NileInstance.ts
2304
2324
  var NileDatabase = class {
@@ -2323,8 +2343,7 @@ var NileDatabase = class {
2323
2343
  const cloned = { ...config };
2324
2344
  cloned.password = "***";
2325
2345
  this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
2326
- this.pool = createProxyForPool(
2327
- new pg.Pool(remaining),
2346
+ this.pool = new PoolWithLogger(
2328
2347
  this.config,
2329
2348
  logger,
2330
2349
  id === "base" ? [] : id.split(":")
@@ -2582,8 +2601,10 @@ var Auth = class {
2582
2601
  return withNileContext(
2583
2602
  this.#config,
2584
2603
  async () => {
2585
- ctx.set({ headers: null });
2586
2604
  const { email, password, ...params } = payload;
2605
+ if (!params.tenantId) {
2606
+ ctx.set({ headers: null });
2607
+ }
2587
2608
  if (!email || !password) {
2588
2609
  throw new Error(
2589
2610
  "Server side sign up requires a user email and password."
@@ -2621,7 +2642,12 @@ var Auth = class {
2621
2642
  );
2622
2643
  }
2623
2644
  const { headers } = ctx.get();
2624
- headers?.append("cookie", token);
2645
+ const cookie = [
2646
+ parseCSRF(res.headers) ?? parseCSRF(headers),
2647
+ parseCallback(res.headers) ?? parseCallback(headers),
2648
+ token
2649
+ ].filter(Boolean).join("; ");
2650
+ headers.set("cookie", cookie);
2625
2651
  ctx.set({ headers });
2626
2652
  updateHeaders(headers);
2627
2653
  if (rawResponse) {
@@ -3064,8 +3090,8 @@ async function obtainCsrf(config, rawResponse = false) {
3064
3090
  if (setCookie) {
3065
3091
  const cookie = [
3066
3092
  csrfCook,
3067
- parseCallback(res.headers),
3068
- parseToken(res.headers)
3093
+ parseCallback(res.headers) ?? parseCallback(headers),
3094
+ parseToken(res.headers) ?? parseToken(headers)
3069
3095
  ].filter(Boolean).join("; ");
3070
3096
  headers.set("cookie", cookie);
3071
3097
  ctx.set({ headers });