@geekmidas/testkit 10.0.0-alpha.132 → 10.0.0-alpha.134

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/README.md CHANGED
@@ -359,6 +359,17 @@ On the server side of a test — a handler serving a request — `browser.fetch`
359
359
  the plain `fetch`: a server forwards what it was handed and never reaches into a
360
360
  browser's jar.
361
361
 
362
+ Given the address of a site on every subdomain, `on(slug)` is the same browser
363
+ (the same jar, address and clients) on that tenant's host. It sends `Origin` on
364
+ every request and opens a relative `visit` there:
365
+
366
+ ```typescript
367
+ const browser = new Browser({ site: 'https://*.test.shop.localhost:8443' });
368
+ await browser.on('acme').api.get('/orders'); // Origin: https://acme.test.shop.localhost:8443
369
+ ```
370
+
371
+ A feature test passes `site` itself when the app declares one.
372
+
362
373
  ### `createMailbox`
363
374
 
364
375
  Reads the mail an app actually sent, from Mailpit's HTTP API. One address per
package/dist/browser.cjs CHANGED
@@ -25,7 +25,13 @@ let tough_cookie = require("tough-cookie");
25
25
  const MAX_REDIRECTS = 20;
26
26
  var Browser = class {
27
27
  /** The cookies this browser holds. */
28
- jar = new tough_cookie.CookieJar();
28
+ jar;
29
+ /**
30
+ * The page this browser is on, sent as `Origin` — what a surface's CORS
31
+ * and an auth server's trusted origins check, and what a multi-tenant app
32
+ * reads its tenant from. None until {@link Browser.on} gives it one.
33
+ */
34
+ origin;
29
35
  /**
30
36
  * The address this browser connects from, sent as `x-forwarded-for` the way
31
37
  * a proxy in front of the app adds it. Each browser is a different person on
@@ -47,17 +53,50 @@ var Browser = class {
47
53
  */
48
54
  fetch;
49
55
  send;
56
+ site;
50
57
  constructor(options = {}) {
51
58
  this.send = options.fetch ?? globalThis.fetch;
52
59
  this.address = options.address ?? privateAddress();
60
+ this.jar = options.jar ?? new tough_cookie.CookieJar();
61
+ if (options.site) this.site = options.site;
62
+ if (options.origin) this.origin = options.origin;
53
63
  this.fetch = (input, init) => {
54
64
  if (require_context.currentTestContext()?.side === "server") return this.send(input, init);
55
65
  return this.start(new Request(input, init), init?.redirect);
56
66
  };
57
67
  }
58
- /** Open a URL the way clicking a link does: a GET, redirects followed. */
68
+ /**
69
+ * Open a URL the way clicking a link does: a GET, redirects followed. A
70
+ * path is opened on the page this browser is on.
71
+ */
59
72
  visit(url) {
60
- return this.fetch(String(url));
73
+ return this.fetch(this.origin ? new URL(url, this.origin).toString() : String(url));
74
+ }
75
+ /**
76
+ * The same person on a tenant's host: this browser — its cookies, its
77
+ * address, its clients — on `https://<slug>.<domain>`, the app's site on
78
+ * every subdomain. Each request it makes says so in `Origin`, as a page on
79
+ * that host would, so a test signs in once and calls the app as two
80
+ * tenants:
81
+ *
82
+ * ```ts
83
+ * await browser.signIn();
84
+ * await browser.on('acme').api.post('/orders', { body });
85
+ * expect(await browser.on('globex').api.get('/orders')).toEqual([]);
86
+ * ```
87
+ */
88
+ on(slug) {
89
+ if (!this.site) throw new NoWildcardSite(slug);
90
+ if (!SLUG.test(slug)) throw new NotATenantSlug(slug);
91
+ const origin = new URL(this.site.replace("*", slug)).origin;
92
+ const Same = this.constructor;
93
+ return new Same({
94
+ fetch: this.send,
95
+ address: this.address,
96
+ jar: this.jar,
97
+ site: this.site,
98
+ origin
99
+ });
61
100
  }
62
101
  /** The cookies this browser would send to `url`, as a header value. */
63
102
  cookieHeader(url) {
@@ -79,6 +118,7 @@ var Browser = class {
79
118
  const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
80
119
  const headers = new Headers(request.headers);
81
120
  if (!headers.has("x-forwarded-for")) headers.set("x-forwarded-for", this.address);
121
+ if (this.origin && !headers.has("origin")) headers.set("origin", this.origin);
82
122
  return this.request({
83
123
  url: request.url,
84
124
  method: request.method,
@@ -134,6 +174,26 @@ var TooManyRedirects = class extends Error {
134
174
  this.name = "TooManyRedirects";
135
175
  }
136
176
  };
177
+ /** One DNS label, as a tenant's slug is. */
178
+ const SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
179
+ /** `browser.on(slug)` in an app with no site on every subdomain. */
180
+ var NoWildcardSite = class extends Error {
181
+ slug;
182
+ constructor(slug) {
183
+ super(`browser.on('${slug}') puts a tenant's slug into the app's site on every subdomain, and this browser knows of none. Declare a StaticSite with subdomain: '*', or pass its address as \`site\`.`);
184
+ this.slug = slug;
185
+ this.name = "NoWildcardSite";
186
+ }
187
+ };
188
+ /** `browser.on(slug)` with something no host can start with. */
189
+ var NotATenantSlug = class extends Error {
190
+ slug;
191
+ constructor(slug) {
192
+ super(`'${slug}' is not a tenant's slug: one DNS label of lowercase letters, digits and inner hyphens, such as 'acme'.`);
193
+ this.slug = slug;
194
+ this.name = "NotATenantSlug";
195
+ }
196
+ };
137
197
  /**
138
198
  * An address from 10.0.0.0/8, which nothing routes to. Random rather than
139
199
  * counted: test files run in separate workers that share no counter.
@@ -144,6 +204,8 @@ function privateAddress() {
144
204
  }
145
205
  //#endregion
146
206
  exports.Browser = Browser;
207
+ exports.NoWildcardSite = NoWildcardSite;
208
+ exports.NotATenantSlug = NotATenantSlug;
147
209
  exports.TooManyRedirects = TooManyRedirects;
148
210
 
149
211
  //# sourceMappingURL=browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.cjs","names":["CookieJar","currentTestContext","randomInt"],"sources":["../src/browser.ts"],"sourcesContent":["/**\n * A browser, for tests: a `fetch` that keeps cookies the way a browser does.\n *\n * An app's real clients — its typed API client, better-auth's client — run on\n * whatever `fetch` they are given. Give them this one and a test signs in the\n * way a person does: the auth server's `Set-Cookie` lands in the jar, and every\n * later request to a URL the cookie belongs to carries it. The jar follows the\n * browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set\n * for the wrong domain is not sent, exactly as a browser would not send it.\n *\n * Extend it once per app with that app's clients:\n *\n * ```ts\n * export class Browser extends TestBrowser {\n * readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });\n * }\n * ```\n */\n\nimport { randomInt } from 'node:crypto';\nimport { CookieJar } from 'tough-cookie';\nimport { currentTestContext } from './context';\n\n/** How many redirects `fetch` follows before giving up, as browsers do. */\nconst MAX_REDIRECTS = 20;\n\nexport interface BrowserOptions {\n\t/**\n\t * The `fetch` requests go out on. Defaults to the global one at the time\n\t * the browser is created — so a browser made inside a test goes through\n\t * whatever the test installed (MSW, the context stamp) and never through\n\t * itself once installed.\n\t */\n\tfetch?: typeof fetch;\n\t/**\n\t * The address this browser connects from. A fresh one by default, from a\n\t * private range nothing routes to — see {@link Browser.address}.\n\t */\n\taddress?: string;\n}\n\nexport class Browser {\n\t/** The cookies this browser holds. */\n\treadonly jar = new CookieJar();\n\n\t/**\n\t * The address this browser connects from, sent as `x-forwarded-for` the way\n\t * a proxy in front of the app adds it. Each browser is a different person on\n\t * a different connection, so what an app keys by client — an auth server's\n\t * rate limit — counts each on its own. Without it every browser was the same\n\t * client, and concurrent tests queued on the same rate-limit row of each\n\t * other's open transactions. A request that sets the header itself — a test\n\t * that is several machines — keeps its own.\n\t */\n\treadonly address: string;\n\n\t/**\n\t * This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`\n\t * into the jar on the way back, redirects followed hop by hop so each hop's\n\t * cookies are kept.\n\t *\n\t * On the server side of a test — a handler serving a request — it is the\n\t * plain `fetch`: a server forwards what it was handed and never reaches into\n\t * a browser's jar.\n\t */\n\treadonly fetch: typeof fetch;\n\n\tprivate readonly send: typeof fetch;\n\n\tconstructor(options: BrowserOptions = {}) {\n\t\tthis.send = options.fetch ?? globalThis.fetch;\n\t\tthis.address = options.address ?? privateAddress();\n\t\tthis.fetch = (input, init) => {\n\t\t\tif (currentTestContext()?.side === 'server') {\n\t\t\t\treturn this.send(input, init);\n\t\t\t}\n\t\t\treturn this.start(new Request(input, init), init?.redirect);\n\t\t};\n\t}\n\n\t/** Open a URL the way clicking a link does: a GET, redirects followed. */\n\tvisit(url: string | URL): Promise<Response> {\n\t\treturn this.fetch(String(url));\n\t}\n\n\t/** The cookies this browser would send to `url`, as a header value. */\n\tcookieHeader(url: string | URL): Promise<string> {\n\t\treturn this.jar.getCookieString(String(url));\n\t}\n\n\t/**\n\t * Make this browser the global `fetch`, for code that uses the global one —\n\t * an app's module-level clients. Returns what puts the previous one back.\n\t */\n\tinstall(): () => void {\n\t\tconst previous = globalThis.fetch;\n\t\tglobalThis.fetch = this.fetch;\n\t\treturn () => {\n\t\t\tglobalThis.fetch = previous;\n\t\t};\n\t}\n\n\t/** Read the body once, so a redirect that keeps the method can send it again. */\n\tprivate async start(\n\t\trequest: Request,\n\t\tredirect: RequestInit['redirect'],\n\t): Promise<Response> {\n\t\tconst body =\n\t\t\trequest.method === 'GET' || request.method === 'HEAD'\n\t\t\t\t? undefined\n\t\t\t\t: await request.arrayBuffer();\n\t\tconst headers = new Headers(request.headers);\n\t\tif (!headers.has('x-forwarded-for')) {\n\t\t\theaders.set('x-forwarded-for', this.address);\n\t\t}\n\t\treturn this.request(\n\t\t\t{ url: request.url, method: request.method, headers, body },\n\t\t\tredirect,\n\t\t);\n\t}\n\n\tprivate async request(\n\t\trequest: Hop,\n\t\tredirect: RequestInit['redirect'],\n\t\thops = 0,\n\t): Promise<Response> {\n\t\tconst headers = new Headers(request.headers);\n\t\tconst cookie = await this.jar.getCookieString(request.url);\n\t\tif (cookie) {\n\t\t\tconst existing = headers.get('cookie');\n\t\t\theaders.set('cookie', existing ? `${existing}; ${cookie}` : cookie);\n\t\t}\n\n\t\tconst response = await this.send(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders,\n\t\t\tbody: request.body,\n\t\t\tredirect: 'manual',\n\t\t});\n\n\t\tfor (const set of response.headers.getSetCookie()) {\n\t\t\t// A cookie a browser would refuse — the wrong domain, Secure over\n\t\t\t// plain HTTP — is dropped silently, as a browser drops it.\n\t\t\tawait this.jar.setCookie(set, request.url, { ignoreError: true });\n\t\t}\n\n\t\tconst location = response.headers.get('location');\n\t\tif (\n\t\t\tredirect === 'manual' ||\n\t\t\t!location ||\n\t\t\tresponse.status < 300 ||\n\t\t\tresponse.status >= 400\n\t\t) {\n\t\t\treturn response;\n\t\t}\n\n\t\tif (hops >= MAX_REDIRECTS) {\n\t\t\tthrow new TooManyRedirects(request.url, MAX_REDIRECTS);\n\t\t}\n\n\t\t// 303, and 301/302 after a POST, continue as a GET without a body — what\n\t\t// every browser does, whatever the spec once said about 302.\n\t\tconst keepsMethod =\n\t\t\tresponse.status === 307 ||\n\t\t\tresponse.status === 308 ||\n\t\t\trequest.method === 'GET' ||\n\t\t\trequest.method === 'HEAD';\n\n\t\tconst url = new URL(location, request.url).toString();\n\t\tconst next: Hop = keepsMethod\n\t\t\t? { ...request, url }\n\t\t\t: { url, method: 'GET', headers: withoutBody(request.headers) };\n\n\t\treturn this.request(next, redirect, hops + 1);\n\t}\n}\n\n/** One request in a redirect chain, with its body already read. */\ninterface Hop {\n\turl: string;\n\tmethod: string;\n\theaders: Headers;\n\tbody?: ArrayBuffer;\n}\n\n/** Headers for a request that no longer carries the body they described. */\nfunction withoutBody(headers: Headers): Headers {\n\tconst next = new Headers(headers);\n\tnext.delete('content-type');\n\tnext.delete('content-length');\n\treturn next;\n}\n\n/** A redirect chain longer than any browser follows. */\nexport class TooManyRedirects extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly limit: number,\n\t) {\n\t\tsuper(\n\t\t\t`${url} redirected more than ${limit} times. A browser gives up here ` +\n\t\t\t\t`too — look for a redirect loop.`,\n\t\t);\n\t\tthis.name = 'TooManyRedirects';\n\t}\n}\n\n/**\n * An address from 10.0.0.0/8, which nothing routes to. Random rather than\n * counted: test files run in separate workers that share no counter.\n */\nfunction privateAddress(): string {\n\tconst n = randomInt(1, 2 ** 24 - 1);\n\treturn `10.${(n >> 16) & 255}.${(n >> 8) & 255}.${n & 255}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB;AAiBtB,IAAa,UAAb,MAAqB;;CAEpB,MAAe,IAAIA,aAAAA,UAAU;;;;;;;;;;CAW7B;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randomInt"],"sources":["../src/browser.ts"],"sourcesContent":["/**\n * A browser, for tests: a `fetch` that keeps cookies the way a browser does.\n *\n * An app's real clients — its typed API client, better-auth's client — run on\n * whatever `fetch` they are given. Give them this one and a test signs in the\n * way a person does: the auth server's `Set-Cookie` lands in the jar, and every\n * later request to a URL the cookie belongs to carries it. The jar follows the\n * browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set\n * for the wrong domain is not sent, exactly as a browser would not send it.\n *\n * Extend it once per app with that app's clients:\n *\n * ```ts\n * export class Browser extends TestBrowser {\n * readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });\n * }\n * ```\n */\n\nimport { randomInt } from 'node:crypto';\nimport { CookieJar } from 'tough-cookie';\nimport { currentTestContext } from './context';\n\n/** How many redirects `fetch` follows before giving up, as browsers do. */\nconst MAX_REDIRECTS = 20;\n\nexport interface BrowserOptions {\n\t/**\n\t * The `fetch` requests go out on. Defaults to the global one at the time\n\t * the browser is created — so a browser made inside a test goes through\n\t * whatever the test installed (MSW, the context stamp) and never through\n\t * itself once installed.\n\t */\n\tfetch?: typeof fetch;\n\t/**\n\t * The address this browser connects from. A fresh one by default, from a\n\t * private range nothing routes to — see {@link Browser.address}.\n\t */\n\taddress?: string;\n\t/**\n\t * The cookies it starts with — another browser's jar, to be the same\n\t * person on another tab. A fresh jar by default.\n\t */\n\tjar?: CookieJar;\n\t/**\n\t * The address of the app's site on every subdomain,\n\t * `https://*.test.shop.localhost:8443`, which {@link Browser.on} puts a\n\t * tenant's slug into. A feature test passes it when the app declares one.\n\t */\n\tsite?: string;\n\t/**\n\t * The page this browser is on: sent as `Origin` on every request that does\n\t * not set its own, and what a relative {@link Browser.visit} resolves\n\t * against. See {@link Browser.on}.\n\t */\n\torigin?: string;\n}\n\nexport class Browser {\n\t/** The cookies this browser holds. */\n\treadonly jar: CookieJar;\n\n\t/**\n\t * The page this browser is on, sent as `Origin` — what a surface's CORS\n\t * and an auth server's trusted origins check, and what a multi-tenant app\n\t * reads its tenant from. None until {@link Browser.on} gives it one.\n\t */\n\treadonly origin?: string;\n\n\t/**\n\t * The address this browser connects from, sent as `x-forwarded-for` the way\n\t * a proxy in front of the app adds it. Each browser is a different person on\n\t * a different connection, so what an app keys by client — an auth server's\n\t * rate limit — counts each on its own. Without it every browser was the same\n\t * client, and concurrent tests queued on the same rate-limit row of each\n\t * other's open transactions. A request that sets the header itself — a test\n\t * that is several machines — keeps its own.\n\t */\n\treadonly address: string;\n\n\t/**\n\t * This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`\n\t * into the jar on the way back, redirects followed hop by hop so each hop's\n\t * cookies are kept.\n\t *\n\t * On the server side of a test — a handler serving a request — it is the\n\t * plain `fetch`: a server forwards what it was handed and never reaches into\n\t * a browser's jar.\n\t */\n\treadonly fetch: typeof fetch;\n\n\tprivate readonly send: typeof fetch;\n\tprivate readonly site?: string;\n\n\tconstructor(options: BrowserOptions = {}) {\n\t\tthis.send = options.fetch ?? globalThis.fetch;\n\t\tthis.address = options.address ?? privateAddress();\n\t\tthis.jar = options.jar ?? new CookieJar();\n\t\tif (options.site) this.site = options.site;\n\t\tif (options.origin) this.origin = options.origin;\n\t\tthis.fetch = (input, init) => {\n\t\t\tif (currentTestContext()?.side === 'server') {\n\t\t\t\treturn this.send(input, init);\n\t\t\t}\n\t\t\treturn this.start(new Request(input, init), init?.redirect);\n\t\t};\n\t}\n\n\t/**\n\t * Open a URL the way clicking a link does: a GET, redirects followed. A\n\t * path is opened on the page this browser is on.\n\t */\n\tvisit(url: string | URL): Promise<Response> {\n\t\treturn this.fetch(\n\t\t\tthis.origin ? new URL(url, this.origin).toString() : String(url),\n\t\t);\n\t}\n\n\t/**\n\t * The same person on a tenant's host: this browser — its cookies, its\n\t * address, its clients — on `https://<slug>.<domain>`, the app's site on\n\t * every subdomain. Each request it makes says so in `Origin`, as a page on\n\t * that host would, so a test signs in once and calls the app as two\n\t * tenants:\n\t *\n\t * ```ts\n\t * await browser.signIn();\n\t * await browser.on('acme').api.post('/orders', { body });\n\t * expect(await browser.on('globex').api.get('/orders')).toEqual([]);\n\t * ```\n\t */\n\ton(slug: string): this {\n\t\tif (!this.site) throw new NoWildcardSite(slug);\n\t\tif (!SLUG.test(slug)) throw new NotATenantSlug(slug);\n\n\t\tconst origin = new URL(this.site.replace('*', slug)).origin;\n\t\tconst Same = this.constructor as new (options: BrowserOptions) => this;\n\t\treturn new Same({\n\t\t\tfetch: this.send,\n\t\t\taddress: this.address,\n\t\t\tjar: this.jar,\n\t\t\tsite: this.site,\n\t\t\torigin,\n\t\t});\n\t}\n\n\t/** The cookies this browser would send to `url`, as a header value. */\n\tcookieHeader(url: string | URL): Promise<string> {\n\t\treturn this.jar.getCookieString(String(url));\n\t}\n\n\t/**\n\t * Make this browser the global `fetch`, for code that uses the global one —\n\t * an app's module-level clients. Returns what puts the previous one back.\n\t */\n\tinstall(): () => void {\n\t\tconst previous = globalThis.fetch;\n\t\tglobalThis.fetch = this.fetch;\n\t\treturn () => {\n\t\t\tglobalThis.fetch = previous;\n\t\t};\n\t}\n\n\t/** Read the body once, so a redirect that keeps the method can send it again. */\n\tprivate async start(\n\t\trequest: Request,\n\t\tredirect: RequestInit['redirect'],\n\t): Promise<Response> {\n\t\tconst body =\n\t\t\trequest.method === 'GET' || request.method === 'HEAD'\n\t\t\t\t? undefined\n\t\t\t\t: await request.arrayBuffer();\n\t\tconst headers = new Headers(request.headers);\n\t\tif (!headers.has('x-forwarded-for')) {\n\t\t\theaders.set('x-forwarded-for', this.address);\n\t\t}\n\t\tif (this.origin && !headers.has('origin')) {\n\t\t\theaders.set('origin', this.origin);\n\t\t}\n\t\treturn this.request(\n\t\t\t{ url: request.url, method: request.method, headers, body },\n\t\t\tredirect,\n\t\t);\n\t}\n\n\tprivate async request(\n\t\trequest: Hop,\n\t\tredirect: RequestInit['redirect'],\n\t\thops = 0,\n\t): Promise<Response> {\n\t\tconst headers = new Headers(request.headers);\n\t\tconst cookie = await this.jar.getCookieString(request.url);\n\t\tif (cookie) {\n\t\t\tconst existing = headers.get('cookie');\n\t\t\theaders.set('cookie', existing ? `${existing}; ${cookie}` : cookie);\n\t\t}\n\n\t\tconst response = await this.send(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders,\n\t\t\tbody: request.body,\n\t\t\tredirect: 'manual',\n\t\t});\n\n\t\tfor (const set of response.headers.getSetCookie()) {\n\t\t\t// A cookie a browser would refuse — the wrong domain, Secure over\n\t\t\t// plain HTTP — is dropped silently, as a browser drops it.\n\t\t\tawait this.jar.setCookie(set, request.url, { ignoreError: true });\n\t\t}\n\n\t\tconst location = response.headers.get('location');\n\t\tif (\n\t\t\tredirect === 'manual' ||\n\t\t\t!location ||\n\t\t\tresponse.status < 300 ||\n\t\t\tresponse.status >= 400\n\t\t) {\n\t\t\treturn response;\n\t\t}\n\n\t\tif (hops >= MAX_REDIRECTS) {\n\t\t\tthrow new TooManyRedirects(request.url, MAX_REDIRECTS);\n\t\t}\n\n\t\t// 303, and 301/302 after a POST, continue as a GET without a body — what\n\t\t// every browser does, whatever the spec once said about 302.\n\t\tconst keepsMethod =\n\t\t\tresponse.status === 307 ||\n\t\t\tresponse.status === 308 ||\n\t\t\trequest.method === 'GET' ||\n\t\t\trequest.method === 'HEAD';\n\n\t\tconst url = new URL(location, request.url).toString();\n\t\tconst next: Hop = keepsMethod\n\t\t\t? { ...request, url }\n\t\t\t: { url, method: 'GET', headers: withoutBody(request.headers) };\n\n\t\treturn this.request(next, redirect, hops + 1);\n\t}\n}\n\n/** One request in a redirect chain, with its body already read. */\ninterface Hop {\n\turl: string;\n\tmethod: string;\n\theaders: Headers;\n\tbody?: ArrayBuffer;\n}\n\n/** Headers for a request that no longer carries the body they described. */\nfunction withoutBody(headers: Headers): Headers {\n\tconst next = new Headers(headers);\n\tnext.delete('content-type');\n\tnext.delete('content-length');\n\treturn next;\n}\n\n/** A redirect chain longer than any browser follows. */\nexport class TooManyRedirects extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly limit: number,\n\t) {\n\t\tsuper(\n\t\t\t`${url} redirected more than ${limit} times. A browser gives up here ` +\n\t\t\t\t`too — look for a redirect loop.`,\n\t\t);\n\t\tthis.name = 'TooManyRedirects';\n\t}\n}\n\n/** One DNS label, as a tenant's slug is. */\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** `browser.on(slug)` in an app with no site on every subdomain. */\nexport class NoWildcardSite extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`browser.on('${slug}') puts a tenant's slug into the app's site on ` +\n\t\t\t\t`every subdomain, and this browser knows of none. Declare a ` +\n\t\t\t\t`StaticSite with subdomain: '*', or pass its address as \\`site\\`.`,\n\t\t);\n\t\tthis.name = 'NoWildcardSite';\n\t}\n}\n\n/** `browser.on(slug)` with something no host can start with. */\nexport class NotATenantSlug extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`'${slug}' is not a tenant's slug: one DNS label of lowercase ` +\n\t\t\t\t`letters, digits and inner hyphens, such as 'acme'.`,\n\t\t);\n\t\tthis.name = 'NotATenantSlug';\n\t}\n}\n\n/**\n * An address from 10.0.0.0/8, which nothing routes to. Random rather than\n * counted: test files run in separate workers that share no counter.\n */\nfunction privateAddress(): string {\n\tconst n = randomInt(1, 2 ** 24 - 1);\n\treturn `10.${(n >> 16) & 255}.${(n >> 8) & 255}.${n & 255}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB;AAkCtB,IAAa,UAAb,MAAqB;;CAEpB;;;;;;CAOA;;;;;;;;;;CAWA;;;;;;;;;;CAWA;CAEA;CACA;CAEA,YAAY,UAA0B,CAAC,GAAG;EACzC,KAAK,OAAO,QAAQ,SAAS,WAAW;EACxC,KAAK,UAAU,QAAQ,WAAW,eAAe;EACjD,KAAK,MAAM,QAAQ,OAAO,IAAIA,aAAAA,UAAU;EACxC,IAAI,QAAQ,MAAM,KAAK,OA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,KAAK,OAAO,cAAc;CAC1B,KAAK,OAAO,gBAAgB;CAC5B,OAAO;AACR;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CAFV,YACC,KACA,OACC;EACD,MACC,GAAG,IAAI,wBAAwB,MAAM,gEAEtC;EANS,KAAA,MAAA;EACA,KAAA,QAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,MAAM,OAAO;;AAGb,IAAa,iBAAb,cAAoC,MAAM;CACpB;CAArB,YAAY,MAAuB;EAClC,MACC,eAAe,KAAK,2KAGrB;EALoB,KAAA,OAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,iBAAb,cAAoC,MAAM;CACpB;CAArB,YAAY,MAAuB;EAClC,MACC,IAAI,KAAK,wGAEV;EAJoB,KAAA,OAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;AAMA,SAAS,iBAAyB;CACjC,MAAM,KAAA,GAAIC,YAAAA,UAAAA,CAAU,GAAG,KAAK,KAAK,CAAC;CAClC,OAAO,MAAO,KAAK,KAAM,IAAI,GAAI,KAAK,IAAK,IAAI,GAAG,IAAI;AACvD"}
@@ -13,10 +13,33 @@ export interface BrowserOptions {
13
13
  * private range nothing routes to — see {@link Browser.address}.
14
14
  */
15
15
  address?: string;
16
+ /**
17
+ * The cookies it starts with — another browser's jar, to be the same
18
+ * person on another tab. A fresh jar by default.
19
+ */
20
+ jar?: CookieJar;
21
+ /**
22
+ * The address of the app's site on every subdomain,
23
+ * `https://*.test.shop.localhost:8443`, which {@link Browser.on} puts a
24
+ * tenant's slug into. A feature test passes it when the app declares one.
25
+ */
26
+ site?: string;
27
+ /**
28
+ * The page this browser is on: sent as `Origin` on every request that does
29
+ * not set its own, and what a relative {@link Browser.visit} resolves
30
+ * against. See {@link Browser.on}.
31
+ */
32
+ origin?: string;
16
33
  }
17
34
  export declare class Browser {
18
35
  /** The cookies this browser holds. */
19
36
  readonly jar: CookieJar;
37
+ /**
38
+ * The page this browser is on, sent as `Origin` — what a surface's CORS
39
+ * and an auth server's trusted origins check, and what a multi-tenant app
40
+ * reads its tenant from. None until {@link Browser.on} gives it one.
41
+ */
42
+ readonly origin?: string;
20
43
  /**
21
44
  * The address this browser connects from, sent as `x-forwarded-for` the way
22
45
  * a proxy in front of the app adds it. Each browser is a different person on
@@ -38,9 +61,27 @@ export declare class Browser {
38
61
  */
39
62
  readonly fetch: typeof fetch;
40
63
  private readonly send;
64
+ private readonly site?;
41
65
  constructor(options?: BrowserOptions);
42
- /** Open a URL the way clicking a link does: a GET, redirects followed. */
66
+ /**
67
+ * Open a URL the way clicking a link does: a GET, redirects followed. A
68
+ * path is opened on the page this browser is on.
69
+ */
43
70
  visit(url: string | URL): Promise<Response>;
71
+ /**
72
+ * The same person on a tenant's host: this browser — its cookies, its
73
+ * address, its clients — on `https://<slug>.<domain>`, the app's site on
74
+ * every subdomain. Each request it makes says so in `Origin`, as a page on
75
+ * that host would, so a test signs in once and calls the app as two
76
+ * tenants:
77
+ *
78
+ * ```ts
79
+ * await browser.signIn();
80
+ * await browser.on('acme').api.post('/orders', { body });
81
+ * expect(await browser.on('globex').api.get('/orders')).toEqual([]);
82
+ * ```
83
+ */
84
+ on(slug: string): this;
44
85
  /** The cookies this browser would send to `url`, as a header value. */
45
86
  cookieHeader(url: string | URL): Promise<string>;
46
87
  /**
@@ -58,5 +99,15 @@ export declare class TooManyRedirects extends Error {
58
99
  readonly limit: number;
59
100
  constructor(url: string, limit: number);
60
101
  }
102
+ /** `browser.on(slug)` in an app with no site on every subdomain. */
103
+ export declare class NoWildcardSite extends Error {
104
+ readonly slug: string;
105
+ constructor(slug: string);
106
+ }
107
+ /** `browser.on(slug)` with something no host can start with. */
108
+ export declare class NotATenantSlug extends Error {
109
+ readonly slug: string;
110
+ constructor(slug: string);
111
+ }
61
112
  //#endregion
62
113
  //# sourceMappingURL=browser.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.d.cts","names":[],"sources":["../src/browser.ts"],"mappings":";;iBA0BiB;;;;;;;EAOhB,eAAe;;;;;EAKf;;qBAGY;;WAEH,KAAG;;;;;;;;;;WAWH;;;;;;;;;;WAWA,cAAc;mBAEN;EAEjB,YAAY,UAAS;;EAYrB,MAAM,cAAc,MAAM,QAAQ;;EAKlC,aAAa,cAAc,MAAM;;;;;EAQjC;;UASc;UAkBA;;;qBAyEF,yBAAyB;WAE3B;WACA;EAFV,YACU,aACA"}
1
+ {"version":3,"file":"browser.d.cts","names":[],"sources":["../src/browser.ts"],"mappings":";;iBA0BiB;;;;;;;EAOhB,eAAe;;;;;EAKf;;;;;EAKA,MAAM;;;;;;EAMN;;;;;;EAMA;;qBAGY;;WAEH,KAAK;;;;;;WAOL;;;;;;;;;;WAWA;;;;;;;;;;WAWA,cAAc;mBAEN;mBACA;EAEjB,YAAY,UAAS;;;;;EAkBrB,MAAM,cAAc,MAAM,QAAQ;;;;;;;;;;;;;;EAmBlC,GAAG;;EAgBH,aAAa,cAAc,MAAM;;;;;EAQjC;;UASc;UAqBA;;;qBAyEF,yBAAyB;WAE3B;WACA;EAFV,YACU,aACA;;;qBAcE,uBAAuB;WACd;EAArB,YAAqB;;;qBAWT,uBAAuB;WACd;EAArB,YAAqB"}
@@ -13,10 +13,33 @@ export interface BrowserOptions {
13
13
  * private range nothing routes to — see {@link Browser.address}.
14
14
  */
15
15
  address?: string;
16
+ /**
17
+ * The cookies it starts with — another browser's jar, to be the same
18
+ * person on another tab. A fresh jar by default.
19
+ */
20
+ jar?: CookieJar;
21
+ /**
22
+ * The address of the app's site on every subdomain,
23
+ * `https://*.test.shop.localhost:8443`, which {@link Browser.on} puts a
24
+ * tenant's slug into. A feature test passes it when the app declares one.
25
+ */
26
+ site?: string;
27
+ /**
28
+ * The page this browser is on: sent as `Origin` on every request that does
29
+ * not set its own, and what a relative {@link Browser.visit} resolves
30
+ * against. See {@link Browser.on}.
31
+ */
32
+ origin?: string;
16
33
  }
17
34
  export declare class Browser {
18
35
  /** The cookies this browser holds. */
19
36
  readonly jar: CookieJar;
37
+ /**
38
+ * The page this browser is on, sent as `Origin` — what a surface's CORS
39
+ * and an auth server's trusted origins check, and what a multi-tenant app
40
+ * reads its tenant from. None until {@link Browser.on} gives it one.
41
+ */
42
+ readonly origin?: string;
20
43
  /**
21
44
  * The address this browser connects from, sent as `x-forwarded-for` the way
22
45
  * a proxy in front of the app adds it. Each browser is a different person on
@@ -38,9 +61,27 @@ export declare class Browser {
38
61
  */
39
62
  readonly fetch: typeof fetch;
40
63
  private readonly send;
64
+ private readonly site?;
41
65
  constructor(options?: BrowserOptions);
42
- /** Open a URL the way clicking a link does: a GET, redirects followed. */
66
+ /**
67
+ * Open a URL the way clicking a link does: a GET, redirects followed. A
68
+ * path is opened on the page this browser is on.
69
+ */
43
70
  visit(url: string | URL): Promise<Response>;
71
+ /**
72
+ * The same person on a tenant's host: this browser — its cookies, its
73
+ * address, its clients — on `https://<slug>.<domain>`, the app's site on
74
+ * every subdomain. Each request it makes says so in `Origin`, as a page on
75
+ * that host would, so a test signs in once and calls the app as two
76
+ * tenants:
77
+ *
78
+ * ```ts
79
+ * await browser.signIn();
80
+ * await browser.on('acme').api.post('/orders', { body });
81
+ * expect(await browser.on('globex').api.get('/orders')).toEqual([]);
82
+ * ```
83
+ */
84
+ on(slug: string): this;
44
85
  /** The cookies this browser would send to `url`, as a header value. */
45
86
  cookieHeader(url: string | URL): Promise<string>;
46
87
  /**
@@ -58,5 +99,15 @@ export declare class TooManyRedirects extends Error {
58
99
  readonly limit: number;
59
100
  constructor(url: string, limit: number);
60
101
  }
102
+ /** `browser.on(slug)` in an app with no site on every subdomain. */
103
+ export declare class NoWildcardSite extends Error {
104
+ readonly slug: string;
105
+ constructor(slug: string);
106
+ }
107
+ /** `browser.on(slug)` with something no host can start with. */
108
+ export declare class NotATenantSlug extends Error {
109
+ readonly slug: string;
110
+ constructor(slug: string);
111
+ }
61
112
  //#endregion
62
113
  //# sourceMappingURL=browser.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.d.mts","names":[],"sources":["../src/browser.ts"],"mappings":";;iBA0BiB;;;;;;;EAOhB,eAAe;;;;;EAKf;;qBAGY;;WAEH,KAAG;;;;;;;;;;WAWH;;;;;;;;;;WAWA,cAAc;mBAEN;EAEjB,YAAY,UAAS;;EAYrB,MAAM,cAAc,MAAM,QAAQ;;EAKlC,aAAa,cAAc,MAAM;;;;;EAQjC;;UASc;UAkBA;;;qBAyEF,yBAAyB;WAE3B;WACA;EAFV,YACU,aACA"}
1
+ {"version":3,"file":"browser.d.mts","names":[],"sources":["../src/browser.ts"],"mappings":";;iBA0BiB;;;;;;;EAOhB,eAAe;;;;;EAKf;;;;;EAKA,MAAM;;;;;;EAMN;;;;;;EAMA;;qBAGY;;WAEH,KAAK;;;;;;WAOL;;;;;;;;;;WAWA;;;;;;;;;;WAWA,cAAc;mBAEN;mBACA;EAEjB,YAAY,UAAS;;;;;EAkBrB,MAAM,cAAc,MAAM,QAAQ;;;;;;;;;;;;;;EAmBlC,GAAG;;EAgBH,aAAa,cAAc,MAAM;;;;;EAQjC;;UASc;UAqBA;;;qBAyEF,yBAAyB;WAE3B;WACA;EAFV,YACU,aACA;;;qBAcE,uBAAuB;WACd;EAArB,YAAqB;;;qBAWT,uBAAuB;WACd;EAArB,YAAqB"}
package/dist/browser.mjs CHANGED
@@ -24,7 +24,13 @@ import { CookieJar } from "tough-cookie";
24
24
  const MAX_REDIRECTS = 20;
25
25
  var Browser = class {
26
26
  /** The cookies this browser holds. */
27
- jar = new CookieJar();
27
+ jar;
28
+ /**
29
+ * The page this browser is on, sent as `Origin` — what a surface's CORS
30
+ * and an auth server's trusted origins check, and what a multi-tenant app
31
+ * reads its tenant from. None until {@link Browser.on} gives it one.
32
+ */
33
+ origin;
28
34
  /**
29
35
  * The address this browser connects from, sent as `x-forwarded-for` the way
30
36
  * a proxy in front of the app adds it. Each browser is a different person on
@@ -46,17 +52,50 @@ var Browser = class {
46
52
  */
47
53
  fetch;
48
54
  send;
55
+ site;
49
56
  constructor(options = {}) {
50
57
  this.send = options.fetch ?? globalThis.fetch;
51
58
  this.address = options.address ?? privateAddress();
59
+ this.jar = options.jar ?? new CookieJar();
60
+ if (options.site) this.site = options.site;
61
+ if (options.origin) this.origin = options.origin;
52
62
  this.fetch = (input, init) => {
53
63
  if (currentTestContext()?.side === "server") return this.send(input, init);
54
64
  return this.start(new Request(input, init), init?.redirect);
55
65
  };
56
66
  }
57
- /** Open a URL the way clicking a link does: a GET, redirects followed. */
67
+ /**
68
+ * Open a URL the way clicking a link does: a GET, redirects followed. A
69
+ * path is opened on the page this browser is on.
70
+ */
58
71
  visit(url) {
59
- return this.fetch(String(url));
72
+ return this.fetch(this.origin ? new URL(url, this.origin).toString() : String(url));
73
+ }
74
+ /**
75
+ * The same person on a tenant's host: this browser — its cookies, its
76
+ * address, its clients — on `https://<slug>.<domain>`, the app's site on
77
+ * every subdomain. Each request it makes says so in `Origin`, as a page on
78
+ * that host would, so a test signs in once and calls the app as two
79
+ * tenants:
80
+ *
81
+ * ```ts
82
+ * await browser.signIn();
83
+ * await browser.on('acme').api.post('/orders', { body });
84
+ * expect(await browser.on('globex').api.get('/orders')).toEqual([]);
85
+ * ```
86
+ */
87
+ on(slug) {
88
+ if (!this.site) throw new NoWildcardSite(slug);
89
+ if (!SLUG.test(slug)) throw new NotATenantSlug(slug);
90
+ const origin = new URL(this.site.replace("*", slug)).origin;
91
+ const Same = this.constructor;
92
+ return new Same({
93
+ fetch: this.send,
94
+ address: this.address,
95
+ jar: this.jar,
96
+ site: this.site,
97
+ origin
98
+ });
60
99
  }
61
100
  /** The cookies this browser would send to `url`, as a header value. */
62
101
  cookieHeader(url) {
@@ -78,6 +117,7 @@ var Browser = class {
78
117
  const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
79
118
  const headers = new Headers(request.headers);
80
119
  if (!headers.has("x-forwarded-for")) headers.set("x-forwarded-for", this.address);
120
+ if (this.origin && !headers.has("origin")) headers.set("origin", this.origin);
81
121
  return this.request({
82
122
  url: request.url,
83
123
  method: request.method,
@@ -133,6 +173,26 @@ var TooManyRedirects = class extends Error {
133
173
  this.name = "TooManyRedirects";
134
174
  }
135
175
  };
176
+ /** One DNS label, as a tenant's slug is. */
177
+ const SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
178
+ /** `browser.on(slug)` in an app with no site on every subdomain. */
179
+ var NoWildcardSite = class extends Error {
180
+ slug;
181
+ constructor(slug) {
182
+ super(`browser.on('${slug}') puts a tenant's slug into the app's site on every subdomain, and this browser knows of none. Declare a StaticSite with subdomain: '*', or pass its address as \`site\`.`);
183
+ this.slug = slug;
184
+ this.name = "NoWildcardSite";
185
+ }
186
+ };
187
+ /** `browser.on(slug)` with something no host can start with. */
188
+ var NotATenantSlug = class extends Error {
189
+ slug;
190
+ constructor(slug) {
191
+ super(`'${slug}' is not a tenant's slug: one DNS label of lowercase letters, digits and inner hyphens, such as 'acme'.`);
192
+ this.slug = slug;
193
+ this.name = "NotATenantSlug";
194
+ }
195
+ };
136
196
  /**
137
197
  * An address from 10.0.0.0/8, which nothing routes to. Random rather than
138
198
  * counted: test files run in separate workers that share no counter.
@@ -142,6 +202,6 @@ function privateAddress() {
142
202
  return `10.${n >> 16 & 255}.${n >> 8 & 255}.${n & 255}`;
143
203
  }
144
204
  //#endregion
145
- export { Browser, TooManyRedirects };
205
+ export { Browser, NoWildcardSite, NotATenantSlug, TooManyRedirects };
146
206
 
147
207
  //# sourceMappingURL=browser.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.mjs","names":[],"sources":["../src/browser.ts"],"sourcesContent":["/**\n * A browser, for tests: a `fetch` that keeps cookies the way a browser does.\n *\n * An app's real clients — its typed API client, better-auth's client — run on\n * whatever `fetch` they are given. Give them this one and a test signs in the\n * way a person does: the auth server's `Set-Cookie` lands in the jar, and every\n * later request to a URL the cookie belongs to carries it. The jar follows the\n * browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set\n * for the wrong domain is not sent, exactly as a browser would not send it.\n *\n * Extend it once per app with that app's clients:\n *\n * ```ts\n * export class Browser extends TestBrowser {\n * readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });\n * }\n * ```\n */\n\nimport { randomInt } from 'node:crypto';\nimport { CookieJar } from 'tough-cookie';\nimport { currentTestContext } from './context';\n\n/** How many redirects `fetch` follows before giving up, as browsers do. */\nconst MAX_REDIRECTS = 20;\n\nexport interface BrowserOptions {\n\t/**\n\t * The `fetch` requests go out on. Defaults to the global one at the time\n\t * the browser is created — so a browser made inside a test goes through\n\t * whatever the test installed (MSW, the context stamp) and never through\n\t * itself once installed.\n\t */\n\tfetch?: typeof fetch;\n\t/**\n\t * The address this browser connects from. A fresh one by default, from a\n\t * private range nothing routes to — see {@link Browser.address}.\n\t */\n\taddress?: string;\n}\n\nexport class Browser {\n\t/** The cookies this browser holds. */\n\treadonly jar = new CookieJar();\n\n\t/**\n\t * The address this browser connects from, sent as `x-forwarded-for` the way\n\t * a proxy in front of the app adds it. Each browser is a different person on\n\t * a different connection, so what an app keys by client — an auth server's\n\t * rate limit — counts each on its own. Without it every browser was the same\n\t * client, and concurrent tests queued on the same rate-limit row of each\n\t * other's open transactions. A request that sets the header itself — a test\n\t * that is several machines — keeps its own.\n\t */\n\treadonly address: string;\n\n\t/**\n\t * This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`\n\t * into the jar on the way back, redirects followed hop by hop so each hop's\n\t * cookies are kept.\n\t *\n\t * On the server side of a test — a handler serving a request — it is the\n\t * plain `fetch`: a server forwards what it was handed and never reaches into\n\t * a browser's jar.\n\t */\n\treadonly fetch: typeof fetch;\n\n\tprivate readonly send: typeof fetch;\n\n\tconstructor(options: BrowserOptions = {}) {\n\t\tthis.send = options.fetch ?? globalThis.fetch;\n\t\tthis.address = options.address ?? privateAddress();\n\t\tthis.fetch = (input, init) => {\n\t\t\tif (currentTestContext()?.side === 'server') {\n\t\t\t\treturn this.send(input, init);\n\t\t\t}\n\t\t\treturn this.start(new Request(input, init), init?.redirect);\n\t\t};\n\t}\n\n\t/** Open a URL the way clicking a link does: a GET, redirects followed. */\n\tvisit(url: string | URL): Promise<Response> {\n\t\treturn this.fetch(String(url));\n\t}\n\n\t/** The cookies this browser would send to `url`, as a header value. */\n\tcookieHeader(url: string | URL): Promise<string> {\n\t\treturn this.jar.getCookieString(String(url));\n\t}\n\n\t/**\n\t * Make this browser the global `fetch`, for code that uses the global one —\n\t * an app's module-level clients. Returns what puts the previous one back.\n\t */\n\tinstall(): () => void {\n\t\tconst previous = globalThis.fetch;\n\t\tglobalThis.fetch = this.fetch;\n\t\treturn () => {\n\t\t\tglobalThis.fetch = previous;\n\t\t};\n\t}\n\n\t/** Read the body once, so a redirect that keeps the method can send it again. */\n\tprivate async start(\n\t\trequest: Request,\n\t\tredirect: RequestInit['redirect'],\n\t): Promise<Response> {\n\t\tconst body =\n\t\t\trequest.method === 'GET' || request.method === 'HEAD'\n\t\t\t\t? undefined\n\t\t\t\t: await request.arrayBuffer();\n\t\tconst headers = new Headers(request.headers);\n\t\tif (!headers.has('x-forwarded-for')) {\n\t\t\theaders.set('x-forwarded-for', this.address);\n\t\t}\n\t\treturn this.request(\n\t\t\t{ url: request.url, method: request.method, headers, body },\n\t\t\tredirect,\n\t\t);\n\t}\n\n\tprivate async request(\n\t\trequest: Hop,\n\t\tredirect: RequestInit['redirect'],\n\t\thops = 0,\n\t): Promise<Response> {\n\t\tconst headers = new Headers(request.headers);\n\t\tconst cookie = await this.jar.getCookieString(request.url);\n\t\tif (cookie) {\n\t\t\tconst existing = headers.get('cookie');\n\t\t\theaders.set('cookie', existing ? `${existing}; ${cookie}` : cookie);\n\t\t}\n\n\t\tconst response = await this.send(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders,\n\t\t\tbody: request.body,\n\t\t\tredirect: 'manual',\n\t\t});\n\n\t\tfor (const set of response.headers.getSetCookie()) {\n\t\t\t// A cookie a browser would refuse — the wrong domain, Secure over\n\t\t\t// plain HTTP — is dropped silently, as a browser drops it.\n\t\t\tawait this.jar.setCookie(set, request.url, { ignoreError: true });\n\t\t}\n\n\t\tconst location = response.headers.get('location');\n\t\tif (\n\t\t\tredirect === 'manual' ||\n\t\t\t!location ||\n\t\t\tresponse.status < 300 ||\n\t\t\tresponse.status >= 400\n\t\t) {\n\t\t\treturn response;\n\t\t}\n\n\t\tif (hops >= MAX_REDIRECTS) {\n\t\t\tthrow new TooManyRedirects(request.url, MAX_REDIRECTS);\n\t\t}\n\n\t\t// 303, and 301/302 after a POST, continue as a GET without a body — what\n\t\t// every browser does, whatever the spec once said about 302.\n\t\tconst keepsMethod =\n\t\t\tresponse.status === 307 ||\n\t\t\tresponse.status === 308 ||\n\t\t\trequest.method === 'GET' ||\n\t\t\trequest.method === 'HEAD';\n\n\t\tconst url = new URL(location, request.url).toString();\n\t\tconst next: Hop = keepsMethod\n\t\t\t? { ...request, url }\n\t\t\t: { url, method: 'GET', headers: withoutBody(request.headers) };\n\n\t\treturn this.request(next, redirect, hops + 1);\n\t}\n}\n\n/** One request in a redirect chain, with its body already read. */\ninterface Hop {\n\turl: string;\n\tmethod: string;\n\theaders: Headers;\n\tbody?: ArrayBuffer;\n}\n\n/** Headers for a request that no longer carries the body they described. */\nfunction withoutBody(headers: Headers): Headers {\n\tconst next = new Headers(headers);\n\tnext.delete('content-type');\n\tnext.delete('content-length');\n\treturn next;\n}\n\n/** A redirect chain longer than any browser follows. */\nexport class TooManyRedirects extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly limit: number,\n\t) {\n\t\tsuper(\n\t\t\t`${url} redirected more than ${limit} times. A browser gives up here ` +\n\t\t\t\t`too — look for a redirect loop.`,\n\t\t);\n\t\tthis.name = 'TooManyRedirects';\n\t}\n}\n\n/**\n * An address from 10.0.0.0/8, which nothing routes to. Random rather than\n * counted: test files run in separate workers that share no counter.\n */\nfunction privateAddress(): string {\n\tconst n = randomInt(1, 2 ** 24 - 1);\n\treturn `10.${(n >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AK,KAAK,CAAC;CAClC,OAAO,MAAO,KAAK,KAAM,IAAI,GAAI,KAAK,IAAK,IAAI,GAAG,IAAI;AACvD"}
1
+ {"version":3,"file":"browser.mjs","names":[],"sources":["../src/browser.ts"],"sourcesContent":["/**\n * A browser, for tests: a `fetch` that keeps cookies the way a browser does.\n *\n * An app's real clients — its typed API client, better-auth's client — run on\n * whatever `fetch` they are given. Give them this one and a test signs in the\n * way a person does: the auth server's `Set-Cookie` lands in the jar, and every\n * later request to a URL the cookie belongs to carries it. The jar follows the\n * browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set\n * for the wrong domain is not sent, exactly as a browser would not send it.\n *\n * Extend it once per app with that app's clients:\n *\n * ```ts\n * export class Browser extends TestBrowser {\n * readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });\n * }\n * ```\n */\n\nimport { randomInt } from 'node:crypto';\nimport { CookieJar } from 'tough-cookie';\nimport { currentTestContext } from './context';\n\n/** How many redirects `fetch` follows before giving up, as browsers do. */\nconst MAX_REDIRECTS = 20;\n\nexport interface BrowserOptions {\n\t/**\n\t * The `fetch` requests go out on. Defaults to the global one at the time\n\t * the browser is created — so a browser made inside a test goes through\n\t * whatever the test installed (MSW, the context stamp) and never through\n\t * itself once installed.\n\t */\n\tfetch?: typeof fetch;\n\t/**\n\t * The address this browser connects from. A fresh one by default, from a\n\t * private range nothing routes to — see {@link Browser.address}.\n\t */\n\taddress?: string;\n\t/**\n\t * The cookies it starts with — another browser's jar, to be the same\n\t * person on another tab. A fresh jar by default.\n\t */\n\tjar?: CookieJar;\n\t/**\n\t * The address of the app's site on every subdomain,\n\t * `https://*.test.shop.localhost:8443`, which {@link Browser.on} puts a\n\t * tenant's slug into. A feature test passes it when the app declares one.\n\t */\n\tsite?: string;\n\t/**\n\t * The page this browser is on: sent as `Origin` on every request that does\n\t * not set its own, and what a relative {@link Browser.visit} resolves\n\t * against. See {@link Browser.on}.\n\t */\n\torigin?: string;\n}\n\nexport class Browser {\n\t/** The cookies this browser holds. */\n\treadonly jar: CookieJar;\n\n\t/**\n\t * The page this browser is on, sent as `Origin` — what a surface's CORS\n\t * and an auth server's trusted origins check, and what a multi-tenant app\n\t * reads its tenant from. None until {@link Browser.on} gives it one.\n\t */\n\treadonly origin?: string;\n\n\t/**\n\t * The address this browser connects from, sent as `x-forwarded-for` the way\n\t * a proxy in front of the app adds it. Each browser is a different person on\n\t * a different connection, so what an app keys by client — an auth server's\n\t * rate limit — counts each on its own. Without it every browser was the same\n\t * client, and concurrent tests queued on the same rate-limit row of each\n\t * other's open transactions. A request that sets the header itself — a test\n\t * that is several machines — keeps its own.\n\t */\n\treadonly address: string;\n\n\t/**\n\t * This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`\n\t * into the jar on the way back, redirects followed hop by hop so each hop's\n\t * cookies are kept.\n\t *\n\t * On the server side of a test — a handler serving a request — it is the\n\t * plain `fetch`: a server forwards what it was handed and never reaches into\n\t * a browser's jar.\n\t */\n\treadonly fetch: typeof fetch;\n\n\tprivate readonly send: typeof fetch;\n\tprivate readonly site?: string;\n\n\tconstructor(options: BrowserOptions = {}) {\n\t\tthis.send = options.fetch ?? globalThis.fetch;\n\t\tthis.address = options.address ?? privateAddress();\n\t\tthis.jar = options.jar ?? new CookieJar();\n\t\tif (options.site) this.site = options.site;\n\t\tif (options.origin) this.origin = options.origin;\n\t\tthis.fetch = (input, init) => {\n\t\t\tif (currentTestContext()?.side === 'server') {\n\t\t\t\treturn this.send(input, init);\n\t\t\t}\n\t\t\treturn this.start(new Request(input, init), init?.redirect);\n\t\t};\n\t}\n\n\t/**\n\t * Open a URL the way clicking a link does: a GET, redirects followed. A\n\t * path is opened on the page this browser is on.\n\t */\n\tvisit(url: string | URL): Promise<Response> {\n\t\treturn this.fetch(\n\t\t\tthis.origin ? new URL(url, this.origin).toString() : String(url),\n\t\t);\n\t}\n\n\t/**\n\t * The same person on a tenant's host: this browser — its cookies, its\n\t * address, its clients — on `https://<slug>.<domain>`, the app's site on\n\t * every subdomain. Each request it makes says so in `Origin`, as a page on\n\t * that host would, so a test signs in once and calls the app as two\n\t * tenants:\n\t *\n\t * ```ts\n\t * await browser.signIn();\n\t * await browser.on('acme').api.post('/orders', { body });\n\t * expect(await browser.on('globex').api.get('/orders')).toEqual([]);\n\t * ```\n\t */\n\ton(slug: string): this {\n\t\tif (!this.site) throw new NoWildcardSite(slug);\n\t\tif (!SLUG.test(slug)) throw new NotATenantSlug(slug);\n\n\t\tconst origin = new URL(this.site.replace('*', slug)).origin;\n\t\tconst Same = this.constructor as new (options: BrowserOptions) => this;\n\t\treturn new Same({\n\t\t\tfetch: this.send,\n\t\t\taddress: this.address,\n\t\t\tjar: this.jar,\n\t\t\tsite: this.site,\n\t\t\torigin,\n\t\t});\n\t}\n\n\t/** The cookies this browser would send to `url`, as a header value. */\n\tcookieHeader(url: string | URL): Promise<string> {\n\t\treturn this.jar.getCookieString(String(url));\n\t}\n\n\t/**\n\t * Make this browser the global `fetch`, for code that uses the global one —\n\t * an app's module-level clients. Returns what puts the previous one back.\n\t */\n\tinstall(): () => void {\n\t\tconst previous = globalThis.fetch;\n\t\tglobalThis.fetch = this.fetch;\n\t\treturn () => {\n\t\t\tglobalThis.fetch = previous;\n\t\t};\n\t}\n\n\t/** Read the body once, so a redirect that keeps the method can send it again. */\n\tprivate async start(\n\t\trequest: Request,\n\t\tredirect: RequestInit['redirect'],\n\t): Promise<Response> {\n\t\tconst body =\n\t\t\trequest.method === 'GET' || request.method === 'HEAD'\n\t\t\t\t? undefined\n\t\t\t\t: await request.arrayBuffer();\n\t\tconst headers = new Headers(request.headers);\n\t\tif (!headers.has('x-forwarded-for')) {\n\t\t\theaders.set('x-forwarded-for', this.address);\n\t\t}\n\t\tif (this.origin && !headers.has('origin')) {\n\t\t\theaders.set('origin', this.origin);\n\t\t}\n\t\treturn this.request(\n\t\t\t{ url: request.url, method: request.method, headers, body },\n\t\t\tredirect,\n\t\t);\n\t}\n\n\tprivate async request(\n\t\trequest: Hop,\n\t\tredirect: RequestInit['redirect'],\n\t\thops = 0,\n\t): Promise<Response> {\n\t\tconst headers = new Headers(request.headers);\n\t\tconst cookie = await this.jar.getCookieString(request.url);\n\t\tif (cookie) {\n\t\t\tconst existing = headers.get('cookie');\n\t\t\theaders.set('cookie', existing ? `${existing}; ${cookie}` : cookie);\n\t\t}\n\n\t\tconst response = await this.send(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders,\n\t\t\tbody: request.body,\n\t\t\tredirect: 'manual',\n\t\t});\n\n\t\tfor (const set of response.headers.getSetCookie()) {\n\t\t\t// A cookie a browser would refuse — the wrong domain, Secure over\n\t\t\t// plain HTTP — is dropped silently, as a browser drops it.\n\t\t\tawait this.jar.setCookie(set, request.url, { ignoreError: true });\n\t\t}\n\n\t\tconst location = response.headers.get('location');\n\t\tif (\n\t\t\tredirect === 'manual' ||\n\t\t\t!location ||\n\t\t\tresponse.status < 300 ||\n\t\t\tresponse.status >= 400\n\t\t) {\n\t\t\treturn response;\n\t\t}\n\n\t\tif (hops >= MAX_REDIRECTS) {\n\t\t\tthrow new TooManyRedirects(request.url, MAX_REDIRECTS);\n\t\t}\n\n\t\t// 303, and 301/302 after a POST, continue as a GET without a body — what\n\t\t// every browser does, whatever the spec once said about 302.\n\t\tconst keepsMethod =\n\t\t\tresponse.status === 307 ||\n\t\t\tresponse.status === 308 ||\n\t\t\trequest.method === 'GET' ||\n\t\t\trequest.method === 'HEAD';\n\n\t\tconst url = new URL(location, request.url).toString();\n\t\tconst next: Hop = keepsMethod\n\t\t\t? { ...request, url }\n\t\t\t: { url, method: 'GET', headers: withoutBody(request.headers) };\n\n\t\treturn this.request(next, redirect, hops + 1);\n\t}\n}\n\n/** One request in a redirect chain, with its body already read. */\ninterface Hop {\n\turl: string;\n\tmethod: string;\n\theaders: Headers;\n\tbody?: ArrayBuffer;\n}\n\n/** Headers for a request that no longer carries the body they described. */\nfunction withoutBody(headers: Headers): Headers {\n\tconst next = new Headers(headers);\n\tnext.delete('content-type');\n\tnext.delete('content-length');\n\treturn next;\n}\n\n/** A redirect chain longer than any browser follows. */\nexport class TooManyRedirects extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly limit: number,\n\t) {\n\t\tsuper(\n\t\t\t`${url} redirected more than ${limit} times. A browser gives up here ` +\n\t\t\t\t`too — look for a redirect loop.`,\n\t\t);\n\t\tthis.name = 'TooManyRedirects';\n\t}\n}\n\n/** One DNS label, as a tenant's slug is. */\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** `browser.on(slug)` in an app with no site on every subdomain. */\nexport class NoWildcardSite extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`browser.on('${slug}') puts a tenant's slug into the app's site on ` +\n\t\t\t\t`every subdomain, and this browser knows of none. Declare a ` +\n\t\t\t\t`StaticSite with subdomain: '*', or pass its address as \\`site\\`.`,\n\t\t);\n\t\tthis.name = 'NoWildcardSite';\n\t}\n}\n\n/** `browser.on(slug)` with something no host can start with. */\nexport class NotATenantSlug extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`'${slug}' is not a tenant's slug: one DNS label of lowercase ` +\n\t\t\t\t`letters, digits and inner hyphens, such as 'acme'.`,\n\t\t);\n\t\tthis.name = 'NotATenantSlug';\n\t}\n}\n\n/**\n * An address from 10.0.0.0/8, which nothing routes to. Random rather than\n * counted: test files run in separate workers that share no counter.\n */\nfunction privateAddress(): string {\n\tconst n = randomInt(1, 2 ** 24 - 1);\n\treturn `10.${(n >> 16) & 255}.${(n >> 8) & 255}.${n & 255}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB;AAkCtB,IAAa,UAAb,MAAqB;;CAEpB;;;;;;CAOA;;;;;;;;;;CAWA;;;;;;;;;;CAWA;CAEA;CACA;CAEA,YAAY,UAA0B,CAAC,GAAG;EACzC,KAAK,OAAO,QAAQ,SAAS,WAAW;EACxC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UAAU,OAAO,CAAC;CAC7C;AACD;;AAWA,SAAS,YAAY,SAA2B;CAC/C,MAAM,OAAO,IAAI,QAAQ,OAAO;CAChC,KAAK,OAAO,cAAc;CAC1B,KAAK,OAAO,gBAAgB;CAC5B,OAAO;AACR;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CAFV,YACC,KACA,OACC;EACD,MACC,GAAG,IAAI,wBAAwB,MAAM,gEAEtC;EANS,KAAA,MAAA;EACA,KAAA,QAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,MAAM,OAAO;;AAGb,IAAa,iBAAb,cAAoC,MAAM;CACpB;CAArB,YAAY,MAAuB;EAClC,MACC,eAAe,KAAK,2KAGrB;EALoB,KAAA,OAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,iBAAb,cAAoC,MAAM;CACpB;CAArB,YAAY,MAAuB;EAClC,MACC,IAAI,KAAK,wGAEV;EAJoB,KAAA,OAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;AAMA,SAAS,iBAAyB;CACjC,MAAM,IAAI,UAAU,GAAG,KAAK,KAAK,CAAC;CAClC,OAAO,MAAO,KAAK,KAAM,IAAI,GAAI,KAAK,IAAK,IAAI,GAAG,IAAI;AACvD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/testkit",
3
- "version": "10.0.0-alpha.132",
3
+ "version": "10.0.0-alpha.134",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -161,17 +161,17 @@
161
161
  "dependencies": {
162
162
  "@faker-js/faker": "~10.6.0",
163
163
  "tough-cookie": "~6.0.2",
164
- "@geekmidas/envkit": "^10.0.0-alpha.132",
165
- "@geekmidas/logger": "^10.0.0-alpha.132",
166
- "@geekmidas/services": "^10.0.0-alpha.132"
164
+ "@geekmidas/envkit": "^10.0.0-alpha.134",
165
+ "@geekmidas/logger": "^10.0.0-alpha.134",
166
+ "@geekmidas/services": "^10.0.0-alpha.134"
167
167
  },
168
168
  "devDependencies": {
169
169
  "@better-auth/test-utils": "~1.7.6",
170
170
  "@types/pg": "~8.23.1",
171
171
  "better-auth": "~1.7.6",
172
- "@geekmidas/envkit": "^10.0.0-alpha.132",
173
- "@geekmidas/logger": "^10.0.0-alpha.132",
174
- "@geekmidas/services": "^10.0.0-alpha.132"
172
+ "@geekmidas/envkit": "^10.0.0-alpha.134",
173
+ "@geekmidas/logger": "^10.0.0-alpha.134",
174
+ "@geekmidas/services": "^10.0.0-alpha.134"
175
175
  },
176
176
  "repository": {
177
177
  "type": "git",