@niledatabase/server 4.2.0-alpha.0 → 4.2.0-alpha.2

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
@@ -80,73 +80,6 @@ var X_NILE_USER_ID = "nile.user_id";
80
80
  var X_NILE_ORIGIN = "nile.origin";
81
81
  var X_NILE_SECURECOOKIES = "nile.secure_cookies";
82
82
 
83
- // src/context/asyncStorage.ts
84
- var globalContext = null;
85
- function setContext(headers) {
86
- const origin = headers.get(X_NILE_ORIGIN);
87
- const host = headers.get("host");
88
- const cookie = headers.get("cookie");
89
- const tenantId = headers.get(X_NILE_TENANT);
90
- const userId = headers.get(X_NILE_USER_ID);
91
- const context = {};
92
- if (origin) {
93
- context.origin = origin;
94
- } else if (host) {
95
- context.origin = host;
96
- }
97
- if (cookie) {
98
- context.cookie = cookie;
99
- }
100
- if (tenantId) {
101
- context.tenantId = tenantId;
102
- }
103
- if (userId) {
104
- context.userId = userId;
105
- }
106
- globalContext = context;
107
- }
108
- function getOrigin() {
109
- return globalContext?.origin;
110
- }
111
- function getCookie() {
112
- return globalContext?.cookie;
113
- }
114
- function setCookie(headers) {
115
- const getSet = headers?.getSetCookie?.();
116
- if (getSet?.length) {
117
- const updatedCookie = [];
118
- for (const cook of getSet) {
119
- const [c] = cook.split("; ");
120
- const [, val] = c.split("=");
121
- if (val) {
122
- updatedCookie.push(c);
123
- }
124
- }
125
- const cookie = mergeCookies(updatedCookie);
126
- globalContext = { ...globalContext, cookie };
127
- }
128
- }
129
- function mergeCookies(overrideArray) {
130
- const cookieString = getCookie();
131
- const cookieMap = {};
132
- if (!cookieString) {
133
- return overrideArray.join("; ");
134
- }
135
- cookieString.split(";").forEach((cookie) => {
136
- const [rawKey, ...rawVal] = cookie.trim().split("=");
137
- const key12 = rawKey.trim();
138
- const value = rawVal.join("=").trim();
139
- if (key12) cookieMap[key12] = value;
140
- });
141
- overrideArray.forEach((cookie) => {
142
- const [rawKey, ...rawVal] = cookie.trim().split("=");
143
- const key12 = rawKey.trim();
144
- const value = rawVal.join("=").trim();
145
- if (key12) cookieMap[key12] = value;
146
- });
147
- return Object.entries(cookieMap).map(([k, v]) => `${k}=${v}`).join("; ");
148
- }
149
-
150
83
  // src/api/utils/request.ts
151
84
  async function request(url, _init, config) {
152
85
  const { debug, info, error } = Logger(config, "[REQUEST]");
@@ -179,7 +112,7 @@ async function request(url, _init, config) {
179
112
  updatedHeaders.set(X_NILE_ORIGIN, requestUrl.origin);
180
113
  debug(`Obtained origin from request ${requestUrl.origin}`);
181
114
  }
182
- const params = { ...init, headers: updatedHeaders };
115
+ const params = { ...init };
183
116
  if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
184
117
  try {
185
118
  updatedHeaders.set("content-type", "application/json");
@@ -193,9 +126,9 @@ async function request(url, _init, config) {
193
126
  params.body = initBody ?? requestBody;
194
127
  }
195
128
  }
129
+ params.headers = updatedHeaders;
196
130
  const fullUrl = `${url}${requestUrl.search}`;
197
131
  try {
198
- setContext(updatedHeaders);
199
132
  const res = await fetch(fullUrl, { ...params }).catch(
200
133
  (e) => {
201
134
  error("An error has occurred in the fetch", {
@@ -214,7 +147,6 @@ async function request(url, _init, config) {
214
147
  statusText: res?.statusText,
215
148
  text: await loggingRes?.text()
216
149
  });
217
- setCookie(res?.headers);
218
150
  return res;
219
151
  } catch (e) {
220
152
  if (e instanceof Error) {
@@ -509,6 +441,7 @@ var ApiConfig = class {
509
441
  routePrefix;
510
442
  secureCookies;
511
443
  origin;
444
+ headers;
512
445
  /**
513
446
  * The client side callback url. Defaults to nothing (so nile.origin will be it), but in the cases of x-origin, you want to set this explicitly to be sure nile-auth does the right thing
514
447
  * If this is set, any `callbackUrl` from the client will be ignored.
@@ -522,6 +455,11 @@ var ApiConfig = class {
522
455
  this.callbackUrl = getCallbackUrl(envVarConfig);
523
456
  this.secureCookies = getSecureCookies(envVarConfig);
524
457
  this.basePath = getBasePath(envVarConfig);
458
+ if (config?.api?.headers instanceof Headers) {
459
+ this.headers = config?.api?.headers;
460
+ } else if (config?.api?.headers) {
461
+ this.headers = new Headers(config.api.headers);
462
+ }
525
463
  this.routes = config?.api?.routes;
526
464
  this.routePrefix = config?.api?.routePrefix;
527
465
  this.origin = config?.api?.origin;
@@ -1046,7 +984,7 @@ var ResponseError = class {
1046
984
 
1047
985
  // src/utils/fetch.ts
1048
986
  function getTokenFromCookie(headers, cookieKey) {
1049
- const cookie = headers.get("cookie")?.split("; ") ?? getCookie()?.split("; ");
987
+ const cookie = headers.get("cookie")?.split("; ");
1050
988
  const _cookies = {};
1051
989
  if (cookie) {
1052
990
  for (const parts of cookie) {
@@ -1084,22 +1022,24 @@ function getUserFromHttp(headers, config) {
1084
1022
  function makeBasicHeaders(config, url, opts) {
1085
1023
  const { warn, error } = Logger(config, "[headers]");
1086
1024
  const headers = new Headers(opts?.headers);
1087
- headers.set("content-type", "application/json; charset=utf-8");
1088
1025
  const cookieKey = config.api?.cookieKey;
1089
- const authHeader = headers.get("Authorization");
1090
- if (!authHeader) {
1091
- const token = getTokenFromCookie(headers, cookieKey);
1092
- if (token) {
1093
- headers.set("Authorization", `Bearer ${token}`);
1094
- } else if (getToken({ config })) {
1095
- headers.set("Authorization", `Bearer ${getToken({ config })}`);
1026
+ headers.set("content-type", "application/json; charset=utf-8");
1027
+ const origin = headers.get(X_NILE_ORIGIN);
1028
+ if (!origin) {
1029
+ if (config.api.headers) {
1030
+ const localOrigin = config.api.headers.get(X_NILE_ORIGIN);
1031
+ if (localOrigin) {
1032
+ headers.set(X_NILE_ORIGIN, localOrigin);
1033
+ }
1096
1034
  }
1097
1035
  }
1098
1036
  const cookie = headers.get("cookie");
1099
1037
  if (!cookie) {
1100
- const contextCookie = getCookie();
1101
- if (contextCookie) {
1102
- headers.set("cookie", contextCookie);
1038
+ if (config.api.headers) {
1039
+ const configCookie = config.api.headers.get("cookie");
1040
+ if (configCookie) {
1041
+ headers.set("cookie", configCookie);
1042
+ }
1103
1043
  } else {
1104
1044
  if (!url.endsWith("/users")) {
1105
1045
  error(
@@ -1108,14 +1048,20 @@ function makeBasicHeaders(config, url, opts) {
1108
1048
  }
1109
1049
  }
1110
1050
  }
1051
+ const authHeader = headers.get("Authorization");
1052
+ if (!authHeader) {
1053
+ const token = getTokenFromCookie(headers, cookieKey);
1054
+ if (token) {
1055
+ headers.set("Authorization", `Bearer ${token}`);
1056
+ } else if (getToken({ config })) {
1057
+ headers.set("Authorization", `Bearer ${getToken({ config })}`);
1058
+ }
1059
+ }
1111
1060
  if (config && config.api.secureCookies != null) {
1112
1061
  headers.set(X_NILE_SECURECOOKIES, String(config.api.secureCookies));
1113
1062
  }
1114
- const savedOrigin = getOrigin();
1115
1063
  if (config && config.api.origin) {
1116
1064
  headers.set(X_NILE_ORIGIN, config.api.origin);
1117
- } else if (savedOrigin) {
1118
- headers.set(X_NILE_ORIGIN, savedOrigin);
1119
1065
  } else {
1120
1066
  warn(
1121
1067
  "nile.origin missing from header, which defaults to secure cookies only."
@@ -1147,7 +1093,8 @@ async function _fetch(config, path, opts) {
1147
1093
  error("[fetch][response]", {
1148
1094
  message: e.message,
1149
1095
  stack: e.stack,
1150
- debug: "Is nile-auth running?"
1096
+ debug: "Is nile-auth running?",
1097
+ cause: e.cause
1151
1098
  });
1152
1099
  return new Error(e);
1153
1100
  });
@@ -2473,6 +2420,52 @@ var Users = class extends Config {
2473
2420
  };
2474
2421
  };
2475
2422
 
2423
+ // src/api/handlers/withContext/index.ts
2424
+ function handlersWithContext(configRoutes, config) {
2425
+ const GET6 = GETTER(configRoutes, config);
2426
+ const POST5 = POSTER(configRoutes, config);
2427
+ const DELETE3 = DELETER(configRoutes, config);
2428
+ const PUT4 = PUTER(configRoutes, config);
2429
+ return {
2430
+ GET: async (req) => {
2431
+ const response = await GET6(req);
2432
+ const updatedConfig = updateConfig(response, config);
2433
+ return { response, nile: new Server(updatedConfig) };
2434
+ },
2435
+ POST: POST5,
2436
+ DELETE: DELETE3,
2437
+ PUT: PUT4
2438
+ };
2439
+ }
2440
+ function updateConfig(response, config) {
2441
+ let origin = "http://localhost:3000";
2442
+ let headers = null;
2443
+ if (response.status === 302) {
2444
+ const location = response.headers.get("location");
2445
+ if (location) {
2446
+ origin = location;
2447
+ }
2448
+ }
2449
+ const setCookies = [];
2450
+ for (const [key12, value] of response.headers) {
2451
+ if (key12.toLowerCase() === "set-cookie") {
2452
+ setCookies.push(value);
2453
+ }
2454
+ }
2455
+ if (setCookies.length > 0) {
2456
+ const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
2457
+ headers = new Headers({ cookie: cookieHeader });
2458
+ }
2459
+ return {
2460
+ ...config,
2461
+ api: {
2462
+ ...config.api,
2463
+ origin,
2464
+ headers: headers ?? void 0
2465
+ }
2466
+ };
2467
+ }
2468
+
2476
2469
  // src/Api.ts
2477
2470
  var Api = class {
2478
2471
  config;
@@ -2482,9 +2475,13 @@ var Api = class {
2482
2475
  routes;
2483
2476
  #headers;
2484
2477
  handlers;
2478
+ handlersWithContext;
2485
2479
  paths;
2486
2480
  constructor(config) {
2487
2481
  this.config = config;
2482
+ if (config?.api.headers) {
2483
+ this.headers = config?.api.headers;
2484
+ }
2488
2485
  this.auth = new Auth(config, void 0, {
2489
2486
  resetHeaders: this.resetHeaders
2490
2487
  });
@@ -2495,6 +2492,7 @@ var Api = class {
2495
2492
  ...config?.api.routes
2496
2493
  };
2497
2494
  this.handlers = Handlers(this.routes, config);
2495
+ this.handlersWithContext = handlersWithContext(this.routes, config);
2498
2496
  this.paths = {
2499
2497
  get: [
2500
2498
  this.routes.ME,
@@ -2546,7 +2544,6 @@ var Api = class {
2546
2544
  };
2547
2545
  resetHeaders = (headers) => {
2548
2546
  this.#headers = new Headers(headers ?? {});
2549
- setContext(new Headers());
2550
2547
  this.reset();
2551
2548
  };
2552
2549
  set headers(headers) {
@@ -2606,13 +2603,22 @@ var Api = class {
2606
2603
  };
2607
2604
  setContext = (req) => {
2608
2605
  if (req instanceof Headers) {
2609
- setContext(req);
2606
+ this.headers = req;
2607
+ return;
2610
2608
  } else if (req instanceof Request) {
2611
- setContext(req.headers);
2609
+ this.headers = new Headers(req.headers);
2610
+ return;
2612
2611
  }
2613
- const { warn } = Logger(this.config, "[API]");
2614
- if (warn) {
2615
- warn("Set context expects a Request or Header object");
2612
+ const headers = new Headers(req);
2613
+ if (headers) {
2614
+ this.headers = headers;
2615
+ } else {
2616
+ const { warn } = Logger(this.config, "[API]");
2617
+ if (warn) {
2618
+ warn(
2619
+ "Set context expects a Request, Header instance or an object of Record<string, string>"
2620
+ );
2621
+ }
2616
2622
  }
2617
2623
  };
2618
2624
  };
@@ -2698,7 +2704,7 @@ var Server = class {
2698
2704
  /**
2699
2705
  * A convenience function that applies a config and ensures whatever was passed is set properly
2700
2706
  */
2701
- getInstance(config) {
2707
+ getInstance(config, req) {
2702
2708
  const _config = { ...this.config, ...config };
2703
2709
  const updatedConfig = new Config(_config);
2704
2710
  this.setConfig(updatedConfig);
@@ -2708,6 +2714,9 @@ var Server = class {
2708
2714
  this.token = updatedConfig.api.token;
2709
2715
  }
2710
2716
  this.databaseId = updatedConfig.databaseId;
2717
+ if (req) {
2718
+ this.api.setContext(req);
2719
+ }
2711
2720
  return this;
2712
2721
  }
2713
2722
  };