@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.js CHANGED
@@ -21,17 +21,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
21
21
  var APIErrorErrorCodeEnum = {
22
22
  InternalError: "internal_error",
23
23
  BadRequest: "bad_request",
24
+ UnsupportedOperation: "unsupported_operation",
24
25
  EntityNotFound: "entity_not_found",
25
26
  DuplicateEntity: "duplicate_entity",
26
27
  InvalidCredentials: "invalid_credentials",
27
28
  UnknownOidcProvider: "unknown_oidc_provider",
29
+ UnknownOidcParty: "unknown_oidc_party",
28
30
  ProviderAlreadyExists: "provider_already_exists",
29
31
  ProviderConfigError: "provider_config_error",
30
32
  ProviderMismatch: "provider_mismatch",
31
33
  ProviderUpdateError: "provider_update_error",
34
+ ProviderDisabled: "provider_disabled",
32
35
  SessionStateMissing: "session_state_missing",
33
36
  SessionStateMismatch: "session_state_mismatch",
34
- OidcCodeMissing: "oidc_code_missing"
37
+ OidcCodeMissing: "oidc_code_missing",
38
+ TenantNotFound: "tenant_not_found",
39
+ ConstraintViolation: "constraint_violation",
40
+ SqlException: "sql_exception",
41
+ DbCreationFailure: "db_creation_failure",
42
+ DbStatusFailure: "db_status_failure",
43
+ DbInitializationFailure: "db_initialization_failure",
44
+ DbConfigMissing: "db_config_missing",
45
+ UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
46
+ EmailSendFailure: "email_send_failure",
47
+ JdbcException: "jdbc_exception",
48
+ OidcException: "oidc_exception",
49
+ RegionMismatch: "region_mismatch",
50
+ CredentialCreationFailure: "credential_creation_failure",
51
+ CredentialPropagationFailure: "credential_propagation_failure"
35
52
  };
36
53
 
37
54
  // src/users/types.ts
@@ -63,7 +80,6 @@ function assertValidUUID(val, fieldName) {
63
80
  }
64
81
 
65
82
  // src/api/utils/routes/index.ts
66
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
67
83
  var DEFAULT_PREFIX = "/api";
68
84
  var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
69
85
  function isValidProviderSlug(value) {
@@ -136,7 +152,7 @@ function filterNullUndefined(obj) {
136
152
  );
137
153
  }
138
154
  function makeRestUrl(apiUrl, path, qp) {
139
- const url = apiUrl || NILEDB_API_URL;
155
+ const url = apiUrl || process.env.NILEDB_API_URL;
140
156
  if (!url) {
141
157
  throw new Error(
142
158
  "An API url is required. Set it via NILEDB_API_URL. Was auto configuration run?"
@@ -146,7 +162,9 @@ function makeRestUrl(apiUrl, path, qp) {
146
162
  filterNullUndefined(qp)
147
163
  );
148
164
  const strParams = params.toString();
149
- return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
165
+ const base = url.replace(/\/+$/, "");
166
+ const cleanPath = path.replace(/^\/+/, "");
167
+ return `${base}/${cleanPath}${strParams ? `?${strParams}` : ""}`;
150
168
  }
151
169
  function normalizePathname(pathname) {
152
170
  const trimmed = pathname.replace(/\/+$/, "");
@@ -309,24 +327,47 @@ function matchesLog(configRoutes, request2) {
309
327
  }
310
328
 
311
329
  // src/api/utils/extensions.ts
330
+ var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
331
+ function resolveExtension(create2, instance) {
332
+ let perServer = extensionInstanceCache.get(instance);
333
+ if (!perServer) {
334
+ perServer = /* @__PURE__ */ new WeakMap();
335
+ extensionInstanceCache.set(instance, perServer);
336
+ }
337
+ let ext = perServer.get(create2);
338
+ if (!ext) {
339
+ ext = create2(instance);
340
+ perServer.set(create2, ext);
341
+ }
342
+ return ext;
343
+ }
344
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
345
+ "host",
346
+ "content-length",
347
+ "transfer-encoding",
348
+ "connection",
349
+ "keep-alive",
350
+ "upgrade"
351
+ ]);
312
352
  function getRequestConfig(params) {
313
- if (typeof params[1] === "object") {
353
+ if (params[1] !== null && typeof params[1] === "object") {
314
354
  return params[1];
315
355
  }
316
356
  return {};
317
357
  }
318
358
  function bindRunExtensions(instance) {
319
359
  return async function runExtensions(toRun, config, params, _init) {
320
- const { debug } = config.logger("[EXTENSIONS]");
360
+ const { debug, warn } = config.logger("[EXTENSIONS]");
321
361
  const extensionConfig = getRequestConfig(
322
362
  Array.isArray(params) ? params : [null, params]
323
363
  );
364
+ let chainedResponse = void 0;
324
365
  if (config.extensions) {
325
366
  for (const create2 of config.extensions) {
326
367
  if (typeof create2 !== "function") {
327
368
  continue;
328
369
  }
329
- const ext = create2(instance);
370
+ const ext = resolveExtension(create2, instance);
330
371
  if (extensionConfig.disableExtensions?.includes(ext.id)) {
331
372
  continue;
332
373
  }
@@ -357,40 +398,86 @@ function bindRunExtensions(instance) {
357
398
  continue;
358
399
  }
359
400
  const previousHeaders = new Headers(previousContext.headers);
401
+ let returnedInit = void 0;
360
402
  try {
361
- await ext.onRequest(_init.request, ctx);
362
- } catch {
403
+ returnedInit = await ext.onRequest(_init.request, ctx);
404
+ } catch (err) {
405
+ warn(`${ext.id ?? create2.name} onRequest failed`, {
406
+ message: err instanceof Error ? err.message : String(err)
407
+ });
363
408
  }
364
409
  const updatedContext = ctx.get();
365
- if (updatedContext?.headers) {
366
- const cookie = updatedContext.headers.get("cookie");
367
- if (cookie && param.headers) {
410
+ const paramObj = param && typeof param === "object" ? param : void 0;
411
+ if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
412
+ const prevCookie = previousHeaders.get("cookie");
413
+ const nextCookie = updatedContext.headers.get("cookie");
414
+ if (nextCookie && nextCookie !== prevCookie) {
368
415
  const updatedCookies = mergeCookies(
369
- previousHeaders?.get("cookie"),
370
- updatedContext.headers.get("cookie")
416
+ prevCookie,
417
+ paramObj.headers.get("cookie"),
418
+ nextCookie
371
419
  );
372
- param.headers.set("cookie", updatedCookies);
420
+ if (updatedCookies) {
421
+ paramObj.headers.set("cookie", updatedCookies);
422
+ }
373
423
  }
374
- if (updatedContext.tenantId && param.headers) {
375
- param.headers.set(
376
- TENANT_COOKIE,
377
- String(updatedContext.headers.get(TENANT_COOKIE))
378
- );
424
+ updatedContext.headers.forEach((value, key18) => {
425
+ const lower = key18.toLowerCase();
426
+ if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
427
+ return;
428
+ }
429
+ if (previousHeaders.get(key18) !== value) {
430
+ paramObj.headers?.set(key18, value);
431
+ }
432
+ });
433
+ if (updatedContext.tenantId) {
434
+ const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
435
+ paramObj.headers.set(TENANT_COOKIE, tenantHeader);
436
+ }
437
+ } else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
438
+ paramObj.headers.set(
439
+ TENANT_COOKIE,
440
+ String(updatedContext.tenantId)
441
+ );
442
+ }
443
+ if (returnedInit && typeof returnedInit === "object" && paramObj) {
444
+ const { headers: returnedHeaders, ...restInit } = returnedInit;
445
+ Object.assign(paramObj, restInit);
446
+ if (returnedHeaders && paramObj.headers instanceof Headers) {
447
+ new Headers(returnedHeaders).forEach((value, key18) => {
448
+ if (key18.toLowerCase() === "cookie") {
449
+ const merged = mergeCookies(
450
+ paramObj.headers?.get("cookie"),
451
+ value
452
+ );
453
+ if (merged) {
454
+ paramObj.headers?.set("cookie", merged);
455
+ }
456
+ } else {
457
+ paramObj.headers?.set(key18, value);
458
+ }
459
+ });
379
460
  }
380
- ctx.set({ headers: param.headers });
381
461
  }
382
462
  debug(`${ext.id ?? create2.name} ran onRequest`);
383
463
  }
384
464
  if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
385
- const result = await ext.onResponse(param, ctx);
465
+ let responseParam = param;
466
+ if (chainedResponse instanceof Response && param && typeof param === "object") {
467
+ responseParam = {
468
+ ...param,
469
+ response: chainedResponse
470
+ };
471
+ }
472
+ const result = await ext.onResponse(responseParam, ctx);
386
473
  debug(`${ext.id ?? create2.name} ran onResponse`);
387
474
  if (result != null) {
388
- return result;
475
+ chainedResponse = result;
389
476
  }
390
477
  }
391
478
  }
392
479
  }
393
- return void 0;
480
+ return chainedResponse;
394
481
  };
395
482
  }
396
483
  function buildExtensionConfig(instance) {
@@ -402,8 +489,12 @@ function mergeCookies(...cookieStrings) {
402
489
  const cookieMap = /* @__PURE__ */ new Map();
403
490
  for (const str of cookieStrings) {
404
491
  if (!str) continue;
405
- for (const part of str.split(";")) {
406
- const [key18, value] = part.split("=").map((s) => s.trim());
492
+ for (const part of str.split(/;\s*/)) {
493
+ if (!part) continue;
494
+ const eqIdx = part.indexOf("=");
495
+ if (eqIdx <= 0) continue;
496
+ const key18 = part.slice(0, eqIdx).trim();
497
+ const value = part.slice(eqIdx + 1).trim();
407
498
  if (key18 && value) cookieMap.set(key18, value);
408
499
  }
409
500
  }
@@ -431,6 +522,7 @@ async function runExtensionContext(config, options) {
431
522
  // src/api/utils/request-context.ts
432
523
  var storage = new async_hooks.AsyncLocalStorage();
433
524
  var hydratedStores = /* @__PURE__ */ new WeakSet();
525
+ var storeOwners = /* @__PURE__ */ new WeakMap();
434
526
  Object.freeze({
435
527
  headers: new Headers(),
436
528
  tenantId: void 0,
@@ -456,6 +548,10 @@ var ctx = {
456
548
  if (hydratedStores.has(inputCtx)) {
457
549
  hydratedStores.add(merged);
458
550
  }
551
+ const owner = storeOwners.get(inputCtx);
552
+ if (owner) {
553
+ storeOwners.set(merged, owner);
554
+ }
459
555
  return storage.run(merged, fn);
460
556
  },
461
557
  get: () => {
@@ -503,7 +599,19 @@ var ctx = {
503
599
  getLastUsed: () => ctx.get()
504
600
  };
505
601
  function shouldUseOwnScopedContext(config, activeStore) {
506
- return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
602
+ if (!config.isScoped) {
603
+ return false;
604
+ }
605
+ if (!activeStore) {
606
+ return true;
607
+ }
608
+ if (config.boundStore === activeStore) {
609
+ return false;
610
+ }
611
+ if (storeOwners.get(activeStore) === config) {
612
+ return false;
613
+ }
614
+ return true;
507
615
  }
508
616
  async function resolveNileContext(config, options = {}) {
509
617
  const active = storage.getStore();
@@ -570,6 +678,9 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
570
678
  }
571
679
  const resolved = await resolveNileContext(config, options);
572
680
  hydratedStores.add(resolved);
681
+ if (config.isScoped) {
682
+ storeOwners.set(resolved, config);
683
+ }
573
684
  const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
574
685
  return ctx.run(resolved, async () => {
575
686
  try {
@@ -585,11 +696,14 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
585
696
  });
586
697
  }
587
698
  function parseCookieHeader(header) {
588
- return header.split(";").map((c) => c.trim()).filter(Boolean).reduce((acc, curr) => {
589
- const [key18, ...val] = curr.split("=");
590
- if (key18) acc[key18] = val.join("=");
591
- return acc;
592
- }, {});
699
+ return header.split(";").map((c) => c.trim()).filter(Boolean).reduce(
700
+ (acc, curr) => {
701
+ const [key18, ...val] = curr.split("=");
702
+ if (key18) acc[key18] = val.join("=");
703
+ return acc;
704
+ },
705
+ {}
706
+ );
593
707
  }
594
708
  function serializeCookies(cookies) {
595
709
  return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
@@ -666,27 +780,33 @@ async function request(url, _init, config) {
666
780
  }
667
781
  }
668
782
  const params = { ...init };
669
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
783
+ const lowerMethod = params.method?.toLowerCase();
784
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
785
+ if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
670
786
  try {
671
- updatedHeaders.set("content-type", "application/json");
672
- const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
673
787
  let bodyText;
674
788
  if (bodyStream === request2.body) {
675
789
  try {
676
790
  bodyText = await request2.clone().text();
677
- } catch (e) {
791
+ } catch {
678
792
  bodyText = await new Response(bodyStream).text();
679
793
  }
680
794
  } else {
681
795
  bodyText = await new Response(bodyStream).text();
682
796
  }
683
- try {
684
- params.body = JSON.stringify(JSON.parse(bodyText));
685
- } catch {
686
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
687
- params.body = bodyText;
797
+ if (lowerMethod !== "delete" || bodyText.length > 0) {
798
+ updatedHeaders.set("content-type", "application/json");
799
+ try {
800
+ params.body = JSON.stringify(JSON.parse(bodyText));
801
+ } catch {
802
+ updatedHeaders.set(
803
+ "content-type",
804
+ "application/x-www-form-urlencoded"
805
+ );
806
+ params.body = bodyText;
807
+ }
688
808
  }
689
- } catch (e) {
809
+ } catch {
690
810
  error("Failed to parse request body");
691
811
  }
692
812
  }
@@ -910,11 +1030,13 @@ function getTokenFromCookie(headers, cookieKey) {
910
1030
  if (!cookieHeader) {
911
1031
  return null;
912
1032
  }
913
- const cookies = cookieHeader.split("; ");
1033
+ const cookies = cookieHeader.split(/;\s*/);
914
1034
  for (const parts of cookies) {
915
- const cookieParts = parts.split("=");
916
- const name = cookieParts[0];
917
- const value = cookieParts.slice(1).join("=");
1035
+ if (!parts) continue;
1036
+ const eqIdx = parts.indexOf("=");
1037
+ if (eqIdx <= 0) continue;
1038
+ const name = parts.slice(0, eqIdx).trim();
1039
+ const value = parts.slice(eqIdx + 1);
918
1040
  if (name === cookieKey) {
919
1041
  return value;
920
1042
  }
@@ -1018,7 +1140,11 @@ async function POST2(config, init) {
1018
1140
  if (!isUUID2(tenantId)) {
1019
1141
  return new Response("Invalid tenantId", { status: 400 });
1020
1142
  }
1021
- init.body = JSON.stringify({ email: session.email });
1143
+ const hasIncomingBody = init.body != null || init.request.body != null;
1144
+ if (!hasIncomingBody) {
1145
+ const sessionEmail = session.email ?? session.user?.email;
1146
+ init.body = JSON.stringify({ email: sessionEmail });
1147
+ }
1022
1148
  init.method = "POST";
1023
1149
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
1024
1150
  return await request(url, init, config);
@@ -1066,7 +1192,8 @@ async function fetchTenantUsers(config, method, payload) {
1066
1192
  if (params?.tenantId) {
1067
1193
  q.set("tenantId", params.tenantId);
1068
1194
  }
1069
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}`;
1195
+ const queryString = q.toString();
1196
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
1070
1197
  const m = method;
1071
1198
  const init = {
1072
1199
  method: m,
@@ -1086,7 +1213,7 @@ async function PUT3(config, init) {
1086
1213
  if (!isUUID2(tenantId)) {
1087
1214
  return new Response("Invalid tenantId", { status: 400 });
1088
1215
  }
1089
- if (yurl.searchParams.size > 0) {
1216
+ if (init.request.method === "GET" && yurl.searchParams.size > 0) {
1090
1217
  init.body = new URLSearchParams(yurl.searchParams).toString();
1091
1218
  }
1092
1219
  init.method = "PUT";
@@ -1099,10 +1226,7 @@ async function PUT3(config, init) {
1099
1226
  headers: res?.headers
1100
1227
  });
1101
1228
  }
1102
- return new Response(res?.body, {
1103
- status: res?.status,
1104
- headers: res?.headers
1105
- });
1229
+ return res;
1106
1230
  }
1107
1231
 
1108
1232
  // src/api/routes/tenants/[tenantId]/invite/POST.ts
@@ -1493,10 +1617,7 @@ async function route11(req, config) {
1493
1617
  headers: res.headers
1494
1618
  });
1495
1619
  }
1496
- return new Response(res.body, {
1497
- status: res.status ?? 502,
1498
- headers: res.headers
1499
- });
1620
+ return res;
1500
1621
  } catch (e) {
1501
1622
  error("an error has occurred", {
1502
1623
  message: e instanceof Error ? e.message : String(e)
@@ -1609,10 +1730,7 @@ async function route15(req, config) {
1609
1730
  headers: res?.headers
1610
1731
  });
1611
1732
  }
1612
- return new Response(res?.body, {
1613
- status: res?.status,
1614
- headers: res?.headers
1615
- });
1733
+ return res;
1616
1734
  }
1617
1735
  function matches15(configRoutes, request2) {
1618
1736
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
@@ -1654,10 +1772,7 @@ async function route16(req, config) {
1654
1772
  headers: res?.headers
1655
1773
  });
1656
1774
  }
1657
- return new Response(res?.body, {
1658
- status: res?.status,
1659
- headers: res?.headers
1660
- });
1775
+ return res;
1661
1776
  }
1662
1777
  function matches16(configRoutes, request2) {
1663
1778
  return urlMatches(request2.url, configRoutes[key13]);
@@ -1718,7 +1833,7 @@ function GETTER(configRoutes, config) {
1718
1833
  const req = params[0] instanceof Request ? params[0] : null;
1719
1834
  if (!req) {
1720
1835
  error("Proxy requests failed, a Request object was not passed.");
1721
- return;
1836
+ return new Response("Invalid request", { status: 400 });
1722
1837
  }
1723
1838
  if (matches(configRoutes, req)) {
1724
1839
  info("matches me");
@@ -1797,7 +1912,7 @@ async function POST5(config, init) {
1797
1912
  return await request(url, init, config);
1798
1913
  }
1799
1914
 
1800
- // src/api/routes/signup/index.tsx
1915
+ // src/api/routes/signup/index.ts
1801
1916
  var key15 = "SIGNUP";
1802
1917
  async function route18(request2, config) {
1803
1918
  switch (request2.method) {
@@ -1844,7 +1959,7 @@ function POSTER(configRoutes, config) {
1844
1959
  const req = params[0] instanceof Request ? params[0] : null;
1845
1960
  if (!req) {
1846
1961
  error("Proxy requests failed, a Request object was not passed.");
1847
- return;
1962
+ return new Response("Invalid request", { status: 400 });
1848
1963
  }
1849
1964
  if (matchesLog(configRoutes, req)) {
1850
1965
  if (!config.debug) {
@@ -2090,7 +2205,7 @@ function DELETER(configRoutes, config) {
2090
2205
  const req = params[0] instanceof Request ? params[0] : null;
2091
2206
  if (!req) {
2092
2207
  error("Proxy requests failed, a Request object was not passed.");
2093
- return;
2208
+ return new Response("Invalid request", { status: 400 });
2094
2209
  }
2095
2210
  if (matches20(configRoutes, req)) {
2096
2211
  info("matches tenant invite id");
@@ -2132,7 +2247,7 @@ function PUTER(configRoutes, config) {
2132
2247
  const req = params[0] instanceof Request ? params[0] : null;
2133
2248
  if (!req) {
2134
2249
  error("Proxy requests failed, a Request object was not passed.");
2135
- return;
2250
+ return new Response("Invalid request", { status: 400 });
2136
2251
  }
2137
2252
  if (matches4(configRoutes, req)) {
2138
2253
  info("matches tenant invite");
@@ -2204,8 +2319,16 @@ var getSecureCookies = (cfg) => {
2204
2319
  if (config?.secureCookies != null) {
2205
2320
  return config?.secureCookies;
2206
2321
  }
2207
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
2208
- return Boolean(process.env.NILEDB_SECURECOOKIES);
2322
+ const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
2323
+ if (envSecure !== void 0) {
2324
+ const normalized = envSecure.trim().toLowerCase();
2325
+ if (normalized === "false" || normalized === "0") {
2326
+ return false;
2327
+ }
2328
+ if (normalized === "true" || normalized === "1") {
2329
+ return true;
2330
+ }
2331
+ return Boolean(envSecure);
2209
2332
  }
2210
2333
  return void 0;
2211
2334
  };
@@ -2227,9 +2350,9 @@ var getUsername = (cfg) => {
2227
2350
  try {
2228
2351
  const url = new URL(pg2);
2229
2352
  if (url.username) {
2230
- return url.username;
2353
+ return decodeURIComponent(url.username);
2231
2354
  }
2232
- } catch (e) {
2355
+ } catch {
2233
2356
  }
2234
2357
  }
2235
2358
  throw new Error(
@@ -2241,7 +2364,7 @@ var getPassword = (cfg) => {
2241
2364
  const logger = config.logger;
2242
2365
  const log = logProtector(logger);
2243
2366
  if (stringCheck(config?.password)) {
2244
- log && log("[config]").info("***");
2367
+ log?.("[config]").info("***");
2245
2368
  return String(config?.password);
2246
2369
  }
2247
2370
  const pass = stringCheck(process.env.NILEDB_PASSWORD);
@@ -2254,9 +2377,9 @@ var getPassword = (cfg) => {
2254
2377
  try {
2255
2378
  const url = new URL(pg2);
2256
2379
  if (url.password) {
2257
- return url.password;
2380
+ return decodeURIComponent(url.password);
2258
2381
  }
2259
- } catch (e) {
2382
+ } catch {
2260
2383
  }
2261
2384
  }
2262
2385
  throw new Error(
@@ -2275,15 +2398,19 @@ var getDatabaseName = (cfg) => {
2275
2398
  info(`[NILEDB_NAME] ${name}`);
2276
2399
  return name;
2277
2400
  }
2278
- if (process.env.NILEDB_POSTGRES_URL) {
2401
+ const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
2402
+ if (pg2) {
2279
2403
  try {
2280
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
2281
- return pgUrl.pathname.substring(1);
2282
- } catch (e) {
2404
+ const pgUrl = new URL(pg2);
2405
+ const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
2406
+ if (dbName) {
2407
+ return dbName;
2408
+ }
2409
+ } catch {
2283
2410
  }
2284
2411
  }
2285
2412
  throw new Error(
2286
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
2413
+ "A database name is required. Set NILEDB_NAME as an environment variable."
2287
2414
  );
2288
2415
  };
2289
2416
  var getTenantId = (cfg) => {
@@ -2317,7 +2444,7 @@ function getDbHost(cfg) {
2317
2444
  const pgUrl = new URL(pg2);
2318
2445
  info(`[NILEDB_POSTGRES_URL] ${pgUrl.hostname}`);
2319
2446
  return pgUrl.hostname;
2320
- } catch (e) {
2447
+ } catch {
2321
2448
  }
2322
2449
  }
2323
2450
  info("[default] db.thenile.dev");
@@ -2342,7 +2469,7 @@ function getDbPort(cfg) {
2342
2469
  if (pgUrl.port) {
2343
2470
  return Number(pgUrl.port);
2344
2471
  }
2345
- } catch (e) {
2472
+ } catch {
2346
2473
  }
2347
2474
  }
2348
2475
  info("[default] 5432");
@@ -2401,7 +2528,7 @@ var Config = class {
2401
2528
  this.routePrefix = config?.routePrefix ?? "/api";
2402
2529
  this.debug = config?.debug;
2403
2530
  this.origin = config?.origin;
2404
- this.extensions = config?.extensions;
2531
+ this.extensions = config?.extensions ? [...config.extensions] : void 0;
2405
2532
  this.skipHostHeader = config?.skipHostHeader;
2406
2533
  this.extensionCtx = config?.extensionCtx;
2407
2534
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
@@ -2531,7 +2658,6 @@ var eventer = new Eventer();
2531
2658
  var evictPool = (val) => {
2532
2659
  eventer.publish("EvictPool" /* EvictPool */, val);
2533
2660
  };
2534
- var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
2535
2661
  var PoolWithLogger = class extends pg__default.default.Pool {
2536
2662
  nileConfig;
2537
2663
  logger;
@@ -2655,6 +2781,7 @@ var PoolWithLogger = class extends pg__default.default.Pool {
2655
2781
  };
2656
2782
 
2657
2783
  // src/db/NileInstance.ts
2784
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
2658
2785
  var NileDatabase = class {
2659
2786
  pool;
2660
2787
  tenantId;
@@ -2663,9 +2790,13 @@ var NileDatabase = class {
2663
2790
  logger;
2664
2791
  timer;
2665
2792
  config;
2666
- constructor(config, logger, id, dbContext) {
2793
+ isShuttingDown = false;
2794
+ shutdownPromise = null;
2795
+ onEvict;
2796
+ constructor(config, logger, id, dbContext, onEvict) {
2667
2797
  this.logger = logger("[NileInstance]");
2668
2798
  this.id = id;
2799
+ this.onEvict = onEvict;
2669
2800
  this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
2670
2801
  this.userId = assertValidUUID(dbContext?.userId, "userId");
2671
2802
  if (this.userId && !this.tenantId) {
@@ -2676,10 +2807,12 @@ var NileDatabase = class {
2676
2807
  const poolConfig = {
2677
2808
  min: 0,
2678
2809
  max: 10,
2679
- idleTimeoutMillis: 3e4,
2810
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
2680
2811
  ...config
2681
2812
  };
2682
- const { afterCreate, ...remaining } = poolConfig;
2813
+ const remaining = { ...poolConfig };
2814
+ delete remaining.afterCreate;
2815
+ delete remaining.maxPools;
2683
2816
  this.config = remaining;
2684
2817
  const cloned = { ...config };
2685
2818
  cloned.password = "***";
@@ -2688,63 +2821,88 @@ var NileDatabase = class {
2688
2821
  tenantId: this.tenantId,
2689
2822
  userId: this.userId
2690
2823
  });
2691
- if (typeof afterCreate === "function") {
2692
- this.logger.warn(
2693
- "Providing an pool configuration will stop automatic tenant context setting."
2694
- );
2695
- }
2696
2824
  this.startTimeout();
2697
2825
  this.pool.on("connect", () => {
2698
2826
  this.logger.debug(`pool connected ${this.id}`);
2699
2827
  this.startTimeout();
2700
2828
  });
2701
2829
  this.pool.on("error", (err) => {
2702
- clearTimeout(this.timer);
2703
- this.logger.info(`pool ${this.id} failed`, {
2830
+ this.logger.info(`pool ${this.id} idle client error`, {
2704
2831
  message: err.message,
2705
2832
  stack: err.stack
2706
2833
  });
2707
- evictPool(this.id);
2708
- });
2709
- this.pool.on("release", (destroy) => {
2710
- if (destroy) {
2711
- clearTimeout(this.timer);
2712
- evictPool(this.id);
2713
- this.logger.debug(`destroying pool ${this.id}`);
2714
- }
2715
2834
  });
2716
2835
  }
2836
+ get shuttingDown() {
2837
+ return this.isShuttingDown;
2838
+ }
2839
+ getIdleTimeoutMs() {
2840
+ const raw = this.config.idleTimeoutMillis;
2841
+ if (raw === void 0 || raw === null) {
2842
+ return DEFAULT_IDLE_TIMEOUT_MS;
2843
+ }
2844
+ const parsed = Number(raw);
2845
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2846
+ return null;
2847
+ }
2848
+ return parsed;
2849
+ }
2717
2850
  startTimeout() {
2851
+ if (this.isShuttingDown) {
2852
+ return;
2853
+ }
2718
2854
  const { debug } = this.logger;
2719
2855
  if (this.timer) {
2720
2856
  clearTimeout(this.timer);
2857
+ this.timer = void 0;
2858
+ }
2859
+ const timeoutMs = this.getIdleTimeoutMs();
2860
+ if (timeoutMs === null) {
2861
+ return;
2721
2862
  }
2722
2863
  this.timer = setTimeout(() => {
2723
2864
  debug(
2724
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2865
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
2725
2866
  );
2726
- this.pool.end(() => {
2727
- clearTimeout(this.timer);
2867
+ this.timer = void 0;
2868
+ if (this.onEvict) {
2869
+ this.onEvict(this.id);
2870
+ } else {
2728
2871
  evictPool(this.id);
2729
- });
2730
- }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2872
+ }
2873
+ void this.shutdown();
2874
+ }, timeoutMs);
2875
+ this.timer.unref?.();
2731
2876
  }
2732
2877
  shutdown() {
2878
+ if (this.shutdownPromise) {
2879
+ return this.shutdownPromise;
2880
+ }
2881
+ this.isShuttingDown = true;
2733
2882
  const { debug } = this.logger;
2734
2883
  debug(`attempting to shut down ${this.id}`);
2735
- clearTimeout(this.timer);
2736
- this.pool.end(() => {
2884
+ if (this.timer) {
2885
+ clearTimeout(this.timer);
2886
+ this.timer = void 0;
2887
+ }
2888
+ this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
2737
2889
  debug(`${this.id} has been shut down`);
2890
+ }).catch((err) => {
2891
+ debug(
2892
+ `error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
2893
+ );
2738
2894
  });
2895
+ return this.shutdownPromise;
2739
2896
  }
2740
2897
  };
2741
2898
  var NileInstance_default = NileDatabase;
2742
2899
 
2743
2900
  // src/db/DBManager.ts
2901
+ var DEFAULT_MAX_POOLS = 100;
2744
2902
  var DBManager = class {
2745
2903
  connections;
2746
2904
  cleared;
2747
- poolWatcherFn;
2905
+ maxPools;
2748
2906
  makeId(tenantId, userId) {
2749
2907
  if (tenantId && userId) {
2750
2908
  return `${tenantId}:${userId}`;
@@ -2757,16 +2915,16 @@ var DBManager = class {
2757
2915
  constructor(config) {
2758
2916
  this.cleared = false;
2759
2917
  this.connections = /* @__PURE__ */ new Map();
2760
- this.poolWatcherFn = this.poolWatcher(config);
2761
- watchEvictPool(this.poolWatcherFn);
2918
+ const configuredMax = Number(config.db?.maxPools);
2919
+ this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
2762
2920
  }
2763
- poolWatcher = (config) => (id) => {
2921
+ evict = (config, id) => {
2764
2922
  const { info, warn } = Logger(config)("[DBManager]");
2765
2923
  if (id && this.connections.has(id)) {
2766
2924
  info(`Removing ${id} from db connection pool.`);
2767
2925
  const connection = this.connections.get(id);
2768
- connection?.shutdown();
2769
2926
  this.connections.delete(id);
2927
+ void connection?.shutdown();
2770
2928
  } else {
2771
2929
  warn(`missed eviction of ${id}`);
2772
2930
  }
@@ -2786,18 +2944,47 @@ var DBManager = class {
2786
2944
  }
2787
2945
  const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
2788
2946
  const userId = assertValidUUID(rawContext.userId, "userId");
2947
+ if (userId && !tenantId) {
2948
+ throw new Error(
2949
+ "Cannot scope database connection with userId without a tenantId in context"
2950
+ );
2951
+ }
2789
2952
  const id = this.makeId(tenantId, userId);
2790
2953
  const existing = this.connections.get(id);
2791
2954
  info(`# of instances: ${this.connections.size}`);
2792
- if (existing) {
2955
+ if (existing && !existing.shuttingDown) {
2793
2956
  info(`returning existing ${id}`);
2957
+ this.connections.delete(id);
2958
+ this.connections.set(id, existing);
2794
2959
  existing.startTimeout();
2795
2960
  return existing.pool;
2796
2961
  }
2797
- const newOne = new NileInstance_default(config.db, config.logger, id, {
2798
- tenantId,
2799
- userId
2800
- });
2962
+ if (existing?.shuttingDown) {
2963
+ this.connections.delete(id);
2964
+ }
2965
+ while (this.connections.size >= this.maxPools) {
2966
+ const oldestId = this.connections.keys().next().value;
2967
+ if (!oldestId) {
2968
+ break;
2969
+ }
2970
+ const oldest = this.connections.get(oldestId);
2971
+ this.connections.delete(oldestId);
2972
+ void oldest?.shutdown();
2973
+ }
2974
+ const newOne = new NileInstance_default(
2975
+ config.db,
2976
+ config.logger,
2977
+ id,
2978
+ {
2979
+ tenantId,
2980
+ userId
2981
+ },
2982
+ (evictedId) => {
2983
+ if (this.connections.get(evictedId) === newOne) {
2984
+ this.connections.delete(evictedId);
2985
+ }
2986
+ }
2987
+ );
2801
2988
  this.connections.set(id, newOne);
2802
2989
  info(`created new ${id}`);
2803
2990
  info(`# of instances: ${this.connections.size}`);
@@ -2806,14 +2993,13 @@ var DBManager = class {
2806
2993
  }
2807
2994
  return newOne.pool;
2808
2995
  };
2809
- clear = (config) => {
2996
+ clear = async (config) => {
2810
2997
  const { info } = Logger(config)("[DBManager]");
2811
2998
  info(`Clearing all connections ${this.connections.size}`);
2812
2999
  this.cleared = true;
2813
- this.connections.forEach((connection) => {
2814
- connection.shutdown();
2815
- });
3000
+ const active = Array.from(this.connections.values());
2816
3001
  this.connections.clear();
3002
+ await Promise.allSettled(active.map((connection) => connection.shutdown()));
2817
3003
  };
2818
3004
  };
2819
3005
 
@@ -3025,7 +3211,15 @@ var Auth = class {
3025
3211
  password = body2.password;
3026
3212
  const cbFromHeaders = parseCallback(req.headers);
3027
3213
  if (cbFromHeaders) {
3028
- callbackUrl = cbFromHeaders;
3214
+ const eqIdx = cbFromHeaders.indexOf("=");
3215
+ const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
3216
+ if (rawVal) {
3217
+ try {
3218
+ callbackUrl = decodeURIComponent(rawVal);
3219
+ } catch {
3220
+ callbackUrl = rawVal;
3221
+ }
3222
+ }
3029
3223
  }
3030
3224
  if (body2.callbackUrl) {
3031
3225
  callbackUrl = body2.callbackUrl;
@@ -3057,9 +3251,8 @@ var Auth = class {
3057
3251
  let urlWithParams;
3058
3252
  try {
3059
3253
  const data = await fetchResetPassword(this.#config, "POST", body);
3060
- const cloned = data.clone();
3061
- if (data.status === 400) {
3062
- const text = await cloned.text();
3254
+ if (!data.ok) {
3255
+ const text = await data.clone().text();
3063
3256
  this.#logger.error(text);
3064
3257
  return data;
3065
3258
  }
@@ -3083,25 +3276,32 @@ var Auth = class {
3083
3276
  );
3084
3277
  }
3085
3278
  const { headers } = ctx.get();
3086
- const cookie = headers?.get("cookie")?.split("; ");
3279
+ const existingCookie = headers?.get("cookie");
3280
+ const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
3087
3281
  if (token) {
3088
- cookie?.push(token);
3282
+ cookie.push(token);
3089
3283
  } else {
3090
3284
  throw new Error(
3091
3285
  "Unable to reset password, reset token is missing from response"
3092
3286
  );
3093
3287
  }
3094
- if (cookie) {
3095
- headers?.set("cookie", cookie?.join("; "));
3096
- ctx.set({
3097
- headers
3098
- });
3099
- }
3288
+ headers?.set("cookie", cookie.join("; "));
3289
+ ctx.set({
3290
+ headers
3291
+ });
3100
3292
  const res = await fetchResetPassword(this.#config, "PUT", body);
3101
- cookie?.pop();
3102
- const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
3103
- cleaned.push(String(parseToken(res.headers)));
3104
- const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
3293
+ cookie.pop();
3294
+ const cleaned = cookie.filter(
3295
+ (c) => !c.includes("nile.session")
3296
+ );
3297
+ const nextSessionToken = parseToken(res.headers);
3298
+ if (nextSessionToken) {
3299
+ cleaned.push(nextSessionToken);
3300
+ }
3301
+ const updatedHeaders = new Headers();
3302
+ if (cleaned.length > 0) {
3303
+ updatedHeaders.set("cookie", cleaned.join("; "));
3304
+ }
3105
3305
  ctx.set({ headers: null });
3106
3306
  ctx.set({ headers: updatedHeaders });
3107
3307
  return res;
@@ -3114,19 +3314,21 @@ var Auth = class {
3114
3314
  * `/api/auth/callback/{provider}` via {@link fetchCallback}.
3115
3315
  */
3116
3316
  async callback(provider, body) {
3117
- if (body instanceof Request) {
3118
- ctx.set({
3119
- headers: body.headers
3120
- });
3121
- return await fetchCallback(
3122
- this.#config,
3123
- provider,
3124
- void 0,
3125
- body,
3126
- "GET"
3127
- );
3128
- }
3129
- return await fetchCallback(this.#config, provider, body);
3317
+ return withNileContext(this.#config, async () => {
3318
+ if (body instanceof Request) {
3319
+ ctx.set({
3320
+ headers: body.headers
3321
+ });
3322
+ return await fetchCallback(
3323
+ this.#config,
3324
+ provider,
3325
+ void 0,
3326
+ body,
3327
+ "GET"
3328
+ );
3329
+ }
3330
+ return await fetchCallback(this.#config, provider, body);
3331
+ });
3130
3332
  }
3131
3333
  async signIn(provider, payload, rawResponse) {
3132
3334
  return withNileContext(this.#config, async () => {
@@ -3171,7 +3373,7 @@ var Auth = class {
3171
3373
  );
3172
3374
  }
3173
3375
  const { email, password } = payload ?? {};
3174
- if (provider === "email" && (!email || !password)) {
3376
+ if (provider === "credentials" && (!email || !password)) {
3175
3377
  throw new Error(
3176
3378
  "Server side sign in requires a user email and password."
3177
3379
  );
@@ -3274,62 +3476,72 @@ var Auth = class {
3274
3476
  });
3275
3477
  }
3276
3478
  };
3277
- function parseCSRF(headers) {
3278
- let cookie = headers?.get("set-cookie");
3279
- if (!cookie) {
3280
- cookie = headers?.get("cookie");
3281
- }
3282
- if (!cookie) {
3479
+ function extractNamedCookie(headers, baseName) {
3480
+ if (!headers) {
3283
3481
  return void 0;
3284
3482
  }
3285
- const [, token] = /((__Secure-)?nile\.csrf-token=[^;]+)/.exec(cookie) ?? [];
3286
- return token;
3287
- }
3288
- function parseCallback(headers) {
3289
- let cookie = headers?.get("set-cookie");
3290
- if (!cookie) {
3291
- cookie = headers?.get("cookie");
3483
+ const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
3484
+ let setCookies = [];
3485
+ if (typeof headers.getSetCookie === "function") {
3486
+ setCookies = headers.getSetCookie();
3487
+ } else {
3488
+ const rawSetCookie = headers.get("set-cookie");
3489
+ if (rawSetCookie) {
3490
+ setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
3491
+ }
3492
+ }
3493
+ for (const candidate of setCookies) {
3494
+ for (const segment of candidate.split(/;\s*/)) {
3495
+ const trimmed = segment.trim();
3496
+ if (!trimmed) continue;
3497
+ const eqIdx = trimmed.indexOf("=");
3498
+ if (eqIdx <= 0) continue;
3499
+ const name = trimmed.slice(0, eqIdx).trim();
3500
+ if (allowedNames.has(name)) {
3501
+ return trimmed;
3502
+ }
3503
+ }
3292
3504
  }
3293
- if (!cookie) {
3505
+ const cookieHeader = headers.get("cookie");
3506
+ if (!cookieHeader) {
3294
3507
  return void 0;
3295
3508
  }
3296
- const [, token] = /((__Secure-)?nile\.callback-url=[^;]+)/.exec(cookie) ?? [];
3297
- return token;
3509
+ for (const part of cookieHeader.split(/;\s*/)) {
3510
+ const trimmed = part.trim();
3511
+ if (!trimmed) continue;
3512
+ const eqIdx = trimmed.indexOf("=");
3513
+ if (eqIdx <= 0) continue;
3514
+ const name = trimmed.slice(0, eqIdx).trim();
3515
+ if (allowedNames.has(name)) {
3516
+ return trimmed;
3517
+ }
3518
+ }
3519
+ return void 0;
3520
+ }
3521
+ function parseCSRF(headers) {
3522
+ return extractNamedCookie(headers, "nile.csrf-token");
3523
+ }
3524
+ function parseCallback(headers) {
3525
+ return extractNamedCookie(headers, "nile.callback-url");
3298
3526
  }
3299
3527
  function parseToken(headers) {
3300
- let authCookie = headers?.get("set-cookie");
3301
- if (!authCookie) {
3302
- authCookie = headers?.get("cookie");
3303
- }
3304
- if (!authCookie) {
3305
- return void 0;
3306
- }
3307
- const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
3308
- return token;
3528
+ return extractNamedCookie(headers, "nile.session-token");
3309
3529
  }
3310
3530
  function parseResetToken(headers) {
3311
- let authCookie = headers?.get("set-cookie");
3312
- if (!authCookie) {
3313
- authCookie = headers?.get("cookie");
3314
- }
3315
- if (!authCookie) {
3316
- return void 0;
3317
- }
3318
- const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
3319
- return token;
3531
+ return extractNamedCookie(headers, "nile.reset");
3320
3532
  }
3321
3533
  function parseTenantId(headers) {
3322
- let authCookie = headers?.get("set-cookie");
3323
- if (!authCookie) {
3324
- authCookie = headers?.get("cookie");
3534
+ if (!headers) {
3535
+ return void 0;
3325
3536
  }
3326
- if (!authCookie) {
3537
+ const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
3538
+ if (!hasCookieHeader) {
3327
3539
  return void 0;
3328
3540
  }
3329
- const [, token] = /((__Secure-)?nile\.tenant-id=[^;]+)/.exec(authCookie) ?? [];
3541
+ const token = extractNamedCookie(headers, "nile.tenant-id");
3330
3542
  if (token) {
3331
- const [, tenantId] = token.split("=");
3332
- return tenantId;
3543
+ const eqIdx = token.indexOf("=");
3544
+ return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
3333
3545
  }
3334
3546
  return null;
3335
3547
  }
@@ -3339,10 +3551,16 @@ function defaultCallbackUrl(config) {
3339
3551
  const { headers } = ctx.get();
3340
3552
  const fallbackCb = parseCallback(headers);
3341
3553
  if (fallbackCb) {
3342
- const [, value] = fallbackCb.split("=");
3343
- cb = decodeURIComponent(value);
3554
+ const eqIdx = fallbackCb.indexOf("=");
3555
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3344
3556
  if (value) {
3345
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3557
+ try {
3558
+ cb = decodeURIComponent(value);
3559
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3560
+ } catch {
3561
+ cb = null;
3562
+ redirect = null;
3563
+ }
3346
3564
  }
3347
3565
  }
3348
3566
  return { callbackUrl: cb, redirectUrl: redirect };
@@ -3350,9 +3568,13 @@ function defaultCallbackUrl(config) {
3350
3568
  function fQUrl(path, config) {
3351
3569
  if (path.startsWith("/")) {
3352
3570
  const { callbackUrl } = defaultCallbackUrl(config);
3353
- if (callbackUrl) {
3354
- const { origin } = new URL(callbackUrl);
3355
- return `${origin}${path}`;
3571
+ const base = callbackUrl || config.origin || config.serverOrigin;
3572
+ if (base) {
3573
+ try {
3574
+ const { origin } = new URL(base);
3575
+ return `${origin}${path}`;
3576
+ } catch {
3577
+ }
3356
3578
  }
3357
3579
  }
3358
3580
  try {
@@ -3375,40 +3597,58 @@ async function is2FA(signInRes) {
3375
3597
  }
3376
3598
 
3377
3599
  // src/auth/obtainCsrf.ts
3600
+ function extractCookiePairs(headers) {
3601
+ const map = /* @__PURE__ */ new Map();
3602
+ const cookieHeader = headers.get("cookie");
3603
+ if (cookieHeader) {
3604
+ for (const part of cookieHeader.split(/;\s*/)) {
3605
+ if (!part) continue;
3606
+ const eqIdx = part.indexOf("=");
3607
+ if (eqIdx <= 0) continue;
3608
+ const key18 = part.slice(0, eqIdx).trim();
3609
+ const val = part.slice(eqIdx + 1).trim();
3610
+ if (key18) {
3611
+ map.set(key18, val);
3612
+ }
3613
+ }
3614
+ }
3615
+ return map;
3616
+ }
3617
+ function extractSetCookies(headers) {
3618
+ if (typeof headers.getSetCookie === "function") {
3619
+ const list = headers.getSetCookie();
3620
+ if (list.length > 0) {
3621
+ return list;
3622
+ }
3623
+ }
3624
+ const single = headers.get("set-cookie");
3625
+ return single ? [single] : [];
3626
+ }
3378
3627
  async function obtainCsrf(config, rawResponse = false) {
3379
3628
  const { headers } = ctx.get();
3380
3629
  const res = await fetchCsrf(config);
3381
3630
  const csrfCook = parseCSRF(res.headers);
3382
- if (csrfCook) {
3383
- const [, value] = csrfCook.split("=");
3631
+ const mergedCookies = extractCookiePairs(headers);
3632
+ for (const setCookie of extractSetCookies(res.headers)) {
3633
+ const pair = setCookie.split(";")[0];
3634
+ const eqIdx = pair.indexOf("=");
3635
+ if (eqIdx <= 0) continue;
3636
+ const key18 = pair.slice(0, eqIdx).trim();
3637
+ const val = pair.slice(eqIdx + 1).trim();
3638
+ if (key18) {
3639
+ mergedCookies.set(key18, val);
3640
+ }
3641
+ }
3642
+ if (mergedCookies.size > 0) {
3643
+ const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
3644
+ const cookieUpdate = new Headers({ cookie: serialized });
3645
+ ctx.set({ headers: cookieUpdate });
3646
+ }
3647
+ if (csrfCook && !rawResponse) {
3648
+ const eqIdx = csrfCook.indexOf("=");
3649
+ const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
3384
3650
  const [token] = decodeURIComponent(value).split("|");
3385
- const setCookie = res.headers.get("set-cookie");
3386
- if (setCookie) {
3387
- const cookie = [
3388
- csrfCook,
3389
- parseCallback(res.headers) ?? parseCallback(headers),
3390
- parseToken(res.headers) ?? parseToken(headers)
3391
- ].filter(Boolean).join("; ");
3392
- headers.set("cookie", cookie);
3393
- ctx.set({ headers });
3394
- }
3395
- if (!rawResponse) {
3396
- return { csrfToken: token };
3397
- }
3398
- } else {
3399
- const existingCookie = headers.get("cookie");
3400
- const cookieParts = [];
3401
- if (existingCookie) {
3402
- cookieParts.push(parseToken(headers), parseCallback(headers));
3403
- }
3404
- if (csrfCook) {
3405
- cookieParts.push(csrfCook);
3406
- } else {
3407
- cookieParts.push(parseCSRF(headers));
3408
- }
3409
- const cookie = cookieParts.filter(Boolean).join("; ");
3410
- headers.set("cookie", cookie);
3411
- ctx.set({ headers });
3651
+ return { csrfToken: token };
3412
3652
  }
3413
3653
  if (rawResponse) {
3414
3654
  return res;
@@ -3421,11 +3661,15 @@ async function obtainCsrf(config, rawResponse = false) {
3421
3661
  }
3422
3662
 
3423
3663
  // src/utils/qualifyDomain.ts
3424
- function fQUrl2(callbackUrl, path) {
3664
+ function fQUrl2(callbackUrl, path, fallbackOrigin) {
3425
3665
  if (path.startsWith("/")) {
3426
- if (callbackUrl) {
3427
- const { origin } = new URL(callbackUrl);
3428
- return `${origin}${path}`;
3666
+ const base = callbackUrl || fallbackOrigin;
3667
+ if (base) {
3668
+ try {
3669
+ const { origin } = new URL(base);
3670
+ return `${origin}${path}`;
3671
+ } catch {
3672
+ }
3429
3673
  }
3430
3674
  }
3431
3675
  try {
@@ -3508,18 +3752,22 @@ var Users = class {
3508
3752
  }
3509
3753
  async verifySelf(options, rawResponse = false) {
3510
3754
  return withNileContext(this.#config, async () => {
3511
- const bypassEmail = typeof options === "object" && options?.bypassEmail === true;
3512
- const callbackUrl = fQUrl2(
3513
- defaultCallbackUrl2().callbackUrl,
3514
- typeof options === "object" ? String(options.callbackUrl) : "/"
3515
- );
3755
+ const isRaw = rawResponse || options === true;
3756
+ const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
3757
+ const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
3758
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
3516
3759
  let res;
3517
3760
  try {
3518
3761
  const me = await this.getSelf();
3519
3762
  if (me instanceof Response) {
3520
3763
  return me;
3521
3764
  }
3522
- res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
3765
+ const callbackUrl = fQUrl2(
3766
+ defaultCallbackUrl2().callbackUrl,
3767
+ requestedPath,
3768
+ fallbackOrigin
3769
+ );
3770
+ res = await verifyEmailAddress(this.#config, me, callbackUrl);
3523
3771
  return res;
3524
3772
  } catch (e) {
3525
3773
  if (!bypassEmail) {
@@ -3537,7 +3785,7 @@ var Users = class {
3537
3785
  this.#logger?.info(
3538
3786
  "bypassing email requirements for email verification"
3539
3787
  );
3540
- res = this.updateSelf({ emailVerified: true }, rawResponse);
3788
+ res = await this.updateSelf({ emailVerified: true }, isRaw);
3541
3789
  }
3542
3790
  return res;
3543
3791
  });
@@ -3569,8 +3817,15 @@ function defaultCallbackUrl2() {
3569
3817
  const { headers } = ctx.get();
3570
3818
  const fallbackCb = parseCallback(headers);
3571
3819
  if (fallbackCb) {
3572
- const [, value] = fallbackCb.split("=");
3573
- cb = decodeURIComponent(value);
3820
+ const eqIdx = fallbackCb.indexOf("=");
3821
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3822
+ if (value) {
3823
+ try {
3824
+ cb = decodeURIComponent(value);
3825
+ } catch {
3826
+ cb = value;
3827
+ }
3828
+ }
3574
3829
  }
3575
3830
  return { callbackUrl: cb };
3576
3831
  }
@@ -3595,7 +3850,7 @@ var Tenants = class {
3595
3850
  "POST",
3596
3851
  JSON.stringify({ name: req })
3597
3852
  );
3598
- } else if (typeof req === "object" && ("name" in req || "id" in req)) {
3853
+ } else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3599
3854
  res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
3600
3855
  }
3601
3856
  if (rawResponse) {
@@ -3618,7 +3873,7 @@ var Tenants = class {
3618
3873
  if (typeof req === "string") {
3619
3874
  ctx.set({ tenantId: req });
3620
3875
  }
3621
- if (typeof req === "object" && "id" in req) {
3876
+ if (req != null && typeof req === "object" && "id" in req) {
3622
3877
  ctx.set({ tenantId: req.id });
3623
3878
  }
3624
3879
  const res = await fetchTenant(this.#config, "DELETE");
@@ -3635,7 +3890,7 @@ var Tenants = class {
3635
3890
  return withNileContext(this.#config, async () => {
3636
3891
  if (typeof req === "string") {
3637
3892
  ctx.set({ tenantId: req });
3638
- } else if (typeof req === "object" && "id" in req) {
3893
+ } else if (req != null && typeof req === "object" && "id" in req) {
3639
3894
  ctx.set({ tenantId: req.id });
3640
3895
  }
3641
3896
  const res = await fetchTenant(this.#config, "GET");
@@ -3652,7 +3907,7 @@ var Tenants = class {
3652
3907
  async update(req, rawResponse) {
3653
3908
  return withNileContext(this.#config, async () => {
3654
3909
  let res;
3655
- if (typeof req === "object" && ("name" in req || "id" in req)) {
3910
+ if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3656
3911
  const { id, ...remaining } = req;
3657
3912
  if (id) {
3658
3913
  ctx.set({ tenantId: id });
@@ -3698,9 +3953,12 @@ var Tenants = class {
3698
3953
  async leaveTenant(req) {
3699
3954
  return withNileContext(this.#config, async () => {
3700
3955
  const me = await fetchMe(this.#config);
3956
+ if (me && "ok" in me && !me.ok) {
3957
+ return me;
3958
+ }
3701
3959
  try {
3702
3960
  const json = await me.json();
3703
- if ("id" in json) {
3961
+ if (json && typeof json === "object" && "id" in json) {
3704
3962
  ctx.set({ userId: json.id });
3705
3963
  }
3706
3964
  } catch {
@@ -3771,37 +4029,54 @@ var Tenants = class {
3771
4029
  return withNileContext(
3772
4030
  this.#config,
3773
4031
  async () => {
3774
- const { csrfToken } = await obtainCsrf(
4032
+ const csrfRes = await obtainCsrf(
3775
4033
  this.#config
3776
4034
  );
4035
+ const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
4036
+ if (!csrfToken) {
4037
+ throw new Error("Unable to obtain CSRF token. Invite failed.");
4038
+ }
3777
4039
  const defaults = defaultCallbackUrl3(this.#config);
3778
- let identifier = req;
4040
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4041
+ let identifier = typeof req === "string" ? req : "";
3779
4042
  let callbackUrl = defaults.callbackUrl;
3780
4043
  let redirectUrl = defaults.redirectUrl;
3781
- if (typeof req === "object") {
4044
+ if (req != null && typeof req === "object") {
3782
4045
  if ("email" in req) {
3783
4046
  identifier = req.email;
3784
4047
  }
3785
- const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3786
4048
  if ("callbackUrl" in req) {
3787
- callbackUrl = fQUrl2(cbUrl, req.callbackUrl ?? "/");
4049
+ callbackUrl = fQUrl2(
4050
+ defaults.callbackUrl,
4051
+ req.callbackUrl ?? "/",
4052
+ fallbackOrigin
4053
+ );
3788
4054
  }
3789
4055
  if ("redirectUrl" in req) {
3790
- redirectUrl = fQUrl2(cbUrl, req.redirectUrl ?? "/");
4056
+ redirectUrl = fQUrl2(
4057
+ defaults.callbackUrl,
4058
+ req.redirectUrl ?? "/",
4059
+ fallbackOrigin
4060
+ );
3791
4061
  }
3792
4062
  }
3793
4063
  const { headers } = ctx.get();
3794
4064
  headers?.set("Content-Type", "application/x-www-form-urlencoded");
3795
4065
  ctx.set({ headers });
4066
+ const formParams = new URLSearchParams({
4067
+ identifier,
4068
+ csrfToken
4069
+ });
4070
+ if (callbackUrl) {
4071
+ formParams.set("callbackUrl", callbackUrl);
4072
+ }
4073
+ if (redirectUrl) {
4074
+ formParams.set("redirectUrl", redirectUrl);
4075
+ }
3796
4076
  const res = await fetchInvite(
3797
4077
  this.#config,
3798
4078
  "POST",
3799
- new URLSearchParams({
3800
- identifier,
3801
- csrfToken,
3802
- callbackUrl,
3803
- redirectUrl
3804
- }).toString()
4079
+ formParams.toString()
3805
4080
  );
3806
4081
  return responseHandler(res, rawResponse);
3807
4082
  },
@@ -3821,7 +4096,8 @@ var Tenants = class {
3821
4096
  }
3822
4097
  const { identifier, token } = req;
3823
4098
  const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3824
- const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/");
4099
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4100
+ const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
3825
4101
  const res = await fetchInvite(
3826
4102
  this.#config,
3827
4103
  "PUT",
@@ -3842,9 +4118,9 @@ var Tenants = class {
3842
4118
  async deleteInvite(req) {
3843
4119
  return withNileContext(this.#config, async () => {
3844
4120
  let id = "";
3845
- if (typeof req === "object") {
4121
+ if (req != null && typeof req === "object") {
3846
4122
  id = req.id;
3847
- } else {
4123
+ } else if (typeof req === "string") {
3848
4124
  id = req;
3849
4125
  }
3850
4126
  if (!id) {
@@ -3855,12 +4131,14 @@ var Tenants = class {
3855
4131
  });
3856
4132
  }
3857
4133
  #handleContext(req) {
3858
- if (typeof req === "object") {
4134
+ if (req != null && typeof req === "object") {
3859
4135
  if ("tenantId" in req) {
3860
4136
  ctx.set({ tenantId: req.tenantId });
3861
4137
  }
3862
4138
  if ("userId" in req) {
3863
4139
  ctx.set({ userId: req.userId });
4140
+ } else if ("id" in req) {
4141
+ ctx.set({ userId: req.id });
3864
4142
  }
3865
4143
  }
3866
4144
  }
@@ -3881,78 +4159,183 @@ function defaultCallbackUrl3(config) {
3881
4159
  const { headers, tenantId } = ctx.get();
3882
4160
  const fallbackCb = parseCallback(headers);
3883
4161
  if (fallbackCb) {
3884
- const [, value] = fallbackCb.split("=");
3885
- cb = decodeURIComponent(value);
4162
+ const eqIdx = fallbackCb.indexOf("=");
4163
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3886
4164
  if (value) {
3887
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", String(tenantId))}`;
4165
+ try {
4166
+ cb = decodeURIComponent(value);
4167
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
4168
+ "{tenantId}",
4169
+ String(tenantId)
4170
+ )}`;
4171
+ } catch {
4172
+ cb = null;
4173
+ redirect = null;
4174
+ }
3888
4175
  }
3889
4176
  }
3890
4177
  return { callbackUrl: cb, redirectUrl: redirect };
3891
4178
  }
3892
4179
 
3893
4180
  // src/api/handlers/withContext/index.ts
3894
- function handlersWithContext(config) {
4181
+ function handlersWithContext(config, spawnScoped) {
3895
4182
  const GET7 = GETTER(config.routes, config);
3896
4183
  const POST6 = POSTER(config.routes, config);
3897
4184
  const DELETE5 = DELETER(config.routes, config);
3898
4185
  const PUT6 = PUTER(config.routes, config);
4186
+ const createRequestServer = (response, req) => {
4187
+ if (spawnScoped) {
4188
+ const { context, origin } = buildScopedContext(response, config, req);
4189
+ return spawnScoped(context, { origin });
4190
+ }
4191
+ const updatedConfig = updateConfig(response, config, req);
4192
+ return new Server(updatedConfig);
4193
+ };
3899
4194
  return {
3900
4195
  GET: async (req) => {
3901
4196
  const response = await GET7(req);
3902
- const updatedConfig = updateConfig(response, config);
3903
- return { response, nile: new Server(updatedConfig) };
4197
+ return {
4198
+ response,
4199
+ nile: createRequestServer(response, req)
4200
+ };
3904
4201
  },
3905
4202
  POST: async (req) => {
3906
4203
  const response = await POST6(req);
3907
- const updatedConfig = updateConfig(response, config);
3908
- return { response, nile: new Server(updatedConfig) };
4204
+ return {
4205
+ response,
4206
+ nile: createRequestServer(response, req)
4207
+ };
3909
4208
  },
3910
4209
  DELETE: async (req) => {
3911
4210
  const response = await DELETE5(req);
3912
- const updatedConfig = updateConfig(response, config);
3913
- return { response, nile: new Server(updatedConfig) };
4211
+ return {
4212
+ response,
4213
+ nile: createRequestServer(response, req)
4214
+ };
3914
4215
  },
3915
4216
  PUT: async (req) => {
3916
4217
  const response = await PUT6(req);
3917
- const updatedConfig = updateConfig(response, config);
3918
- return { response, nile: new Server(updatedConfig) };
4218
+ return {
4219
+ response,
4220
+ nile: createRequestServer(response, req)
4221
+ };
3919
4222
  }
3920
4223
  };
3921
4224
  }
3922
- function updateConfig(response, config) {
3923
- let origin = "http://localhost:3000";
3924
- let headers = null;
3925
- if (response instanceof Response) {
3926
- if (response?.status === 302) {
3927
- const location = response.headers.get("location");
3928
- if (location) {
3929
- const urlLocation = new URL(location);
3930
- origin = urlLocation.origin;
4225
+ function parseCookieString(cookieHeader) {
4226
+ const map = /* @__PURE__ */ new Map();
4227
+ if (!cookieHeader) {
4228
+ return map;
4229
+ }
4230
+ for (const part of cookieHeader.split(/;\s*/)) {
4231
+ if (!part) continue;
4232
+ const eqIdx = part.indexOf("=");
4233
+ if (eqIdx <= 0) continue;
4234
+ const name = part.slice(0, eqIdx).trim();
4235
+ const value = part.slice(eqIdx + 1).trim();
4236
+ if (name) {
4237
+ map.set(name, value);
4238
+ }
4239
+ }
4240
+ return map;
4241
+ }
4242
+ function getResponseSetCookies(response) {
4243
+ if (typeof response.headers?.getSetCookie === "function") {
4244
+ const cookies = response.headers.getSetCookie();
4245
+ if (cookies.length > 0) {
4246
+ return cookies;
4247
+ }
4248
+ }
4249
+ const collected = [];
4250
+ if (response.headers) {
4251
+ for (const [key18, value] of response.headers) {
4252
+ if (key18.toLowerCase() === "set-cookie") {
4253
+ collected.push(value);
3931
4254
  }
3932
4255
  }
3933
- const setCookies = [];
3934
- if (response?.headers) {
3935
- for (const [key18, value] of response.headers) {
3936
- if (key18.toLowerCase() === "set-cookie") {
3937
- setCookies.push(value);
4256
+ }
4257
+ return collected;
4258
+ }
4259
+ function resolveOrigin(response, config, req) {
4260
+ let origin = config.origin ?? config.serverOrigin ?? void 0;
4261
+ if (!origin && req?.url) {
4262
+ try {
4263
+ origin = new URL(req.url).origin;
4264
+ } catch {
4265
+ }
4266
+ }
4267
+ if (response instanceof Response && response.status === 302) {
4268
+ const location = response.headers.get("location");
4269
+ if (location) {
4270
+ try {
4271
+ const base = origin || req?.url || "http://localhost:3000";
4272
+ const urlLocation = new URL(location, base);
4273
+ if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
4274
+ origin = urlLocation.origin;
3938
4275
  }
4276
+ } catch {
3939
4277
  }
3940
4278
  }
3941
- if (setCookies.length > 0) {
3942
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3943
- headers = new Headers({ cookie: cookieHeader });
4279
+ }
4280
+ return origin;
4281
+ }
4282
+ function buildMergedHeaders(response, req, origin) {
4283
+ const cookieMap = parseCookieString(req?.headers?.get("cookie"));
4284
+ if (response instanceof Response) {
4285
+ const setCookies = getResponseSetCookies(response);
4286
+ for (const cookieStr of setCookies) {
4287
+ const [pair, ...attrs] = cookieStr.split(";");
4288
+ const eqIdx = pair.indexOf("=");
4289
+ if (eqIdx <= 0) continue;
4290
+ const name = pair.slice(0, eqIdx).trim();
4291
+ const value = pair.slice(eqIdx + 1).trim();
4292
+ const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
4293
+ if (isClearing) {
4294
+ cookieMap.delete(name);
4295
+ } else if (name) {
4296
+ cookieMap.set(name, value);
4297
+ }
3944
4298
  }
3945
4299
  }
4300
+ const headers = new Headers();
4301
+ if (cookieMap.size > 0) {
4302
+ const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
4303
+ headers.set("cookie", serialized);
4304
+ }
4305
+ if (origin) {
4306
+ headers.set(HEADER_ORIGIN, origin);
4307
+ }
4308
+ const tenantId = cookieMap.get(TENANT_COOKIE);
4309
+ return { headers, tenantId };
4310
+ }
4311
+ function buildScopedContext(response, config, req) {
4312
+ const origin = resolveOrigin(response, config, req);
4313
+ const { headers, tenantId } = buildMergedHeaders(response, req, origin);
4314
+ return {
4315
+ origin,
4316
+ context: {
4317
+ headers,
4318
+ tenantId: tenantId ?? config.context.tenantId,
4319
+ userId: config.context.userId
4320
+ }
4321
+ };
4322
+ }
4323
+ function updateConfig(response, config, req) {
4324
+ const { context, origin } = buildScopedContext(response, config, req);
4325
+ const hasCookies = Boolean(context.headers.get("cookie"));
3946
4326
  return {
3947
4327
  ...config,
4328
+ user: config.db?.user,
4329
+ password: typeof config.db?.password === "string" ? config.db.password : void 0,
4330
+ databaseName: config.db?.database,
3948
4331
  origin,
3949
- headers: headers ?? void 0,
4332
+ headers: hasCookies ? context.headers : void 0,
3950
4333
  useLastContext: true
3951
4334
  };
3952
4335
  }
3953
4336
 
3954
4337
  // src/Server.ts
3955
- var SCOPED_INIT = Symbol("SCOPED_INIT");
4338
+ var SCOPED_INIT = /* @__PURE__ */ Symbol("SCOPED_INIT");
3956
4339
  var Server = class _Server {
3957
4340
  users;
3958
4341
  tenants;
@@ -3975,9 +4358,10 @@ var Server = class _Server {
3975
4358
  ...config,
3976
4359
  extensionCtx: buildExtensionConfig(this)
3977
4360
  });
4361
+ const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
3978
4362
  this.#handlers = {
3979
4363
  ...this.#config.handlers,
3980
- withContext: handlersWithContext(this.#config)
4364
+ withContext: handlersWithContext(this.#config, spawnFromHandler)
3981
4365
  };
3982
4366
  if (this.#config.context.tenantId === void 0) {
3983
4367
  this.#config.context.tenantId = getTenantId({
@@ -3989,33 +4373,33 @@ var Server = class _Server {
3989
4373
  this.users = new Users(this.#config);
3990
4374
  this.tenants = new Tenants(this.#config);
3991
4375
  this.auth = new Auth(this.#config);
3992
- if (config?.extensions) {
3993
- for (const create2 of config.extensions) {
3994
- if (typeof create2 !== "function") {
3995
- continue;
3996
- }
3997
- const ext = create2();
3998
- if (typeof ext.onConfigure === "function") {
3999
- this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4000
- ext.onConfigure(this);
4001
- }
4002
- if (ext?.replace?.handlers) {
4003
- this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4004
- this.#handlers = ext.replace.handlers({
4005
- ...this.#config.handlers,
4006
- withContext: handlersWithContext(this.#config)
4007
- });
4008
- }
4376
+ if (this.#config.extensions) {
4377
+ for (const create2 of this.#config.extensions) {
4378
+ this.#applyExtension(create2);
4009
4379
  }
4010
4380
  }
4011
4381
  }
4382
+ #applyExtension(create2) {
4383
+ if (typeof create2 !== "function") {
4384
+ return;
4385
+ }
4386
+ const ext = resolveExtension(create2, this);
4387
+ if (typeof ext.onConfigure === "function") {
4388
+ this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4389
+ ext.onConfigure(this);
4390
+ }
4391
+ if (ext?.replace?.handlers) {
4392
+ this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4393
+ this.#handlers = ext.replace.handlers(this.#handlers);
4394
+ }
4395
+ }
4012
4396
  /**
4013
4397
  * Query the database with the current context
4014
4398
  */
4015
4399
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4016
- query = (queryStream, values) => {
4400
+ query = (...args) => {
4017
4401
  const pool = this.#manager.getConnection(this.#config);
4018
- return pool.query(queryStream, values);
4402
+ return pool.query(...args);
4019
4403
  };
4020
4404
  /**
4021
4405
  * Return a db object that can be used to talk to the database
@@ -4024,9 +4408,7 @@ var Server = class _Server {
4024
4408
  get db() {
4025
4409
  const pool = this.#manager.getConnection(this.#config, true);
4026
4410
  return Object.assign(pool, {
4027
- clearConnections: () => {
4028
- this.#manager.clear(this.#config);
4029
- }
4411
+ clearConnections: () => this.#manager.clear(this.#config)
4030
4412
  });
4031
4413
  }
4032
4414
  get logger() {
@@ -4036,7 +4418,9 @@ var Server = class _Server {
4036
4418
  return {
4037
4419
  remove: async (id) => {
4038
4420
  if (!this.#config.extensions) return;
4039
- const resolved = this.#config.extensions.map((ext) => ext());
4421
+ const resolved = this.#config.extensions.map(
4422
+ (ext) => resolveExtension(ext, this)
4423
+ );
4040
4424
  const index = resolved.findIndex((ext) => ext.id === id);
4041
4425
  if (index !== -1) {
4042
4426
  this.#config.extensions.splice(index, 1);
@@ -4048,6 +4432,7 @@ var Server = class _Server {
4048
4432
  this.#config.extensions = [];
4049
4433
  }
4050
4434
  this.#config.extensions.push(extension);
4435
+ this.#applyExtension(extension);
4051
4436
  }
4052
4437
  };
4053
4438
  }
@@ -4128,10 +4513,12 @@ var Server = class _Server {
4128
4513
  }
4129
4514
  return cloneContext(this.#config.context);
4130
4515
  }
4131
- #spawnScoped(scopedContext, boundStore) {
4516
+ #spawnScoped(scopedContext, boundStore, options) {
4517
+ const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
4132
4518
  const clonedConfig = Object.assign(
4133
4519
  Object.create(Config.prototype),
4134
4520
  this.#config,
4521
+ originPatch,
4135
4522
  {
4136
4523
  context: cloneContext(scopedContext),
4137
4524
  isScoped: true,
@@ -4155,12 +4542,12 @@ var Server = class _Server {
4155
4542
  this.#config.context.headers = new Headers();
4156
4543
  if (config instanceof Headers) {
4157
4544
  headers = config;
4158
- } else if (config?.headers) {
4159
- headers = config?.headers;
4160
- if (config && config.origin) {
4545
+ } else if (config) {
4546
+ headers = config.headers;
4547
+ if (config.origin) {
4161
4548
  this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
4162
4549
  }
4163
- if (config && config.secureCookies != null) {
4550
+ if (config.secureCookies != null) {
4164
4551
  this.#config.context.headers.set(
4165
4552
  HEADER_SECURE_COOKIES,
4166
4553
  String(config.secureCookies)