@niledatabase/server 5.3.3-alpha.1 → 5.3.3-alpha.3

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
@@ -15,17 +15,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
15
15
  var APIErrorErrorCodeEnum = {
16
16
  InternalError: "internal_error",
17
17
  BadRequest: "bad_request",
18
+ UnsupportedOperation: "unsupported_operation",
18
19
  EntityNotFound: "entity_not_found",
19
20
  DuplicateEntity: "duplicate_entity",
20
21
  InvalidCredentials: "invalid_credentials",
21
22
  UnknownOidcProvider: "unknown_oidc_provider",
23
+ UnknownOidcParty: "unknown_oidc_party",
22
24
  ProviderAlreadyExists: "provider_already_exists",
23
25
  ProviderConfigError: "provider_config_error",
24
26
  ProviderMismatch: "provider_mismatch",
25
27
  ProviderUpdateError: "provider_update_error",
28
+ ProviderDisabled: "provider_disabled",
26
29
  SessionStateMissing: "session_state_missing",
27
30
  SessionStateMismatch: "session_state_mismatch",
28
- OidcCodeMissing: "oidc_code_missing"
31
+ OidcCodeMissing: "oidc_code_missing",
32
+ TenantNotFound: "tenant_not_found",
33
+ ConstraintViolation: "constraint_violation",
34
+ SqlException: "sql_exception",
35
+ DbCreationFailure: "db_creation_failure",
36
+ DbStatusFailure: "db_status_failure",
37
+ DbInitializationFailure: "db_initialization_failure",
38
+ DbConfigMissing: "db_config_missing",
39
+ UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
40
+ EmailSendFailure: "email_send_failure",
41
+ JdbcException: "jdbc_exception",
42
+ OidcException: "oidc_exception",
43
+ RegionMismatch: "region_mismatch",
44
+ CredentialCreationFailure: "credential_creation_failure",
45
+ CredentialPropagationFailure: "credential_propagation_failure"
29
46
  };
30
47
 
31
48
  // src/users/types.ts
@@ -57,7 +74,6 @@ function assertValidUUID(val, fieldName) {
57
74
  }
58
75
 
59
76
  // src/api/utils/routes/index.ts
60
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
61
77
  var DEFAULT_PREFIX = "/api";
62
78
  var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
63
79
  function isValidProviderSlug(value) {
@@ -130,7 +146,7 @@ function filterNullUndefined(obj) {
130
146
  );
131
147
  }
132
148
  function makeRestUrl(apiUrl, path, qp) {
133
- const url = apiUrl || NILEDB_API_URL;
149
+ const url = apiUrl || process.env.NILEDB_API_URL;
134
150
  if (!url) {
135
151
  throw new Error(
136
152
  "An API url is required. Set it via NILEDB_API_URL. Was auto configuration run?"
@@ -140,7 +156,9 @@ function makeRestUrl(apiUrl, path, qp) {
140
156
  filterNullUndefined(qp)
141
157
  );
142
158
  const strParams = params.toString();
143
- return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
159
+ const base = url.replace(/\/+$/, "");
160
+ const cleanPath = path.replace(/^\/+/, "");
161
+ return `${base}/${cleanPath}${strParams ? `?${strParams}` : ""}`;
144
162
  }
145
163
  function normalizePathname(pathname) {
146
164
  const trimmed = pathname.replace(/\/+$/, "");
@@ -303,24 +321,47 @@ function matchesLog(configRoutes, request2) {
303
321
  }
304
322
 
305
323
  // src/api/utils/extensions.ts
324
+ var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
325
+ function resolveExtension(create2, instance) {
326
+ let perServer = extensionInstanceCache.get(instance);
327
+ if (!perServer) {
328
+ perServer = /* @__PURE__ */ new WeakMap();
329
+ extensionInstanceCache.set(instance, perServer);
330
+ }
331
+ let ext = perServer.get(create2);
332
+ if (!ext) {
333
+ ext = create2(instance);
334
+ perServer.set(create2, ext);
335
+ }
336
+ return ext;
337
+ }
338
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
339
+ "host",
340
+ "content-length",
341
+ "transfer-encoding",
342
+ "connection",
343
+ "keep-alive",
344
+ "upgrade"
345
+ ]);
306
346
  function getRequestConfig(params) {
307
- if (typeof params[1] === "object") {
347
+ if (params[1] !== null && typeof params[1] === "object") {
308
348
  return params[1];
309
349
  }
310
350
  return {};
311
351
  }
312
352
  function bindRunExtensions(instance) {
313
353
  return async function runExtensions(toRun, config, params, _init) {
314
- const { debug } = config.logger("[EXTENSIONS]");
354
+ const { debug, warn } = config.logger("[EXTENSIONS]");
315
355
  const extensionConfig = getRequestConfig(
316
356
  Array.isArray(params) ? params : [null, params]
317
357
  );
358
+ let chainedResponse = void 0;
318
359
  if (config.extensions) {
319
360
  for (const create2 of config.extensions) {
320
361
  if (typeof create2 !== "function") {
321
362
  continue;
322
363
  }
323
- const ext = create2(instance);
364
+ const ext = resolveExtension(create2, instance);
324
365
  if (extensionConfig.disableExtensions?.includes(ext.id)) {
325
366
  continue;
326
367
  }
@@ -351,40 +392,86 @@ function bindRunExtensions(instance) {
351
392
  continue;
352
393
  }
353
394
  const previousHeaders = new Headers(previousContext.headers);
395
+ let returnedInit = void 0;
354
396
  try {
355
- await ext.onRequest(_init.request, ctx);
356
- } catch {
397
+ returnedInit = await ext.onRequest(_init.request, ctx);
398
+ } catch (err) {
399
+ warn(`${ext.id ?? create2.name} onRequest failed`, {
400
+ message: err instanceof Error ? err.message : String(err)
401
+ });
357
402
  }
358
403
  const updatedContext = ctx.get();
359
- if (updatedContext?.headers) {
360
- const cookie = updatedContext.headers.get("cookie");
361
- if (cookie && param.headers) {
404
+ const paramObj = param && typeof param === "object" ? param : void 0;
405
+ if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
406
+ const prevCookie = previousHeaders.get("cookie");
407
+ const nextCookie = updatedContext.headers.get("cookie");
408
+ if (nextCookie && nextCookie !== prevCookie) {
362
409
  const updatedCookies = mergeCookies(
363
- previousHeaders?.get("cookie"),
364
- updatedContext.headers.get("cookie")
410
+ prevCookie,
411
+ paramObj.headers.get("cookie"),
412
+ nextCookie
365
413
  );
366
- param.headers.set("cookie", updatedCookies);
414
+ if (updatedCookies) {
415
+ paramObj.headers.set("cookie", updatedCookies);
416
+ }
367
417
  }
368
- if (updatedContext.tenantId && param.headers) {
369
- param.headers.set(
370
- TENANT_COOKIE,
371
- String(updatedContext.headers.get(TENANT_COOKIE))
372
- );
418
+ updatedContext.headers.forEach((value, key18) => {
419
+ const lower = key18.toLowerCase();
420
+ if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
421
+ return;
422
+ }
423
+ if (previousHeaders.get(key18) !== value) {
424
+ paramObj.headers?.set(key18, value);
425
+ }
426
+ });
427
+ if (updatedContext.tenantId) {
428
+ const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
429
+ paramObj.headers.set(TENANT_COOKIE, tenantHeader);
430
+ }
431
+ } else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
432
+ paramObj.headers.set(
433
+ TENANT_COOKIE,
434
+ String(updatedContext.tenantId)
435
+ );
436
+ }
437
+ if (returnedInit && typeof returnedInit === "object" && paramObj) {
438
+ const { headers: returnedHeaders, ...restInit } = returnedInit;
439
+ Object.assign(paramObj, restInit);
440
+ if (returnedHeaders && paramObj.headers instanceof Headers) {
441
+ new Headers(returnedHeaders).forEach((value, key18) => {
442
+ if (key18.toLowerCase() === "cookie") {
443
+ const merged = mergeCookies(
444
+ paramObj.headers?.get("cookie"),
445
+ value
446
+ );
447
+ if (merged) {
448
+ paramObj.headers?.set("cookie", merged);
449
+ }
450
+ } else {
451
+ paramObj.headers?.set(key18, value);
452
+ }
453
+ });
373
454
  }
374
- ctx.set({ headers: param.headers });
375
455
  }
376
456
  debug(`${ext.id ?? create2.name} ran onRequest`);
377
457
  }
378
458
  if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
379
- const result = await ext.onResponse(param, ctx);
459
+ let responseParam = param;
460
+ if (chainedResponse instanceof Response && param && typeof param === "object") {
461
+ responseParam = {
462
+ ...param,
463
+ response: chainedResponse
464
+ };
465
+ }
466
+ const result = await ext.onResponse(responseParam, ctx);
380
467
  debug(`${ext.id ?? create2.name} ran onResponse`);
381
468
  if (result != null) {
382
- return result;
469
+ chainedResponse = result;
383
470
  }
384
471
  }
385
472
  }
386
473
  }
387
- return void 0;
474
+ return chainedResponse;
388
475
  };
389
476
  }
390
477
  function buildExtensionConfig(instance) {
@@ -396,8 +483,12 @@ function mergeCookies(...cookieStrings) {
396
483
  const cookieMap = /* @__PURE__ */ new Map();
397
484
  for (const str of cookieStrings) {
398
485
  if (!str) continue;
399
- for (const part of str.split(";")) {
400
- const [key18, value] = part.split("=").map((s) => s.trim());
486
+ for (const part of str.split(/;\s*/)) {
487
+ if (!part) continue;
488
+ const eqIdx = part.indexOf("=");
489
+ if (eqIdx <= 0) continue;
490
+ const key18 = part.slice(0, eqIdx).trim();
491
+ const value = part.slice(eqIdx + 1).trim();
401
492
  if (key18 && value) cookieMap.set(key18, value);
402
493
  }
403
494
  }
@@ -425,6 +516,7 @@ async function runExtensionContext(config, options) {
425
516
  // src/api/utils/request-context.ts
426
517
  var storage = new AsyncLocalStorage();
427
518
  var hydratedStores = /* @__PURE__ */ new WeakSet();
519
+ var storeOwners = /* @__PURE__ */ new WeakMap();
428
520
  Object.freeze({
429
521
  headers: new Headers(),
430
522
  tenantId: void 0,
@@ -450,6 +542,10 @@ var ctx = {
450
542
  if (hydratedStores.has(inputCtx)) {
451
543
  hydratedStores.add(merged);
452
544
  }
545
+ const owner = storeOwners.get(inputCtx);
546
+ if (owner) {
547
+ storeOwners.set(merged, owner);
548
+ }
453
549
  return storage.run(merged, fn);
454
550
  },
455
551
  get: () => {
@@ -497,7 +593,19 @@ var ctx = {
497
593
  getLastUsed: () => ctx.get()
498
594
  };
499
595
  function shouldUseOwnScopedContext(config, activeStore) {
500
- return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
596
+ if (!config.isScoped) {
597
+ return false;
598
+ }
599
+ if (!activeStore) {
600
+ return true;
601
+ }
602
+ if (config.boundStore === activeStore) {
603
+ return false;
604
+ }
605
+ if (storeOwners.get(activeStore) === config) {
606
+ return false;
607
+ }
608
+ return true;
501
609
  }
502
610
  async function resolveNileContext(config, options = {}) {
503
611
  const active = storage.getStore();
@@ -564,6 +672,9 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
564
672
  }
565
673
  const resolved = await resolveNileContext(config, options);
566
674
  hydratedStores.add(resolved);
675
+ if (config.isScoped) {
676
+ storeOwners.set(resolved, config);
677
+ }
567
678
  const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
568
679
  return ctx.run(resolved, async () => {
569
680
  try {
@@ -579,11 +690,14 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
579
690
  });
580
691
  }
581
692
  function parseCookieHeader(header) {
582
- return header.split(";").map((c) => c.trim()).filter(Boolean).reduce((acc, curr) => {
583
- const [key18, ...val] = curr.split("=");
584
- if (key18) acc[key18] = val.join("=");
585
- return acc;
586
- }, {});
693
+ return header.split(";").map((c) => c.trim()).filter(Boolean).reduce(
694
+ (acc, curr) => {
695
+ const [key18, ...val] = curr.split("=");
696
+ if (key18) acc[key18] = val.join("=");
697
+ return acc;
698
+ },
699
+ {}
700
+ );
587
701
  }
588
702
  function serializeCookies(cookies) {
589
703
  return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
@@ -660,27 +774,33 @@ async function request(url, _init, config) {
660
774
  }
661
775
  }
662
776
  const params = { ...init };
663
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
777
+ const lowerMethod = params.method?.toLowerCase();
778
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
779
+ if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
664
780
  try {
665
- updatedHeaders.set("content-type", "application/json");
666
- const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
667
781
  let bodyText;
668
782
  if (bodyStream === request2.body) {
669
783
  try {
670
784
  bodyText = await request2.clone().text();
671
- } catch (e) {
785
+ } catch {
672
786
  bodyText = await new Response(bodyStream).text();
673
787
  }
674
788
  } else {
675
789
  bodyText = await new Response(bodyStream).text();
676
790
  }
677
- try {
678
- params.body = JSON.stringify(JSON.parse(bodyText));
679
- } catch {
680
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
681
- params.body = bodyText;
791
+ if (lowerMethod !== "delete" || bodyText.length > 0) {
792
+ updatedHeaders.set("content-type", "application/json");
793
+ try {
794
+ params.body = JSON.stringify(JSON.parse(bodyText));
795
+ } catch {
796
+ updatedHeaders.set(
797
+ "content-type",
798
+ "application/x-www-form-urlencoded"
799
+ );
800
+ params.body = bodyText;
801
+ }
682
802
  }
683
- } catch (e) {
803
+ } catch {
684
804
  error("Failed to parse request body");
685
805
  }
686
806
  }
@@ -904,11 +1024,13 @@ function getTokenFromCookie(headers, cookieKey) {
904
1024
  if (!cookieHeader) {
905
1025
  return null;
906
1026
  }
907
- const cookies = cookieHeader.split("; ");
1027
+ const cookies = cookieHeader.split(/;\s*/);
908
1028
  for (const parts of cookies) {
909
- const cookieParts = parts.split("=");
910
- const name = cookieParts[0];
911
- const value = cookieParts.slice(1).join("=");
1029
+ if (!parts) continue;
1030
+ const eqIdx = parts.indexOf("=");
1031
+ if (eqIdx <= 0) continue;
1032
+ const name = parts.slice(0, eqIdx).trim();
1033
+ const value = parts.slice(eqIdx + 1);
912
1034
  if (name === cookieKey) {
913
1035
  return value;
914
1036
  }
@@ -1012,7 +1134,11 @@ async function POST2(config, init) {
1012
1134
  if (!isUUID2(tenantId)) {
1013
1135
  return new Response("Invalid tenantId", { status: 400 });
1014
1136
  }
1015
- init.body = JSON.stringify({ email: session.email });
1137
+ const hasIncomingBody = init.body != null || init.request.body != null;
1138
+ if (!hasIncomingBody) {
1139
+ const sessionEmail = session.email ?? session.user?.email;
1140
+ init.body = JSON.stringify({ email: sessionEmail });
1141
+ }
1016
1142
  init.method = "POST";
1017
1143
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
1018
1144
  return await request(url, init, config);
@@ -1060,7 +1186,8 @@ async function fetchTenantUsers(config, method, payload) {
1060
1186
  if (params?.tenantId) {
1061
1187
  q.set("tenantId", params.tenantId);
1062
1188
  }
1063
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}`;
1189
+ const queryString = q.toString();
1190
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
1064
1191
  const m = method;
1065
1192
  const init = {
1066
1193
  method: m,
@@ -1080,7 +1207,7 @@ async function PUT3(config, init) {
1080
1207
  if (!isUUID2(tenantId)) {
1081
1208
  return new Response("Invalid tenantId", { status: 400 });
1082
1209
  }
1083
- if (yurl.searchParams.size > 0) {
1210
+ if (init.request.method === "GET" && yurl.searchParams.size > 0) {
1084
1211
  init.body = new URLSearchParams(yurl.searchParams).toString();
1085
1212
  }
1086
1213
  init.method = "PUT";
@@ -1093,10 +1220,7 @@ async function PUT3(config, init) {
1093
1220
  headers: res?.headers
1094
1221
  });
1095
1222
  }
1096
- return new Response(res?.body, {
1097
- status: res?.status,
1098
- headers: res?.headers
1099
- });
1223
+ return res;
1100
1224
  }
1101
1225
 
1102
1226
  // src/api/routes/tenants/[tenantId]/invite/POST.ts
@@ -1487,10 +1611,7 @@ async function route11(req, config) {
1487
1611
  headers: res.headers
1488
1612
  });
1489
1613
  }
1490
- return new Response(res.body, {
1491
- status: res.status ?? 502,
1492
- headers: res.headers
1493
- });
1614
+ return res;
1494
1615
  } catch (e) {
1495
1616
  error("an error has occurred", {
1496
1617
  message: e instanceof Error ? e.message : String(e)
@@ -1603,10 +1724,7 @@ async function route15(req, config) {
1603
1724
  headers: res?.headers
1604
1725
  });
1605
1726
  }
1606
- return new Response(res?.body, {
1607
- status: res?.status,
1608
- headers: res?.headers
1609
- });
1727
+ return res;
1610
1728
  }
1611
1729
  function matches15(configRoutes, request2) {
1612
1730
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
@@ -1648,10 +1766,7 @@ async function route16(req, config) {
1648
1766
  headers: res?.headers
1649
1767
  });
1650
1768
  }
1651
- return new Response(res?.body, {
1652
- status: res?.status,
1653
- headers: res?.headers
1654
- });
1769
+ return res;
1655
1770
  }
1656
1771
  function matches16(configRoutes, request2) {
1657
1772
  return urlMatches(request2.url, configRoutes[key13]);
@@ -1712,7 +1827,7 @@ function GETTER(configRoutes, config) {
1712
1827
  const req = params[0] instanceof Request ? params[0] : null;
1713
1828
  if (!req) {
1714
1829
  error("Proxy requests failed, a Request object was not passed.");
1715
- return;
1830
+ return new Response("Invalid request", { status: 400 });
1716
1831
  }
1717
1832
  if (matches(configRoutes, req)) {
1718
1833
  info("matches me");
@@ -1791,7 +1906,7 @@ async function POST5(config, init) {
1791
1906
  return await request(url, init, config);
1792
1907
  }
1793
1908
 
1794
- // src/api/routes/signup/index.tsx
1909
+ // src/api/routes/signup/index.ts
1795
1910
  var key15 = "SIGNUP";
1796
1911
  async function route18(request2, config) {
1797
1912
  switch (request2.method) {
@@ -1838,7 +1953,7 @@ function POSTER(configRoutes, config) {
1838
1953
  const req = params[0] instanceof Request ? params[0] : null;
1839
1954
  if (!req) {
1840
1955
  error("Proxy requests failed, a Request object was not passed.");
1841
- return;
1956
+ return new Response("Invalid request", { status: 400 });
1842
1957
  }
1843
1958
  if (matchesLog(configRoutes, req)) {
1844
1959
  if (!config.debug) {
@@ -2084,7 +2199,7 @@ function DELETER(configRoutes, config) {
2084
2199
  const req = params[0] instanceof Request ? params[0] : null;
2085
2200
  if (!req) {
2086
2201
  error("Proxy requests failed, a Request object was not passed.");
2087
- return;
2202
+ return new Response("Invalid request", { status: 400 });
2088
2203
  }
2089
2204
  if (matches20(configRoutes, req)) {
2090
2205
  info("matches tenant invite id");
@@ -2126,7 +2241,7 @@ function PUTER(configRoutes, config) {
2126
2241
  const req = params[0] instanceof Request ? params[0] : null;
2127
2242
  if (!req) {
2128
2243
  error("Proxy requests failed, a Request object was not passed.");
2129
- return;
2244
+ return new Response("Invalid request", { status: 400 });
2130
2245
  }
2131
2246
  if (matches4(configRoutes, req)) {
2132
2247
  info("matches tenant invite");
@@ -2198,8 +2313,16 @@ var getSecureCookies = (cfg) => {
2198
2313
  if (config?.secureCookies != null) {
2199
2314
  return config?.secureCookies;
2200
2315
  }
2201
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
2202
- return Boolean(process.env.NILEDB_SECURECOOKIES);
2316
+ const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
2317
+ if (envSecure !== void 0) {
2318
+ const normalized = envSecure.trim().toLowerCase();
2319
+ if (normalized === "false" || normalized === "0") {
2320
+ return false;
2321
+ }
2322
+ if (normalized === "true" || normalized === "1") {
2323
+ return true;
2324
+ }
2325
+ return Boolean(envSecure);
2203
2326
  }
2204
2327
  return void 0;
2205
2328
  };
@@ -2221,9 +2344,9 @@ var getUsername = (cfg) => {
2221
2344
  try {
2222
2345
  const url = new URL(pg2);
2223
2346
  if (url.username) {
2224
- return url.username;
2347
+ return decodeURIComponent(url.username);
2225
2348
  }
2226
- } catch (e) {
2349
+ } catch {
2227
2350
  }
2228
2351
  }
2229
2352
  throw new Error(
@@ -2235,7 +2358,7 @@ var getPassword = (cfg) => {
2235
2358
  const logger = config.logger;
2236
2359
  const log = logProtector(logger);
2237
2360
  if (stringCheck(config?.password)) {
2238
- log && log("[config]").info("***");
2361
+ log?.("[config]").info("***");
2239
2362
  return String(config?.password);
2240
2363
  }
2241
2364
  const pass = stringCheck(process.env.NILEDB_PASSWORD);
@@ -2248,9 +2371,9 @@ var getPassword = (cfg) => {
2248
2371
  try {
2249
2372
  const url = new URL(pg2);
2250
2373
  if (url.password) {
2251
- return url.password;
2374
+ return decodeURIComponent(url.password);
2252
2375
  }
2253
- } catch (e) {
2376
+ } catch {
2254
2377
  }
2255
2378
  }
2256
2379
  throw new Error(
@@ -2269,15 +2392,19 @@ var getDatabaseName = (cfg) => {
2269
2392
  info(`[NILEDB_NAME] ${name}`);
2270
2393
  return name;
2271
2394
  }
2272
- if (process.env.NILEDB_POSTGRES_URL) {
2395
+ const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
2396
+ if (pg2) {
2273
2397
  try {
2274
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
2275
- return pgUrl.pathname.substring(1);
2276
- } catch (e) {
2398
+ const pgUrl = new URL(pg2);
2399
+ const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
2400
+ if (dbName) {
2401
+ return dbName;
2402
+ }
2403
+ } catch {
2277
2404
  }
2278
2405
  }
2279
2406
  throw new Error(
2280
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
2407
+ "A database name is required. Set NILEDB_NAME as an environment variable."
2281
2408
  );
2282
2409
  };
2283
2410
  var getTenantId = (cfg) => {
@@ -2311,7 +2438,7 @@ function getDbHost(cfg) {
2311
2438
  const pgUrl = new URL(pg2);
2312
2439
  info(`[NILEDB_POSTGRES_URL] ${pgUrl.hostname}`);
2313
2440
  return pgUrl.hostname;
2314
- } catch (e) {
2441
+ } catch {
2315
2442
  }
2316
2443
  }
2317
2444
  info("[default] db.thenile.dev");
@@ -2336,7 +2463,7 @@ function getDbPort(cfg) {
2336
2463
  if (pgUrl.port) {
2337
2464
  return Number(pgUrl.port);
2338
2465
  }
2339
- } catch (e) {
2466
+ } catch {
2340
2467
  }
2341
2468
  }
2342
2469
  info("[default] 5432");
@@ -2395,7 +2522,7 @@ var Config = class {
2395
2522
  this.routePrefix = config?.routePrefix ?? "/api";
2396
2523
  this.debug = config?.debug;
2397
2524
  this.origin = config?.origin;
2398
- this.extensions = config?.extensions;
2525
+ this.extensions = config?.extensions ? [...config.extensions] : void 0;
2399
2526
  this.skipHostHeader = config?.skipHostHeader;
2400
2527
  this.extensionCtx = config?.extensionCtx;
2401
2528
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
@@ -2525,7 +2652,6 @@ var eventer = new Eventer();
2525
2652
  var evictPool = (val) => {
2526
2653
  eventer.publish("EvictPool" /* EvictPool */, val);
2527
2654
  };
2528
- var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
2529
2655
  var PoolWithLogger = class extends pg.Pool {
2530
2656
  nileConfig;
2531
2657
  logger;
@@ -2649,6 +2775,7 @@ var PoolWithLogger = class extends pg.Pool {
2649
2775
  };
2650
2776
 
2651
2777
  // src/db/NileInstance.ts
2778
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
2652
2779
  var NileDatabase = class {
2653
2780
  pool;
2654
2781
  tenantId;
@@ -2657,9 +2784,13 @@ var NileDatabase = class {
2657
2784
  logger;
2658
2785
  timer;
2659
2786
  config;
2660
- constructor(config, logger, id, dbContext) {
2787
+ isShuttingDown = false;
2788
+ shutdownPromise = null;
2789
+ onEvict;
2790
+ constructor(config, logger, id, dbContext, onEvict) {
2661
2791
  this.logger = logger("[NileInstance]");
2662
2792
  this.id = id;
2793
+ this.onEvict = onEvict;
2663
2794
  this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
2664
2795
  this.userId = assertValidUUID(dbContext?.userId, "userId");
2665
2796
  if (this.userId && !this.tenantId) {
@@ -2670,10 +2801,12 @@ var NileDatabase = class {
2670
2801
  const poolConfig = {
2671
2802
  min: 0,
2672
2803
  max: 10,
2673
- idleTimeoutMillis: 3e4,
2804
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
2674
2805
  ...config
2675
2806
  };
2676
- const { afterCreate, ...remaining } = poolConfig;
2807
+ const remaining = { ...poolConfig };
2808
+ delete remaining.afterCreate;
2809
+ delete remaining.maxPools;
2677
2810
  this.config = remaining;
2678
2811
  const cloned = { ...config };
2679
2812
  cloned.password = "***";
@@ -2682,63 +2815,88 @@ var NileDatabase = class {
2682
2815
  tenantId: this.tenantId,
2683
2816
  userId: this.userId
2684
2817
  });
2685
- if (typeof afterCreate === "function") {
2686
- this.logger.warn(
2687
- "Providing an pool configuration will stop automatic tenant context setting."
2688
- );
2689
- }
2690
2818
  this.startTimeout();
2691
2819
  this.pool.on("connect", () => {
2692
2820
  this.logger.debug(`pool connected ${this.id}`);
2693
2821
  this.startTimeout();
2694
2822
  });
2695
2823
  this.pool.on("error", (err) => {
2696
- clearTimeout(this.timer);
2697
- this.logger.info(`pool ${this.id} failed`, {
2824
+ this.logger.info(`pool ${this.id} idle client error`, {
2698
2825
  message: err.message,
2699
2826
  stack: err.stack
2700
2827
  });
2701
- evictPool(this.id);
2702
- });
2703
- this.pool.on("release", (destroy) => {
2704
- if (destroy) {
2705
- clearTimeout(this.timer);
2706
- evictPool(this.id);
2707
- this.logger.debug(`destroying pool ${this.id}`);
2708
- }
2709
2828
  });
2710
2829
  }
2830
+ get shuttingDown() {
2831
+ return this.isShuttingDown;
2832
+ }
2833
+ getIdleTimeoutMs() {
2834
+ const raw = this.config.idleTimeoutMillis;
2835
+ if (raw === void 0 || raw === null) {
2836
+ return DEFAULT_IDLE_TIMEOUT_MS;
2837
+ }
2838
+ const parsed = Number(raw);
2839
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2840
+ return null;
2841
+ }
2842
+ return parsed;
2843
+ }
2711
2844
  startTimeout() {
2845
+ if (this.isShuttingDown) {
2846
+ return;
2847
+ }
2712
2848
  const { debug } = this.logger;
2713
2849
  if (this.timer) {
2714
2850
  clearTimeout(this.timer);
2851
+ this.timer = void 0;
2852
+ }
2853
+ const timeoutMs = this.getIdleTimeoutMs();
2854
+ if (timeoutMs === null) {
2855
+ return;
2715
2856
  }
2716
2857
  this.timer = setTimeout(() => {
2717
2858
  debug(
2718
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2859
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
2719
2860
  );
2720
- this.pool.end(() => {
2721
- clearTimeout(this.timer);
2861
+ this.timer = void 0;
2862
+ if (this.onEvict) {
2863
+ this.onEvict(this.id);
2864
+ } else {
2722
2865
  evictPool(this.id);
2723
- });
2724
- }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2866
+ }
2867
+ void this.shutdown();
2868
+ }, timeoutMs);
2869
+ this.timer.unref?.();
2725
2870
  }
2726
2871
  shutdown() {
2872
+ if (this.shutdownPromise) {
2873
+ return this.shutdownPromise;
2874
+ }
2875
+ this.isShuttingDown = true;
2727
2876
  const { debug } = this.logger;
2728
2877
  debug(`attempting to shut down ${this.id}`);
2729
- clearTimeout(this.timer);
2730
- this.pool.end(() => {
2878
+ if (this.timer) {
2879
+ clearTimeout(this.timer);
2880
+ this.timer = void 0;
2881
+ }
2882
+ this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
2731
2883
  debug(`${this.id} has been shut down`);
2884
+ }).catch((err) => {
2885
+ debug(
2886
+ `error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
2887
+ );
2732
2888
  });
2889
+ return this.shutdownPromise;
2733
2890
  }
2734
2891
  };
2735
2892
  var NileInstance_default = NileDatabase;
2736
2893
 
2737
2894
  // src/db/DBManager.ts
2895
+ var DEFAULT_MAX_POOLS = 100;
2738
2896
  var DBManager = class {
2739
2897
  connections;
2740
2898
  cleared;
2741
- poolWatcherFn;
2899
+ maxPools;
2742
2900
  makeId(tenantId, userId) {
2743
2901
  if (tenantId && userId) {
2744
2902
  return `${tenantId}:${userId}`;
@@ -2751,16 +2909,16 @@ var DBManager = class {
2751
2909
  constructor(config) {
2752
2910
  this.cleared = false;
2753
2911
  this.connections = /* @__PURE__ */ new Map();
2754
- this.poolWatcherFn = this.poolWatcher(config);
2755
- watchEvictPool(this.poolWatcherFn);
2912
+ const configuredMax = Number(config.db?.maxPools);
2913
+ this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
2756
2914
  }
2757
- poolWatcher = (config) => (id) => {
2915
+ evict = (config, id) => {
2758
2916
  const { info, warn } = Logger(config)("[DBManager]");
2759
2917
  if (id && this.connections.has(id)) {
2760
2918
  info(`Removing ${id} from db connection pool.`);
2761
2919
  const connection = this.connections.get(id);
2762
- connection?.shutdown();
2763
2920
  this.connections.delete(id);
2921
+ void connection?.shutdown();
2764
2922
  } else {
2765
2923
  warn(`missed eviction of ${id}`);
2766
2924
  }
@@ -2780,18 +2938,47 @@ var DBManager = class {
2780
2938
  }
2781
2939
  const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
2782
2940
  const userId = assertValidUUID(rawContext.userId, "userId");
2941
+ if (userId && !tenantId) {
2942
+ throw new Error(
2943
+ "Cannot scope database connection with userId without a tenantId in context"
2944
+ );
2945
+ }
2783
2946
  const id = this.makeId(tenantId, userId);
2784
2947
  const existing = this.connections.get(id);
2785
2948
  info(`# of instances: ${this.connections.size}`);
2786
- if (existing) {
2949
+ if (existing && !existing.shuttingDown) {
2787
2950
  info(`returning existing ${id}`);
2951
+ this.connections.delete(id);
2952
+ this.connections.set(id, existing);
2788
2953
  existing.startTimeout();
2789
2954
  return existing.pool;
2790
2955
  }
2791
- const newOne = new NileInstance_default(config.db, config.logger, id, {
2792
- tenantId,
2793
- userId
2794
- });
2956
+ if (existing?.shuttingDown) {
2957
+ this.connections.delete(id);
2958
+ }
2959
+ while (this.connections.size >= this.maxPools) {
2960
+ const oldestId = this.connections.keys().next().value;
2961
+ if (!oldestId) {
2962
+ break;
2963
+ }
2964
+ const oldest = this.connections.get(oldestId);
2965
+ this.connections.delete(oldestId);
2966
+ void oldest?.shutdown();
2967
+ }
2968
+ const newOne = new NileInstance_default(
2969
+ config.db,
2970
+ config.logger,
2971
+ id,
2972
+ {
2973
+ tenantId,
2974
+ userId
2975
+ },
2976
+ (evictedId) => {
2977
+ if (this.connections.get(evictedId) === newOne) {
2978
+ this.connections.delete(evictedId);
2979
+ }
2980
+ }
2981
+ );
2795
2982
  this.connections.set(id, newOne);
2796
2983
  info(`created new ${id}`);
2797
2984
  info(`# of instances: ${this.connections.size}`);
@@ -2800,14 +2987,13 @@ var DBManager = class {
2800
2987
  }
2801
2988
  return newOne.pool;
2802
2989
  };
2803
- clear = (config) => {
2990
+ clear = async (config) => {
2804
2991
  const { info } = Logger(config)("[DBManager]");
2805
2992
  info(`Clearing all connections ${this.connections.size}`);
2806
2993
  this.cleared = true;
2807
- this.connections.forEach((connection) => {
2808
- connection.shutdown();
2809
- });
2994
+ const active = Array.from(this.connections.values());
2810
2995
  this.connections.clear();
2996
+ await Promise.allSettled(active.map((connection) => connection.shutdown()));
2811
2997
  };
2812
2998
  };
2813
2999
 
@@ -3019,7 +3205,15 @@ var Auth = class {
3019
3205
  password = body2.password;
3020
3206
  const cbFromHeaders = parseCallback(req.headers);
3021
3207
  if (cbFromHeaders) {
3022
- callbackUrl = cbFromHeaders;
3208
+ const eqIdx = cbFromHeaders.indexOf("=");
3209
+ const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
3210
+ if (rawVal) {
3211
+ try {
3212
+ callbackUrl = decodeURIComponent(rawVal);
3213
+ } catch {
3214
+ callbackUrl = rawVal;
3215
+ }
3216
+ }
3023
3217
  }
3024
3218
  if (body2.callbackUrl) {
3025
3219
  callbackUrl = body2.callbackUrl;
@@ -3051,9 +3245,8 @@ var Auth = class {
3051
3245
  let urlWithParams;
3052
3246
  try {
3053
3247
  const data = await fetchResetPassword(this.#config, "POST", body);
3054
- const cloned = data.clone();
3055
- if (data.status === 400) {
3056
- const text = await cloned.text();
3248
+ if (!data.ok) {
3249
+ const text = await data.clone().text();
3057
3250
  this.#logger.error(text);
3058
3251
  return data;
3059
3252
  }
@@ -3077,25 +3270,32 @@ var Auth = class {
3077
3270
  );
3078
3271
  }
3079
3272
  const { headers } = ctx.get();
3080
- const cookie = headers?.get("cookie")?.split("; ");
3273
+ const existingCookie = headers?.get("cookie");
3274
+ const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
3081
3275
  if (token) {
3082
- cookie?.push(token);
3276
+ cookie.push(token);
3083
3277
  } else {
3084
3278
  throw new Error(
3085
3279
  "Unable to reset password, reset token is missing from response"
3086
3280
  );
3087
3281
  }
3088
- if (cookie) {
3089
- headers?.set("cookie", cookie?.join("; "));
3090
- ctx.set({
3091
- headers
3092
- });
3093
- }
3282
+ headers?.set("cookie", cookie.join("; "));
3283
+ ctx.set({
3284
+ headers
3285
+ });
3094
3286
  const res = await fetchResetPassword(this.#config, "PUT", body);
3095
- cookie?.pop();
3096
- const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
3097
- cleaned.push(String(parseToken(res.headers)));
3098
- const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
3287
+ cookie.pop();
3288
+ const cleaned = cookie.filter(
3289
+ (c) => !c.includes("nile.session")
3290
+ );
3291
+ const nextSessionToken = parseToken(res.headers);
3292
+ if (nextSessionToken) {
3293
+ cleaned.push(nextSessionToken);
3294
+ }
3295
+ const updatedHeaders = new Headers();
3296
+ if (cleaned.length > 0) {
3297
+ updatedHeaders.set("cookie", cleaned.join("; "));
3298
+ }
3099
3299
  ctx.set({ headers: null });
3100
3300
  ctx.set({ headers: updatedHeaders });
3101
3301
  return res;
@@ -3108,19 +3308,21 @@ var Auth = class {
3108
3308
  * `/api/auth/callback/{provider}` via {@link fetchCallback}.
3109
3309
  */
3110
3310
  async callback(provider, body) {
3111
- if (body instanceof Request) {
3112
- ctx.set({
3113
- headers: body.headers
3114
- });
3115
- return await fetchCallback(
3116
- this.#config,
3117
- provider,
3118
- void 0,
3119
- body,
3120
- "GET"
3121
- );
3122
- }
3123
- return await fetchCallback(this.#config, provider, body);
3311
+ return withNileContext(this.#config, async () => {
3312
+ if (body instanceof Request) {
3313
+ ctx.set({
3314
+ headers: body.headers
3315
+ });
3316
+ return await fetchCallback(
3317
+ this.#config,
3318
+ provider,
3319
+ void 0,
3320
+ body,
3321
+ "GET"
3322
+ );
3323
+ }
3324
+ return await fetchCallback(this.#config, provider, body);
3325
+ });
3124
3326
  }
3125
3327
  async signIn(provider, payload, rawResponse) {
3126
3328
  return withNileContext(this.#config, async () => {
@@ -3165,7 +3367,7 @@ var Auth = class {
3165
3367
  );
3166
3368
  }
3167
3369
  const { email, password } = payload ?? {};
3168
- if (provider === "email" && (!email || !password)) {
3370
+ if (provider === "credentials" && (!email || !password)) {
3169
3371
  throw new Error(
3170
3372
  "Server side sign in requires a user email and password."
3171
3373
  );
@@ -3268,62 +3470,72 @@ var Auth = class {
3268
3470
  });
3269
3471
  }
3270
3472
  };
3271
- function parseCSRF(headers) {
3272
- let cookie = headers?.get("set-cookie");
3273
- if (!cookie) {
3274
- cookie = headers?.get("cookie");
3275
- }
3276
- if (!cookie) {
3473
+ function extractNamedCookie(headers, baseName) {
3474
+ if (!headers) {
3277
3475
  return void 0;
3278
3476
  }
3279
- const [, token] = /((__Secure-)?nile\.csrf-token=[^;]+)/.exec(cookie) ?? [];
3280
- return token;
3281
- }
3282
- function parseCallback(headers) {
3283
- let cookie = headers?.get("set-cookie");
3284
- if (!cookie) {
3285
- cookie = headers?.get("cookie");
3477
+ const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
3478
+ let setCookies = [];
3479
+ if (typeof headers.getSetCookie === "function") {
3480
+ setCookies = headers.getSetCookie();
3481
+ } else {
3482
+ const rawSetCookie = headers.get("set-cookie");
3483
+ if (rawSetCookie) {
3484
+ setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
3485
+ }
3486
+ }
3487
+ for (const candidate of setCookies) {
3488
+ for (const segment of candidate.split(/;\s*/)) {
3489
+ const trimmed = segment.trim();
3490
+ if (!trimmed) continue;
3491
+ const eqIdx = trimmed.indexOf("=");
3492
+ if (eqIdx <= 0) continue;
3493
+ const name = trimmed.slice(0, eqIdx).trim();
3494
+ if (allowedNames.has(name)) {
3495
+ return trimmed;
3496
+ }
3497
+ }
3286
3498
  }
3287
- if (!cookie) {
3499
+ const cookieHeader = headers.get("cookie");
3500
+ if (!cookieHeader) {
3288
3501
  return void 0;
3289
3502
  }
3290
- const [, token] = /((__Secure-)?nile\.callback-url=[^;]+)/.exec(cookie) ?? [];
3291
- return token;
3503
+ for (const part of cookieHeader.split(/;\s*/)) {
3504
+ const trimmed = part.trim();
3505
+ if (!trimmed) continue;
3506
+ const eqIdx = trimmed.indexOf("=");
3507
+ if (eqIdx <= 0) continue;
3508
+ const name = trimmed.slice(0, eqIdx).trim();
3509
+ if (allowedNames.has(name)) {
3510
+ return trimmed;
3511
+ }
3512
+ }
3513
+ return void 0;
3514
+ }
3515
+ function parseCSRF(headers) {
3516
+ return extractNamedCookie(headers, "nile.csrf-token");
3517
+ }
3518
+ function parseCallback(headers) {
3519
+ return extractNamedCookie(headers, "nile.callback-url");
3292
3520
  }
3293
3521
  function parseToken(headers) {
3294
- let authCookie = headers?.get("set-cookie");
3295
- if (!authCookie) {
3296
- authCookie = headers?.get("cookie");
3297
- }
3298
- if (!authCookie) {
3299
- return void 0;
3300
- }
3301
- const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
3302
- return token;
3522
+ return extractNamedCookie(headers, "nile.session-token");
3303
3523
  }
3304
3524
  function parseResetToken(headers) {
3305
- let authCookie = headers?.get("set-cookie");
3306
- if (!authCookie) {
3307
- authCookie = headers?.get("cookie");
3308
- }
3309
- if (!authCookie) {
3310
- return void 0;
3311
- }
3312
- const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
3313
- return token;
3525
+ return extractNamedCookie(headers, "nile.reset");
3314
3526
  }
3315
3527
  function parseTenantId(headers) {
3316
- let authCookie = headers?.get("set-cookie");
3317
- if (!authCookie) {
3318
- authCookie = headers?.get("cookie");
3528
+ if (!headers) {
3529
+ return void 0;
3319
3530
  }
3320
- if (!authCookie) {
3531
+ const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
3532
+ if (!hasCookieHeader) {
3321
3533
  return void 0;
3322
3534
  }
3323
- const [, token] = /((__Secure-)?nile\.tenant-id=[^;]+)/.exec(authCookie) ?? [];
3535
+ const token = extractNamedCookie(headers, "nile.tenant-id");
3324
3536
  if (token) {
3325
- const [, tenantId] = token.split("=");
3326
- return tenantId;
3537
+ const eqIdx = token.indexOf("=");
3538
+ return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
3327
3539
  }
3328
3540
  return null;
3329
3541
  }
@@ -3333,10 +3545,16 @@ function defaultCallbackUrl(config) {
3333
3545
  const { headers } = ctx.get();
3334
3546
  const fallbackCb = parseCallback(headers);
3335
3547
  if (fallbackCb) {
3336
- const [, value] = fallbackCb.split("=");
3337
- cb = decodeURIComponent(value);
3548
+ const eqIdx = fallbackCb.indexOf("=");
3549
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3338
3550
  if (value) {
3339
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3551
+ try {
3552
+ cb = decodeURIComponent(value);
3553
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3554
+ } catch {
3555
+ cb = null;
3556
+ redirect = null;
3557
+ }
3340
3558
  }
3341
3559
  }
3342
3560
  return { callbackUrl: cb, redirectUrl: redirect };
@@ -3344,9 +3562,13 @@ function defaultCallbackUrl(config) {
3344
3562
  function fQUrl(path, config) {
3345
3563
  if (path.startsWith("/")) {
3346
3564
  const { callbackUrl } = defaultCallbackUrl(config);
3347
- if (callbackUrl) {
3348
- const { origin } = new URL(callbackUrl);
3349
- return `${origin}${path}`;
3565
+ const base = callbackUrl || config.origin || config.serverOrigin;
3566
+ if (base) {
3567
+ try {
3568
+ const { origin } = new URL(base);
3569
+ return `${origin}${path}`;
3570
+ } catch {
3571
+ }
3350
3572
  }
3351
3573
  }
3352
3574
  try {
@@ -3369,40 +3591,58 @@ async function is2FA(signInRes) {
3369
3591
  }
3370
3592
 
3371
3593
  // src/auth/obtainCsrf.ts
3594
+ function extractCookiePairs(headers) {
3595
+ const map = /* @__PURE__ */ new Map();
3596
+ const cookieHeader = headers.get("cookie");
3597
+ if (cookieHeader) {
3598
+ for (const part of cookieHeader.split(/;\s*/)) {
3599
+ if (!part) continue;
3600
+ const eqIdx = part.indexOf("=");
3601
+ if (eqIdx <= 0) continue;
3602
+ const key18 = part.slice(0, eqIdx).trim();
3603
+ const val = part.slice(eqIdx + 1).trim();
3604
+ if (key18) {
3605
+ map.set(key18, val);
3606
+ }
3607
+ }
3608
+ }
3609
+ return map;
3610
+ }
3611
+ function extractSetCookies(headers) {
3612
+ if (typeof headers.getSetCookie === "function") {
3613
+ const list = headers.getSetCookie();
3614
+ if (list.length > 0) {
3615
+ return list;
3616
+ }
3617
+ }
3618
+ const single = headers.get("set-cookie");
3619
+ return single ? [single] : [];
3620
+ }
3372
3621
  async function obtainCsrf(config, rawResponse = false) {
3373
3622
  const { headers } = ctx.get();
3374
3623
  const res = await fetchCsrf(config);
3375
3624
  const csrfCook = parseCSRF(res.headers);
3376
- if (csrfCook) {
3377
- const [, value] = csrfCook.split("=");
3625
+ const mergedCookies = extractCookiePairs(headers);
3626
+ for (const setCookie of extractSetCookies(res.headers)) {
3627
+ const pair = setCookie.split(";")[0];
3628
+ const eqIdx = pair.indexOf("=");
3629
+ if (eqIdx <= 0) continue;
3630
+ const key18 = pair.slice(0, eqIdx).trim();
3631
+ const val = pair.slice(eqIdx + 1).trim();
3632
+ if (key18) {
3633
+ mergedCookies.set(key18, val);
3634
+ }
3635
+ }
3636
+ if (mergedCookies.size > 0) {
3637
+ const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
3638
+ const cookieUpdate = new Headers({ cookie: serialized });
3639
+ ctx.set({ headers: cookieUpdate });
3640
+ }
3641
+ if (csrfCook && !rawResponse) {
3642
+ const eqIdx = csrfCook.indexOf("=");
3643
+ const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
3378
3644
  const [token] = decodeURIComponent(value).split("|");
3379
- const setCookie = res.headers.get("set-cookie");
3380
- if (setCookie) {
3381
- const cookie = [
3382
- csrfCook,
3383
- parseCallback(res.headers) ?? parseCallback(headers),
3384
- parseToken(res.headers) ?? parseToken(headers)
3385
- ].filter(Boolean).join("; ");
3386
- headers.set("cookie", cookie);
3387
- ctx.set({ headers });
3388
- }
3389
- if (!rawResponse) {
3390
- return { csrfToken: token };
3391
- }
3392
- } else {
3393
- const existingCookie = headers.get("cookie");
3394
- const cookieParts = [];
3395
- if (existingCookie) {
3396
- cookieParts.push(parseToken(headers), parseCallback(headers));
3397
- }
3398
- if (csrfCook) {
3399
- cookieParts.push(csrfCook);
3400
- } else {
3401
- cookieParts.push(parseCSRF(headers));
3402
- }
3403
- const cookie = cookieParts.filter(Boolean).join("; ");
3404
- headers.set("cookie", cookie);
3405
- ctx.set({ headers });
3645
+ return { csrfToken: token };
3406
3646
  }
3407
3647
  if (rawResponse) {
3408
3648
  return res;
@@ -3415,11 +3655,15 @@ async function obtainCsrf(config, rawResponse = false) {
3415
3655
  }
3416
3656
 
3417
3657
  // src/utils/qualifyDomain.ts
3418
- function fQUrl2(callbackUrl, path) {
3658
+ function fQUrl2(callbackUrl, path, fallbackOrigin) {
3419
3659
  if (path.startsWith("/")) {
3420
- if (callbackUrl) {
3421
- const { origin } = new URL(callbackUrl);
3422
- return `${origin}${path}`;
3660
+ const base = callbackUrl || fallbackOrigin;
3661
+ if (base) {
3662
+ try {
3663
+ const { origin } = new URL(base);
3664
+ return `${origin}${path}`;
3665
+ } catch {
3666
+ }
3423
3667
  }
3424
3668
  }
3425
3669
  try {
@@ -3502,18 +3746,22 @@ var Users = class {
3502
3746
  }
3503
3747
  async verifySelf(options, rawResponse = false) {
3504
3748
  return withNileContext(this.#config, async () => {
3505
- const bypassEmail = typeof options === "object" && options?.bypassEmail === true;
3506
- const callbackUrl = fQUrl2(
3507
- defaultCallbackUrl2().callbackUrl,
3508
- typeof options === "object" ? String(options.callbackUrl) : "/"
3509
- );
3749
+ const isRaw = rawResponse || options === true;
3750
+ const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
3751
+ const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
3752
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
3510
3753
  let res;
3511
3754
  try {
3512
3755
  const me = await this.getSelf();
3513
3756
  if (me instanceof Response) {
3514
3757
  return me;
3515
3758
  }
3516
- res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
3759
+ const callbackUrl = fQUrl2(
3760
+ defaultCallbackUrl2().callbackUrl,
3761
+ requestedPath,
3762
+ fallbackOrigin
3763
+ );
3764
+ res = await verifyEmailAddress(this.#config, me, callbackUrl);
3517
3765
  return res;
3518
3766
  } catch (e) {
3519
3767
  if (!bypassEmail) {
@@ -3531,7 +3779,7 @@ var Users = class {
3531
3779
  this.#logger?.info(
3532
3780
  "bypassing email requirements for email verification"
3533
3781
  );
3534
- res = this.updateSelf({ emailVerified: true }, rawResponse);
3782
+ res = await this.updateSelf({ emailVerified: true }, isRaw);
3535
3783
  }
3536
3784
  return res;
3537
3785
  });
@@ -3563,8 +3811,15 @@ function defaultCallbackUrl2() {
3563
3811
  const { headers } = ctx.get();
3564
3812
  const fallbackCb = parseCallback(headers);
3565
3813
  if (fallbackCb) {
3566
- const [, value] = fallbackCb.split("=");
3567
- cb = decodeURIComponent(value);
3814
+ const eqIdx = fallbackCb.indexOf("=");
3815
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3816
+ if (value) {
3817
+ try {
3818
+ cb = decodeURIComponent(value);
3819
+ } catch {
3820
+ cb = value;
3821
+ }
3822
+ }
3568
3823
  }
3569
3824
  return { callbackUrl: cb };
3570
3825
  }
@@ -3589,7 +3844,7 @@ var Tenants = class {
3589
3844
  "POST",
3590
3845
  JSON.stringify({ name: req })
3591
3846
  );
3592
- } else if (typeof req === "object" && ("name" in req || "id" in req)) {
3847
+ } else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3593
3848
  res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
3594
3849
  }
3595
3850
  if (rawResponse) {
@@ -3612,7 +3867,7 @@ var Tenants = class {
3612
3867
  if (typeof req === "string") {
3613
3868
  ctx.set({ tenantId: req });
3614
3869
  }
3615
- if (typeof req === "object" && "id" in req) {
3870
+ if (req != null && typeof req === "object" && "id" in req) {
3616
3871
  ctx.set({ tenantId: req.id });
3617
3872
  }
3618
3873
  const res = await fetchTenant(this.#config, "DELETE");
@@ -3629,7 +3884,7 @@ var Tenants = class {
3629
3884
  return withNileContext(this.#config, async () => {
3630
3885
  if (typeof req === "string") {
3631
3886
  ctx.set({ tenantId: req });
3632
- } else if (typeof req === "object" && "id" in req) {
3887
+ } else if (req != null && typeof req === "object" && "id" in req) {
3633
3888
  ctx.set({ tenantId: req.id });
3634
3889
  }
3635
3890
  const res = await fetchTenant(this.#config, "GET");
@@ -3646,7 +3901,7 @@ var Tenants = class {
3646
3901
  async update(req, rawResponse) {
3647
3902
  return withNileContext(this.#config, async () => {
3648
3903
  let res;
3649
- if (typeof req === "object" && ("name" in req || "id" in req)) {
3904
+ if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3650
3905
  const { id, ...remaining } = req;
3651
3906
  if (id) {
3652
3907
  ctx.set({ tenantId: id });
@@ -3692,9 +3947,12 @@ var Tenants = class {
3692
3947
  async leaveTenant(req) {
3693
3948
  return withNileContext(this.#config, async () => {
3694
3949
  const me = await fetchMe(this.#config);
3950
+ if (me && "ok" in me && !me.ok) {
3951
+ return me;
3952
+ }
3695
3953
  try {
3696
3954
  const json = await me.json();
3697
- if ("id" in json) {
3955
+ if (json && typeof json === "object" && "id" in json) {
3698
3956
  ctx.set({ userId: json.id });
3699
3957
  }
3700
3958
  } catch {
@@ -3765,37 +4023,54 @@ var Tenants = class {
3765
4023
  return withNileContext(
3766
4024
  this.#config,
3767
4025
  async () => {
3768
- const { csrfToken } = await obtainCsrf(
4026
+ const csrfRes = await obtainCsrf(
3769
4027
  this.#config
3770
4028
  );
4029
+ const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
4030
+ if (!csrfToken) {
4031
+ throw new Error("Unable to obtain CSRF token. Invite failed.");
4032
+ }
3771
4033
  const defaults = defaultCallbackUrl3(this.#config);
3772
- let identifier = req;
4034
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4035
+ let identifier = typeof req === "string" ? req : "";
3773
4036
  let callbackUrl = defaults.callbackUrl;
3774
4037
  let redirectUrl = defaults.redirectUrl;
3775
- if (typeof req === "object") {
4038
+ if (req != null && typeof req === "object") {
3776
4039
  if ("email" in req) {
3777
4040
  identifier = req.email;
3778
4041
  }
3779
- const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3780
4042
  if ("callbackUrl" in req) {
3781
- callbackUrl = fQUrl2(cbUrl, req.callbackUrl ?? "/");
4043
+ callbackUrl = fQUrl2(
4044
+ defaults.callbackUrl,
4045
+ req.callbackUrl ?? "/",
4046
+ fallbackOrigin
4047
+ );
3782
4048
  }
3783
4049
  if ("redirectUrl" in req) {
3784
- redirectUrl = fQUrl2(cbUrl, req.redirectUrl ?? "/");
4050
+ redirectUrl = fQUrl2(
4051
+ defaults.callbackUrl,
4052
+ req.redirectUrl ?? "/",
4053
+ fallbackOrigin
4054
+ );
3785
4055
  }
3786
4056
  }
3787
4057
  const { headers } = ctx.get();
3788
4058
  headers?.set("Content-Type", "application/x-www-form-urlencoded");
3789
4059
  ctx.set({ headers });
4060
+ const formParams = new URLSearchParams({
4061
+ identifier,
4062
+ csrfToken
4063
+ });
4064
+ if (callbackUrl) {
4065
+ formParams.set("callbackUrl", callbackUrl);
4066
+ }
4067
+ if (redirectUrl) {
4068
+ formParams.set("redirectUrl", redirectUrl);
4069
+ }
3790
4070
  const res = await fetchInvite(
3791
4071
  this.#config,
3792
4072
  "POST",
3793
- new URLSearchParams({
3794
- identifier,
3795
- csrfToken,
3796
- callbackUrl,
3797
- redirectUrl
3798
- }).toString()
4073
+ formParams.toString()
3799
4074
  );
3800
4075
  return responseHandler(res, rawResponse);
3801
4076
  },
@@ -3815,7 +4090,8 @@ var Tenants = class {
3815
4090
  }
3816
4091
  const { identifier, token } = req;
3817
4092
  const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3818
- const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/");
4093
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4094
+ const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
3819
4095
  const res = await fetchInvite(
3820
4096
  this.#config,
3821
4097
  "PUT",
@@ -3836,9 +4112,9 @@ var Tenants = class {
3836
4112
  async deleteInvite(req) {
3837
4113
  return withNileContext(this.#config, async () => {
3838
4114
  let id = "";
3839
- if (typeof req === "object") {
4115
+ if (req != null && typeof req === "object") {
3840
4116
  id = req.id;
3841
- } else {
4117
+ } else if (typeof req === "string") {
3842
4118
  id = req;
3843
4119
  }
3844
4120
  if (!id) {
@@ -3849,12 +4125,14 @@ var Tenants = class {
3849
4125
  });
3850
4126
  }
3851
4127
  #handleContext(req) {
3852
- if (typeof req === "object") {
4128
+ if (req != null && typeof req === "object") {
3853
4129
  if ("tenantId" in req) {
3854
4130
  ctx.set({ tenantId: req.tenantId });
3855
4131
  }
3856
4132
  if ("userId" in req) {
3857
4133
  ctx.set({ userId: req.userId });
4134
+ } else if ("id" in req) {
4135
+ ctx.set({ userId: req.id });
3858
4136
  }
3859
4137
  }
3860
4138
  }
@@ -3875,78 +4153,183 @@ function defaultCallbackUrl3(config) {
3875
4153
  const { headers, tenantId } = ctx.get();
3876
4154
  const fallbackCb = parseCallback(headers);
3877
4155
  if (fallbackCb) {
3878
- const [, value] = fallbackCb.split("=");
3879
- cb = decodeURIComponent(value);
4156
+ const eqIdx = fallbackCb.indexOf("=");
4157
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3880
4158
  if (value) {
3881
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", String(tenantId))}`;
4159
+ try {
4160
+ cb = decodeURIComponent(value);
4161
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
4162
+ "{tenantId}",
4163
+ String(tenantId)
4164
+ )}`;
4165
+ } catch {
4166
+ cb = null;
4167
+ redirect = null;
4168
+ }
3882
4169
  }
3883
4170
  }
3884
4171
  return { callbackUrl: cb, redirectUrl: redirect };
3885
4172
  }
3886
4173
 
3887
4174
  // src/api/handlers/withContext/index.ts
3888
- function handlersWithContext(config) {
4175
+ function handlersWithContext(config, spawnScoped) {
3889
4176
  const GET7 = GETTER(config.routes, config);
3890
4177
  const POST6 = POSTER(config.routes, config);
3891
4178
  const DELETE5 = DELETER(config.routes, config);
3892
4179
  const PUT6 = PUTER(config.routes, config);
4180
+ const createRequestServer = (response, req) => {
4181
+ if (spawnScoped) {
4182
+ const { context, origin } = buildScopedContext(response, config, req);
4183
+ return spawnScoped(context, { origin });
4184
+ }
4185
+ const updatedConfig = updateConfig(response, config, req);
4186
+ return new Server(updatedConfig);
4187
+ };
3893
4188
  return {
3894
4189
  GET: async (req) => {
3895
4190
  const response = await GET7(req);
3896
- const updatedConfig = updateConfig(response, config);
3897
- return { response, nile: new Server(updatedConfig) };
4191
+ return {
4192
+ response,
4193
+ nile: createRequestServer(response, req)
4194
+ };
3898
4195
  },
3899
4196
  POST: async (req) => {
3900
4197
  const response = await POST6(req);
3901
- const updatedConfig = updateConfig(response, config);
3902
- return { response, nile: new Server(updatedConfig) };
4198
+ return {
4199
+ response,
4200
+ nile: createRequestServer(response, req)
4201
+ };
3903
4202
  },
3904
4203
  DELETE: async (req) => {
3905
4204
  const response = await DELETE5(req);
3906
- const updatedConfig = updateConfig(response, config);
3907
- return { response, nile: new Server(updatedConfig) };
4205
+ return {
4206
+ response,
4207
+ nile: createRequestServer(response, req)
4208
+ };
3908
4209
  },
3909
4210
  PUT: async (req) => {
3910
4211
  const response = await PUT6(req);
3911
- const updatedConfig = updateConfig(response, config);
3912
- return { response, nile: new Server(updatedConfig) };
4212
+ return {
4213
+ response,
4214
+ nile: createRequestServer(response, req)
4215
+ };
3913
4216
  }
3914
4217
  };
3915
4218
  }
3916
- function updateConfig(response, config) {
3917
- let origin = "http://localhost:3000";
3918
- let headers = null;
3919
- if (response instanceof Response) {
3920
- if (response?.status === 302) {
3921
- const location = response.headers.get("location");
3922
- if (location) {
3923
- const urlLocation = new URL(location);
3924
- origin = urlLocation.origin;
4219
+ function parseCookieString(cookieHeader) {
4220
+ const map = /* @__PURE__ */ new Map();
4221
+ if (!cookieHeader) {
4222
+ return map;
4223
+ }
4224
+ for (const part of cookieHeader.split(/;\s*/)) {
4225
+ if (!part) continue;
4226
+ const eqIdx = part.indexOf("=");
4227
+ if (eqIdx <= 0) continue;
4228
+ const name = part.slice(0, eqIdx).trim();
4229
+ const value = part.slice(eqIdx + 1).trim();
4230
+ if (name) {
4231
+ map.set(name, value);
4232
+ }
4233
+ }
4234
+ return map;
4235
+ }
4236
+ function getResponseSetCookies(response) {
4237
+ if (typeof response.headers?.getSetCookie === "function") {
4238
+ const cookies = response.headers.getSetCookie();
4239
+ if (cookies.length > 0) {
4240
+ return cookies;
4241
+ }
4242
+ }
4243
+ const collected = [];
4244
+ if (response.headers) {
4245
+ for (const [key18, value] of response.headers) {
4246
+ if (key18.toLowerCase() === "set-cookie") {
4247
+ collected.push(value);
3925
4248
  }
3926
4249
  }
3927
- const setCookies = [];
3928
- if (response?.headers) {
3929
- for (const [key18, value] of response.headers) {
3930
- if (key18.toLowerCase() === "set-cookie") {
3931
- setCookies.push(value);
4250
+ }
4251
+ return collected;
4252
+ }
4253
+ function resolveOrigin(response, config, req) {
4254
+ let origin = config.origin ?? config.serverOrigin ?? void 0;
4255
+ if (!origin && req?.url) {
4256
+ try {
4257
+ origin = new URL(req.url).origin;
4258
+ } catch {
4259
+ }
4260
+ }
4261
+ if (response instanceof Response && response.status === 302) {
4262
+ const location = response.headers.get("location");
4263
+ if (location) {
4264
+ try {
4265
+ const base = origin || req?.url || "http://localhost:3000";
4266
+ const urlLocation = new URL(location, base);
4267
+ if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
4268
+ origin = urlLocation.origin;
3932
4269
  }
4270
+ } catch {
3933
4271
  }
3934
4272
  }
3935
- if (setCookies.length > 0) {
3936
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3937
- headers = new Headers({ cookie: cookieHeader });
4273
+ }
4274
+ return origin;
4275
+ }
4276
+ function buildMergedHeaders(response, req, origin) {
4277
+ const cookieMap = parseCookieString(req?.headers?.get("cookie"));
4278
+ if (response instanceof Response) {
4279
+ const setCookies = getResponseSetCookies(response);
4280
+ for (const cookieStr of setCookies) {
4281
+ const [pair, ...attrs] = cookieStr.split(";");
4282
+ const eqIdx = pair.indexOf("=");
4283
+ if (eqIdx <= 0) continue;
4284
+ const name = pair.slice(0, eqIdx).trim();
4285
+ const value = pair.slice(eqIdx + 1).trim();
4286
+ const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
4287
+ if (isClearing) {
4288
+ cookieMap.delete(name);
4289
+ } else if (name) {
4290
+ cookieMap.set(name, value);
4291
+ }
3938
4292
  }
3939
4293
  }
4294
+ const headers = new Headers();
4295
+ if (cookieMap.size > 0) {
4296
+ const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
4297
+ headers.set("cookie", serialized);
4298
+ }
4299
+ if (origin) {
4300
+ headers.set(HEADER_ORIGIN, origin);
4301
+ }
4302
+ const tenantId = cookieMap.get(TENANT_COOKIE);
4303
+ return { headers, tenantId };
4304
+ }
4305
+ function buildScopedContext(response, config, req) {
4306
+ const origin = resolveOrigin(response, config, req);
4307
+ const { headers, tenantId } = buildMergedHeaders(response, req, origin);
4308
+ return {
4309
+ origin,
4310
+ context: {
4311
+ headers,
4312
+ tenantId: tenantId ?? config.context.tenantId,
4313
+ userId: config.context.userId
4314
+ }
4315
+ };
4316
+ }
4317
+ function updateConfig(response, config, req) {
4318
+ const { context, origin } = buildScopedContext(response, config, req);
4319
+ const hasCookies = Boolean(context.headers.get("cookie"));
3940
4320
  return {
3941
4321
  ...config,
4322
+ user: config.db?.user,
4323
+ password: typeof config.db?.password === "string" ? config.db.password : void 0,
4324
+ databaseName: config.db?.database,
3942
4325
  origin,
3943
- headers: headers ?? void 0,
4326
+ headers: hasCookies ? context.headers : void 0,
3944
4327
  useLastContext: true
3945
4328
  };
3946
4329
  }
3947
4330
 
3948
4331
  // src/Server.ts
3949
- var SCOPED_INIT = Symbol("SCOPED_INIT");
4332
+ var SCOPED_INIT = /* @__PURE__ */ Symbol("SCOPED_INIT");
3950
4333
  var Server = class _Server {
3951
4334
  users;
3952
4335
  tenants;
@@ -3969,9 +4352,10 @@ var Server = class _Server {
3969
4352
  ...config,
3970
4353
  extensionCtx: buildExtensionConfig(this)
3971
4354
  });
4355
+ const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
3972
4356
  this.#handlers = {
3973
4357
  ...this.#config.handlers,
3974
- withContext: handlersWithContext(this.#config)
4358
+ withContext: handlersWithContext(this.#config, spawnFromHandler)
3975
4359
  };
3976
4360
  if (this.#config.context.tenantId === void 0) {
3977
4361
  this.#config.context.tenantId = getTenantId({
@@ -3983,33 +4367,33 @@ var Server = class _Server {
3983
4367
  this.users = new Users(this.#config);
3984
4368
  this.tenants = new Tenants(this.#config);
3985
4369
  this.auth = new Auth(this.#config);
3986
- if (config?.extensions) {
3987
- for (const create2 of config.extensions) {
3988
- if (typeof create2 !== "function") {
3989
- continue;
3990
- }
3991
- const ext = create2();
3992
- if (typeof ext.onConfigure === "function") {
3993
- this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
3994
- ext.onConfigure(this);
3995
- }
3996
- if (ext?.replace?.handlers) {
3997
- this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
3998
- this.#handlers = ext.replace.handlers({
3999
- ...this.#config.handlers,
4000
- withContext: handlersWithContext(this.#config)
4001
- });
4002
- }
4370
+ if (this.#config.extensions) {
4371
+ for (const create2 of this.#config.extensions) {
4372
+ this.#applyExtension(create2);
4003
4373
  }
4004
4374
  }
4005
4375
  }
4376
+ #applyExtension(create2) {
4377
+ if (typeof create2 !== "function") {
4378
+ return;
4379
+ }
4380
+ const ext = resolveExtension(create2, this);
4381
+ if (typeof ext.onConfigure === "function") {
4382
+ this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4383
+ ext.onConfigure(this);
4384
+ }
4385
+ if (ext?.replace?.handlers) {
4386
+ this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4387
+ this.#handlers = ext.replace.handlers(this.#handlers);
4388
+ }
4389
+ }
4006
4390
  /**
4007
4391
  * Query the database with the current context
4008
4392
  */
4009
4393
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4010
- query = (queryStream, values) => {
4394
+ query = (...args) => {
4011
4395
  const pool = this.#manager.getConnection(this.#config);
4012
- return pool.query(queryStream, values);
4396
+ return pool.query(...args);
4013
4397
  };
4014
4398
  /**
4015
4399
  * Return a db object that can be used to talk to the database
@@ -4018,9 +4402,7 @@ var Server = class _Server {
4018
4402
  get db() {
4019
4403
  const pool = this.#manager.getConnection(this.#config, true);
4020
4404
  return Object.assign(pool, {
4021
- clearConnections: () => {
4022
- this.#manager.clear(this.#config);
4023
- }
4405
+ clearConnections: () => this.#manager.clear(this.#config)
4024
4406
  });
4025
4407
  }
4026
4408
  get logger() {
@@ -4030,7 +4412,9 @@ var Server = class _Server {
4030
4412
  return {
4031
4413
  remove: async (id) => {
4032
4414
  if (!this.#config.extensions) return;
4033
- const resolved = this.#config.extensions.map((ext) => ext());
4415
+ const resolved = this.#config.extensions.map(
4416
+ (ext) => resolveExtension(ext, this)
4417
+ );
4034
4418
  const index = resolved.findIndex((ext) => ext.id === id);
4035
4419
  if (index !== -1) {
4036
4420
  this.#config.extensions.splice(index, 1);
@@ -4042,6 +4426,7 @@ var Server = class _Server {
4042
4426
  this.#config.extensions = [];
4043
4427
  }
4044
4428
  this.#config.extensions.push(extension);
4429
+ this.#applyExtension(extension);
4045
4430
  }
4046
4431
  };
4047
4432
  }
@@ -4122,10 +4507,12 @@ var Server = class _Server {
4122
4507
  }
4123
4508
  return cloneContext(this.#config.context);
4124
4509
  }
4125
- #spawnScoped(scopedContext, boundStore) {
4510
+ #spawnScoped(scopedContext, boundStore, options) {
4511
+ const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
4126
4512
  const clonedConfig = Object.assign(
4127
4513
  Object.create(Config.prototype),
4128
4514
  this.#config,
4515
+ originPatch,
4129
4516
  {
4130
4517
  context: cloneContext(scopedContext),
4131
4518
  isScoped: true,
@@ -4149,12 +4536,12 @@ var Server = class _Server {
4149
4536
  this.#config.context.headers = new Headers();
4150
4537
  if (config instanceof Headers) {
4151
4538
  headers = config;
4152
- } else if (config?.headers) {
4153
- headers = config?.headers;
4154
- if (config && config.origin) {
4539
+ } else if (config) {
4540
+ headers = config.headers;
4541
+ if (config.origin) {
4155
4542
  this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
4156
4543
  }
4157
- if (config && config.secureCookies != null) {
4544
+ if (config.secureCookies != null) {
4158
4545
  this.#config.context.headers.set(
4159
4546
  HEADER_SECURE_COOKIES,
4160
4547
  String(config.secureCookies)