@geekmidas/testkit 10.0.0-alpha.16 → 10.0.0-alpha.161
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 +108 -0
- package/dist/PostgresKyselyMigrator.d.cts +1 -1
- package/dist/PostgresKyselyMigrator.d.mts +1 -1
- package/dist/{PostgresMigrator-CoHQ95cT.d.cts → PostgresMigrator-CDPnnwMJ.d.cts} +10 -3
- package/dist/PostgresMigrator-CDPnnwMJ.d.cts.map +1 -0
- package/dist/{PostgresMigrator-CoHQ95cT.d.mts → PostgresMigrator-CDPnnwMJ.d.mts} +10 -3
- package/dist/PostgresMigrator-CDPnnwMJ.d.mts.map +1 -0
- package/dist/PostgresMigrator.cjs +14 -5
- package/dist/PostgresMigrator.cjs.map +1 -1
- package/dist/PostgresMigrator.d.cts +1 -1
- package/dist/PostgresMigrator.d.mts +1 -1
- package/dist/PostgresMigrator.mjs +14 -5
- package/dist/PostgresMigrator.mjs.map +1 -1
- package/dist/PostgresObjectionMigrator.d.cts +1 -1
- package/dist/PostgresObjectionMigrator.d.mts +1 -1
- package/dist/browser.cjs +211 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +113 -0
- package/dist/browser.d.cts.map +1 -0
- package/dist/browser.d.mts +113 -0
- package/dist/browser.d.mts.map +1 -0
- package/dist/browser.mjs +207 -0
- package/dist/browser.mjs.map +1 -0
- package/dist/context.cjs +80 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +55 -0
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.mts +55 -0
- package/dist/context.d.mts.map +1 -0
- package/dist/context.mjs +73 -0
- package/dist/context.mjs.map +1 -0
- package/dist/faker.cjs +51 -0
- package/dist/faker.cjs.map +1 -1
- package/dist/faker.d.cts +26 -19
- package/dist/faker.d.cts.map +1 -1
- package/dist/faker.d.mts +26 -19
- package/dist/faker.d.mts.map +1 -1
- package/dist/faker.mjs +51 -1
- package/dist/faker.mjs.map +1 -1
- package/dist/mailbox.cjs +107 -0
- package/dist/mailbox.cjs.map +1 -0
- package/dist/mailbox.d.cts +58 -0
- package/dist/mailbox.d.cts.map +1 -0
- package/dist/mailbox.d.mts +58 -0
- package/dist/mailbox.d.mts.map +1 -0
- package/dist/mailbox.mjs +103 -0
- package/dist/mailbox.mjs.map +1 -0
- package/dist/transactions.cjs +239 -0
- package/dist/transactions.cjs.map +1 -0
- package/dist/transactions.d.cts +44 -0
- package/dist/transactions.d.cts.map +1 -0
- package/dist/transactions.d.mts +44 -0
- package/dist/transactions.d.mts.map +1 -0
- package/dist/transactions.mjs +234 -0
- package/dist/transactions.mjs.map +1 -0
- package/package.json +57 -8
- package/dist/PostgresMigrator-CoHQ95cT.d.cts.map +0 -1
- package/dist/PostgresMigrator-CoHQ95cT.d.mts.map +0 -1
package/dist/mailbox.cjs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/mailbox.ts
|
|
3
|
+
/** How long `last()` waits for mail that is still on its way. */
|
|
4
|
+
const DEFAULT_TIMEOUT = 5e3;
|
|
5
|
+
const POLL_INTERVAL = 50;
|
|
6
|
+
/** A way to read the mail sent to one address. */
|
|
7
|
+
function createMailbox(options) {
|
|
8
|
+
const inbox = options.inbox.replace(/\/$/, "");
|
|
9
|
+
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
10
|
+
const get = (path, init) => (options.fetch ?? globalThis.fetch)(`${inbox}${path}`, init);
|
|
11
|
+
return (address) => {
|
|
12
|
+
const query = `?query=${encodeURIComponent(`to:"${address}"`)}`;
|
|
13
|
+
const all = async () => {
|
|
14
|
+
const found = await json(await get(`/api/v1/search${query}`), inbox);
|
|
15
|
+
return Promise.all(found.messages.map(async ({ ID }) => {
|
|
16
|
+
const response = await get(`/api/v1/message/${ID}/raw`);
|
|
17
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
18
|
+
return email(ID, new Uint8Array(await response.arrayBuffer()));
|
|
19
|
+
}));
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
all,
|
|
23
|
+
async last() {
|
|
24
|
+
const deadline = Date.now() + timeout;
|
|
25
|
+
for (;;) {
|
|
26
|
+
const [newest] = await all();
|
|
27
|
+
if (newest) return newest;
|
|
28
|
+
if (Date.now() >= deadline) throw new NoMail(address, timeout);
|
|
29
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
async clear() {
|
|
33
|
+
const response = await get(`/api/v1/search${query}`, { method: "DELETE" });
|
|
34
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async function json(response, inbox) {
|
|
40
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
41
|
+
return await response.json();
|
|
42
|
+
}
|
|
43
|
+
/** The message, through the one MIME parser everything that reads mail uses. */
|
|
44
|
+
async function email(id, raw) {
|
|
45
|
+
let inbound;
|
|
46
|
+
try {
|
|
47
|
+
inbound = await import("@geekmidas/emailkit/inbound");
|
|
48
|
+
} catch (cause) {
|
|
49
|
+
throw new MailboxNeedsEmailkit(cause);
|
|
50
|
+
}
|
|
51
|
+
const message = await inbound.parseEmail(raw);
|
|
52
|
+
const html = message.html ?? "";
|
|
53
|
+
const text = message.text ?? "";
|
|
54
|
+
const links = [...new Set([...html.matchAll(/href="(https?:\/\/[^"]+)"/g), ...text.matchAll(/(https?:\/\/[^\s<>"]+)/g)].map(([, url]) => decodeEntities(url)))];
|
|
55
|
+
return {
|
|
56
|
+
id,
|
|
57
|
+
from: message.from?.address ?? "",
|
|
58
|
+
to: message.to.map(({ address }) => address),
|
|
59
|
+
subject: message.subject ?? "",
|
|
60
|
+
text,
|
|
61
|
+
html,
|
|
62
|
+
headers: message.headers,
|
|
63
|
+
links,
|
|
64
|
+
link: links[0],
|
|
65
|
+
attachments: message.attachments
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** `&` in an HTML attribute is `&` in the URL it names. */
|
|
69
|
+
function decodeEntities(url) {
|
|
70
|
+
return url.replaceAll("&", "&");
|
|
71
|
+
}
|
|
72
|
+
/** No email to an address arrived in time. */
|
|
73
|
+
var NoMail = class extends Error {
|
|
74
|
+
address;
|
|
75
|
+
timeout;
|
|
76
|
+
constructor(address, timeout) {
|
|
77
|
+
super(`No email to ${address} arrived within ${timeout}ms. Check that the code under test sends it, and to that address.`);
|
|
78
|
+
this.address = address;
|
|
79
|
+
this.timeout = timeout;
|
|
80
|
+
this.name = "NoMail";
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */
|
|
84
|
+
var MailboxNeedsEmailkit = class extends Error {
|
|
85
|
+
constructor(cause) {
|
|
86
|
+
super("Reading mail from the mailbox parses it with @geekmidas/emailkit, which could not be loaded. Add it to the dev dependencies of the app whose mail the test reads.", { cause });
|
|
87
|
+
this.name = "MailboxNeedsEmailkit";
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
/** Mailpit did not answer. */
|
|
91
|
+
var InboxUnreachable = class extends Error {
|
|
92
|
+
inbox;
|
|
93
|
+
status;
|
|
94
|
+
constructor(inbox, status) {
|
|
95
|
+
super(`Mailpit at ${inbox} answered ${status}. Is it running? \`gkm test\` starts it when the app declares an Email construct.`);
|
|
96
|
+
this.inbox = inbox;
|
|
97
|
+
this.status = status;
|
|
98
|
+
this.name = "InboxUnreachable";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
//#endregion
|
|
102
|
+
exports.InboxUnreachable = InboxUnreachable;
|
|
103
|
+
exports.MailboxNeedsEmailkit = MailboxNeedsEmailkit;
|
|
104
|
+
exports.NoMail = NoMail;
|
|
105
|
+
exports.createMailbox = createMailbox;
|
|
106
|
+
|
|
107
|
+
//# sourceMappingURL=mailbox.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox.cjs","names":[],"sources":["../src/mailbox.ts"],"sourcesContent":["/**\n * The mail a test sent, read from Mailpit.\n *\n * Locally, mail goes over real SMTP to Mailpit — the same client, the same\n * message, only the host differs. A test reads what arrived through Mailpit's\n * HTTP API, so a magic link is signed in with by opening the email that was\n * actually sent rather than a token pulled from somewhere else.\n *\n * Mailpit has one inbox for everything, and transactions do not reach it, so a\n * test keeps to its own mail by address: a unique recipient per test, read by\n * `to:`, and cleared afterwards.\n */\n\nimport type { ReceivedAttachment } from '@geekmidas/emailkit/inbound';\n\n/** How long `last()` waits for mail that is still on its way. */\nconst DEFAULT_TIMEOUT = 5_000;\nconst POLL_INTERVAL = 50;\n\nexport interface MailboxOptions {\n\t/** Mailpit's HTTP address — what `gkm test` injects as `<ID>_INBOX_URL`. */\n\tinbox: string;\n\t/** The `fetch` to read it with. Defaults to the global one. */\n\tfetch?: typeof fetch;\n\t/** How long `last()` waits for mail to arrive. */\n\ttimeout?: number;\n}\n\n/** One email, as it arrived. */\nexport interface Email {\n\tid: string;\n\tfrom: string;\n\tto: string[];\n\tsubject: string;\n\ttext: string;\n\thtml: string;\n\t/** Every header, by lower-case name, as the parser an inbox uses reads them. */\n\theaders: Readonly<Record<string, readonly string[]>>;\n\t/** Every `http(s)` link in the email, in order. */\n\tlinks: string[];\n\t/** The first link — the one a sign-in or confirmation email is about. */\n\tlink: string | undefined;\n\t/**\n\t * Its files, read from the raw message by the parser an inbox's handler\n\t * uses — so what survives one survives the other.\n\t */\n\tattachments: ReceivedAttachment[];\n}\n\nexport interface Mailbox {\n\t/** The newest email to this address, waiting for one if none has arrived. */\n\tlast(): Promise<Email>;\n\t/** Every email to this address, newest first. */\n\tall(): Promise<Email[]>;\n\t/** Delete every email to this address. */\n\tclear(): Promise<void>;\n}\n\n/** A way to read the mail sent to one address. */\nexport function createMailbox(\n\toptions: MailboxOptions,\n): (address: string) => Mailbox {\n\tconst inbox = options.inbox.replace(/\\/$/, '');\n\tconst timeout = options.timeout ?? DEFAULT_TIMEOUT;\n\tconst get = (path: string, init?: RequestInit) =>\n\t\t(options.fetch ?? globalThis.fetch)(`${inbox}${path}`, init);\n\n\treturn (address) => {\n\t\tconst query = `?query=${encodeURIComponent(`to:\"${address}\"`)}`;\n\n\t\tconst all = async (): Promise<Email[]> => {\n\t\t\tconst found = await json<SearchResult>(\n\t\t\t\tawait get(`/api/v1/search${query}`),\n\t\t\t\tinbox,\n\t\t\t);\n\t\t\treturn Promise.all(\n\t\t\t\tfound.messages.map(async ({ ID }) => {\n\t\t\t\t\tconst response = await get(`/api/v1/message/${ID}/raw`);\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tthrow new InboxUnreachable(inbox, response.status);\n\t\t\t\t\t}\n\t\t\t\t\treturn email(ID, new Uint8Array(await response.arrayBuffer()));\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\n\t\treturn {\n\t\t\tall,\n\t\t\tasync last() {\n\t\t\t\tconst deadline = Date.now() + timeout;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst [newest] = await all();\n\t\t\t\t\tif (newest) return newest;\n\t\t\t\t\tif (Date.now() >= deadline) throw new NoMail(address, timeout);\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync clear() {\n\t\t\t\tconst response = await get(`/api/v1/search${query}`, {\n\t\t\t\t\tmethod: 'DELETE',\n\t\t\t\t});\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new InboxUnreachable(inbox, response.status);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n}\n\ninterface SearchResult {\n\tmessages: { ID: string }[];\n}\n\nasync function json<T>(response: Response, inbox: string): Promise<T> {\n\tif (!response.ok) throw new InboxUnreachable(inbox, response.status);\n\treturn (await response.json()) as T;\n}\n\n/** The message, through the one MIME parser everything that reads mail uses. */\nasync function email(id: string, raw: Uint8Array): Promise<Email> {\n\t// emailkit is an optional peer: loaded when mail is read, inside a `try`\n\t// so a bundled test harness for an app that sends none leaves it alone.\n\tlet inbound: typeof import('@geekmidas/emailkit/inbound');\n\ttry {\n\t\tinbound = await import('@geekmidas/emailkit/inbound');\n\t} catch (cause) {\n\t\tthrow new MailboxNeedsEmailkit(cause);\n\t}\n\tconst message = await inbound.parseEmail(raw);\n\tconst html = message.html ?? '';\n\tconst text = message.text ?? '';\n\tconst links = [\n\t\t...new Set(\n\t\t\t[\n\t\t\t\t...html.matchAll(/href=\"(https?:\\/\\/[^\"]+)\"/g),\n\t\t\t\t...text.matchAll(/(https?:\\/\\/[^\\s<>\"]+)/g),\n\t\t\t].map(([, url]) => decodeEntities(url!)),\n\t\t),\n\t];\n\n\treturn {\n\t\tid,\n\t\tfrom: message.from?.address ?? '',\n\t\tto: message.to.map(({ address }) => address),\n\t\tsubject: message.subject ?? '',\n\t\ttext,\n\t\thtml,\n\t\theaders: message.headers,\n\t\tlinks,\n\t\tlink: links[0],\n\t\tattachments: message.attachments,\n\t};\n}\n\n/** `&` in an HTML attribute is `&` in the URL it names. */\nfunction decodeEntities(url: string): string {\n\treturn url.replaceAll('&', '&');\n}\n\n/** No email to an address arrived in time. */\nexport class NoMail extends Error {\n\tconstructor(\n\t\treadonly address: string,\n\t\treadonly timeout: number,\n\t) {\n\t\tsuper(\n\t\t\t`No email to ${address} arrived within ${timeout}ms. Check that the ` +\n\t\t\t\t`code under test sends it, and to that address.`,\n\t\t);\n\t\tthis.name = 'NoMail';\n\t}\n}\n\n/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */\nexport class MailboxNeedsEmailkit extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(\n\t\t\t'Reading mail from the mailbox parses it with @geekmidas/emailkit, ' +\n\t\t\t\t'which could not be loaded. Add it to the dev dependencies of the ' +\n\t\t\t\t'app whose mail the test reads.',\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'MailboxNeedsEmailkit';\n\t}\n}\n\n/** Mailpit did not answer. */\nexport class InboxUnreachable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`Mailpit at ${inbox} answered ${status}. Is it running? \\`gkm test\\` ` +\n\t\t\t\t`starts it when the app declares an Email construct.`,\n\t\t);\n\t\tthis.name = 'InboxUnreachable';\n\t}\n}\n"],"mappings":";;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;;AA0CtB,SAAgB,cACf,SAC+B;CAC/B,MAAM,QAAQ,QAAQ,MAAM,QAAQ,OAAO,EAAE;CAC7C,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,OAAO,MAAc,UACzB,QAAQ,SAAS,WAAW,MAAA,CAAO,GAAG,QAAQ,QAAQ,IAAI;CAE5D,QAAQ,YAAY;EACnB,MAAM,QAAQ,UAAU,mBAAmB,OAAO,QAAQ,EAAE;EAE5D,MAAM,MAAM,YAA8B;GACzC,MAAM,QAAQ,MAAM,KACnB,MAAM,IAAI,iBAAiB,OAAO,GAClC,KACD;GACA,OAAO,QAAQ,IACd,MAAM,SAAS,IAAI,OAAO,EAAE,SAAS;IACpC,MAAM,WAAW,MAAM,IAAI,mBAAmB,GAAG,KAAK;IACtD,IAAI,CAAC,SAAS,IACb,MAAM,IAAI,iBAAiB,OAAO,SAAS,MAAM;IAElD,OAAO,MAAM,IAAI,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;GAC9D,CAAC,CACF;EACD;EAEA,OAAO;GACN;GACA,MAAM,OAAO;IACZ,MAAM,WAAW,KAAK,IAAI,IAAI;IAC9B,SAAS;KACR,MAAM,CAAC,UAAU,MAAM,IAAI;KAC3B,IAAI,QAAQ,OAAO;KACnB,IAAI,KAAK,IAAI,KAAK,UAAU,MAAM,IAAI,OAAO,SAAS,OAAO;KAC7D,MAAM,IAAI,SAAS,YAAY,WAAW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cAA0C,MAAM;CAC/C,YAAY,OAAgB;EAC3B,MACC,qKAGA,EAAE,MAAM,CACT;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CAFV,YACC,OACA,QACC;EACD,MACC,cAAc,MAAM,YAAY,OAAO,kFAExC;EANS,KAAA,QAAA;EACA,KAAA,SAAA;EAMT,KAAK,OAAO;CACb;AACD"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ReceivedAttachment } from "@geekmidas/emailkit/inbound";
|
|
2
|
+
//#region src/mailbox.d.ts
|
|
3
|
+
export interface MailboxOptions {
|
|
4
|
+
/** Mailpit's HTTP address — what `gkm test` injects as `<ID>_INBOX_URL`. */
|
|
5
|
+
inbox: string;
|
|
6
|
+
/** The `fetch` to read it with. Defaults to the global one. */
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
/** How long `last()` waits for mail to arrive. */
|
|
9
|
+
timeout?: number;
|
|
10
|
+
}
|
|
11
|
+
/** One email, as it arrived. */
|
|
12
|
+
export interface Email {
|
|
13
|
+
id: string;
|
|
14
|
+
from: string;
|
|
15
|
+
to: string[];
|
|
16
|
+
subject: string;
|
|
17
|
+
text: string;
|
|
18
|
+
html: string;
|
|
19
|
+
/** Every header, by lower-case name, as the parser an inbox uses reads them. */
|
|
20
|
+
headers: Readonly<Record<string, readonly string[]>>;
|
|
21
|
+
/** Every `http(s)` link in the email, in order. */
|
|
22
|
+
links: string[];
|
|
23
|
+
/** The first link — the one a sign-in or confirmation email is about. */
|
|
24
|
+
link: string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Its files, read from the raw message by the parser an inbox's handler
|
|
27
|
+
* uses — so what survives one survives the other.
|
|
28
|
+
*/
|
|
29
|
+
attachments: ReceivedAttachment[];
|
|
30
|
+
}
|
|
31
|
+
export interface Mailbox {
|
|
32
|
+
/** The newest email to this address, waiting for one if none has arrived. */
|
|
33
|
+
last(): Promise<Email>;
|
|
34
|
+
/** Every email to this address, newest first. */
|
|
35
|
+
all(): Promise<Email[]>;
|
|
36
|
+
/** Delete every email to this address. */
|
|
37
|
+
clear(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** A way to read the mail sent to one address. */
|
|
40
|
+
export declare function createMailbox(options: MailboxOptions): (address: string) => Mailbox;
|
|
41
|
+
/** No email to an address arrived in time. */
|
|
42
|
+
export declare class NoMail extends Error {
|
|
43
|
+
readonly address: string;
|
|
44
|
+
readonly timeout: number;
|
|
45
|
+
constructor(address: string, timeout: number);
|
|
46
|
+
}
|
|
47
|
+
/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */
|
|
48
|
+
export declare class MailboxNeedsEmailkit extends Error {
|
|
49
|
+
constructor(cause: unknown);
|
|
50
|
+
}
|
|
51
|
+
/** Mailpit did not answer. */
|
|
52
|
+
export declare class InboxUnreachable extends Error {
|
|
53
|
+
readonly inbox: string;
|
|
54
|
+
readonly status: number;
|
|
55
|
+
constructor(inbox: string, status: number);
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//# sourceMappingURL=mailbox.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox.d.cts","names":[],"sources":["../src/mailbox.ts"],"mappings":";;iBAmBiB;;EAEhB;;EAEA,eAAe;;EAEf;;;iBAIgB;EAChB;EACA;EACA;EACA;EACA;EACA;;EAEA,SAAS,SAAS;;EAElB;;EAEA;;;;;EAKA,aAAa;;iBAGG;;EAEhB,QAAQ,QAAQ;;EAEhB,OAAO,QAAQ;;EAEf,SAAS;;;wBAIM,cACf,SAAS,kBACN,oBAAoB;;qBAmGX,eAAe;WAEjB;WACA;EAFV,YACU,iBACA;;;qBAWE,6BAA6B;EACzC,YAAY;;;qBAYA,yBAAyB;WAE3B;WACA;EAFV,YACU,eACA"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ReceivedAttachment } from "@geekmidas/emailkit/inbound";
|
|
2
|
+
//#region src/mailbox.d.ts
|
|
3
|
+
export interface MailboxOptions {
|
|
4
|
+
/** Mailpit's HTTP address — what `gkm test` injects as `<ID>_INBOX_URL`. */
|
|
5
|
+
inbox: string;
|
|
6
|
+
/** The `fetch` to read it with. Defaults to the global one. */
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
/** How long `last()` waits for mail to arrive. */
|
|
9
|
+
timeout?: number;
|
|
10
|
+
}
|
|
11
|
+
/** One email, as it arrived. */
|
|
12
|
+
export interface Email {
|
|
13
|
+
id: string;
|
|
14
|
+
from: string;
|
|
15
|
+
to: string[];
|
|
16
|
+
subject: string;
|
|
17
|
+
text: string;
|
|
18
|
+
html: string;
|
|
19
|
+
/** Every header, by lower-case name, as the parser an inbox uses reads them. */
|
|
20
|
+
headers: Readonly<Record<string, readonly string[]>>;
|
|
21
|
+
/** Every `http(s)` link in the email, in order. */
|
|
22
|
+
links: string[];
|
|
23
|
+
/** The first link — the one a sign-in or confirmation email is about. */
|
|
24
|
+
link: string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Its files, read from the raw message by the parser an inbox's handler
|
|
27
|
+
* uses — so what survives one survives the other.
|
|
28
|
+
*/
|
|
29
|
+
attachments: ReceivedAttachment[];
|
|
30
|
+
}
|
|
31
|
+
export interface Mailbox {
|
|
32
|
+
/** The newest email to this address, waiting for one if none has arrived. */
|
|
33
|
+
last(): Promise<Email>;
|
|
34
|
+
/** Every email to this address, newest first. */
|
|
35
|
+
all(): Promise<Email[]>;
|
|
36
|
+
/** Delete every email to this address. */
|
|
37
|
+
clear(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** A way to read the mail sent to one address. */
|
|
40
|
+
export declare function createMailbox(options: MailboxOptions): (address: string) => Mailbox;
|
|
41
|
+
/** No email to an address arrived in time. */
|
|
42
|
+
export declare class NoMail extends Error {
|
|
43
|
+
readonly address: string;
|
|
44
|
+
readonly timeout: number;
|
|
45
|
+
constructor(address: string, timeout: number);
|
|
46
|
+
}
|
|
47
|
+
/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */
|
|
48
|
+
export declare class MailboxNeedsEmailkit extends Error {
|
|
49
|
+
constructor(cause: unknown);
|
|
50
|
+
}
|
|
51
|
+
/** Mailpit did not answer. */
|
|
52
|
+
export declare class InboxUnreachable extends Error {
|
|
53
|
+
readonly inbox: string;
|
|
54
|
+
readonly status: number;
|
|
55
|
+
constructor(inbox: string, status: number);
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//# sourceMappingURL=mailbox.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox.d.mts","names":[],"sources":["../src/mailbox.ts"],"mappings":";;iBAmBiB;;EAEhB;;EAEA,eAAe;;EAEf;;;iBAIgB;EAChB;EACA;EACA;EACA;EACA;EACA;;EAEA,SAAS,SAAS;;EAElB;;EAEA;;;;;EAKA,aAAa;;iBAGG;;EAEhB,QAAQ,QAAQ;;EAEhB,OAAO,QAAQ;;EAEf,SAAS;;;wBAIM,cACf,SAAS,kBACN,oBAAoB;;qBAmGX,eAAe;WAEjB;WACA;EAFV,YACU,iBACA;;;qBAWE,6BAA6B;EACzC,YAAY;;;qBAYA,yBAAyB;WAE3B;WACA;EAFV,YACU,eACA"}
|
package/dist/mailbox.mjs
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//#region src/mailbox.ts
|
|
2
|
+
/** How long `last()` waits for mail that is still on its way. */
|
|
3
|
+
const DEFAULT_TIMEOUT = 5e3;
|
|
4
|
+
const POLL_INTERVAL = 50;
|
|
5
|
+
/** A way to read the mail sent to one address. */
|
|
6
|
+
function createMailbox(options) {
|
|
7
|
+
const inbox = options.inbox.replace(/\/$/, "");
|
|
8
|
+
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
9
|
+
const get = (path, init) => (options.fetch ?? globalThis.fetch)(`${inbox}${path}`, init);
|
|
10
|
+
return (address) => {
|
|
11
|
+
const query = `?query=${encodeURIComponent(`to:"${address}"`)}`;
|
|
12
|
+
const all = async () => {
|
|
13
|
+
const found = await json(await get(`/api/v1/search${query}`), inbox);
|
|
14
|
+
return Promise.all(found.messages.map(async ({ ID }) => {
|
|
15
|
+
const response = await get(`/api/v1/message/${ID}/raw`);
|
|
16
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
17
|
+
return email(ID, new Uint8Array(await response.arrayBuffer()));
|
|
18
|
+
}));
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
all,
|
|
22
|
+
async last() {
|
|
23
|
+
const deadline = Date.now() + timeout;
|
|
24
|
+
for (;;) {
|
|
25
|
+
const [newest] = await all();
|
|
26
|
+
if (newest) return newest;
|
|
27
|
+
if (Date.now() >= deadline) throw new NoMail(address, timeout);
|
|
28
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
async clear() {
|
|
32
|
+
const response = await get(`/api/v1/search${query}`, { method: "DELETE" });
|
|
33
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
async function json(response, inbox) {
|
|
39
|
+
if (!response.ok) throw new InboxUnreachable(inbox, response.status);
|
|
40
|
+
return await response.json();
|
|
41
|
+
}
|
|
42
|
+
/** The message, through the one MIME parser everything that reads mail uses. */
|
|
43
|
+
async function email(id, raw) {
|
|
44
|
+
let inbound;
|
|
45
|
+
try {
|
|
46
|
+
inbound = await import("@geekmidas/emailkit/inbound");
|
|
47
|
+
} catch (cause) {
|
|
48
|
+
throw new MailboxNeedsEmailkit(cause);
|
|
49
|
+
}
|
|
50
|
+
const message = await inbound.parseEmail(raw);
|
|
51
|
+
const html = message.html ?? "";
|
|
52
|
+
const text = message.text ?? "";
|
|
53
|
+
const links = [...new Set([...html.matchAll(/href="(https?:\/\/[^"]+)"/g), ...text.matchAll(/(https?:\/\/[^\s<>"]+)/g)].map(([, url]) => decodeEntities(url)))];
|
|
54
|
+
return {
|
|
55
|
+
id,
|
|
56
|
+
from: message.from?.address ?? "",
|
|
57
|
+
to: message.to.map(({ address }) => address),
|
|
58
|
+
subject: message.subject ?? "",
|
|
59
|
+
text,
|
|
60
|
+
html,
|
|
61
|
+
headers: message.headers,
|
|
62
|
+
links,
|
|
63
|
+
link: links[0],
|
|
64
|
+
attachments: message.attachments
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** `&` in an HTML attribute is `&` in the URL it names. */
|
|
68
|
+
function decodeEntities(url) {
|
|
69
|
+
return url.replaceAll("&", "&");
|
|
70
|
+
}
|
|
71
|
+
/** No email to an address arrived in time. */
|
|
72
|
+
var NoMail = class extends Error {
|
|
73
|
+
address;
|
|
74
|
+
timeout;
|
|
75
|
+
constructor(address, timeout) {
|
|
76
|
+
super(`No email to ${address} arrived within ${timeout}ms. Check that the code under test sends it, and to that address.`);
|
|
77
|
+
this.address = address;
|
|
78
|
+
this.timeout = timeout;
|
|
79
|
+
this.name = "NoMail";
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */
|
|
83
|
+
var MailboxNeedsEmailkit = class extends Error {
|
|
84
|
+
constructor(cause) {
|
|
85
|
+
super("Reading mail from the mailbox parses it with @geekmidas/emailkit, which could not be loaded. Add it to the dev dependencies of the app whose mail the test reads.", { cause });
|
|
86
|
+
this.name = "MailboxNeedsEmailkit";
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/** Mailpit did not answer. */
|
|
90
|
+
var InboxUnreachable = class extends Error {
|
|
91
|
+
inbox;
|
|
92
|
+
status;
|
|
93
|
+
constructor(inbox, status) {
|
|
94
|
+
super(`Mailpit at ${inbox} answered ${status}. Is it running? \`gkm test\` starts it when the app declares an Email construct.`);
|
|
95
|
+
this.inbox = inbox;
|
|
96
|
+
this.status = status;
|
|
97
|
+
this.name = "InboxUnreachable";
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
//#endregion
|
|
101
|
+
export { InboxUnreachable, MailboxNeedsEmailkit, NoMail, createMailbox };
|
|
102
|
+
|
|
103
|
+
//# sourceMappingURL=mailbox.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox.mjs","names":[],"sources":["../src/mailbox.ts"],"sourcesContent":["/**\n * The mail a test sent, read from Mailpit.\n *\n * Locally, mail goes over real SMTP to Mailpit — the same client, the same\n * message, only the host differs. A test reads what arrived through Mailpit's\n * HTTP API, so a magic link is signed in with by opening the email that was\n * actually sent rather than a token pulled from somewhere else.\n *\n * Mailpit has one inbox for everything, and transactions do not reach it, so a\n * test keeps to its own mail by address: a unique recipient per test, read by\n * `to:`, and cleared afterwards.\n */\n\nimport type { ReceivedAttachment } from '@geekmidas/emailkit/inbound';\n\n/** How long `last()` waits for mail that is still on its way. */\nconst DEFAULT_TIMEOUT = 5_000;\nconst POLL_INTERVAL = 50;\n\nexport interface MailboxOptions {\n\t/** Mailpit's HTTP address — what `gkm test` injects as `<ID>_INBOX_URL`. */\n\tinbox: string;\n\t/** The `fetch` to read it with. Defaults to the global one. */\n\tfetch?: typeof fetch;\n\t/** How long `last()` waits for mail to arrive. */\n\ttimeout?: number;\n}\n\n/** One email, as it arrived. */\nexport interface Email {\n\tid: string;\n\tfrom: string;\n\tto: string[];\n\tsubject: string;\n\ttext: string;\n\thtml: string;\n\t/** Every header, by lower-case name, as the parser an inbox uses reads them. */\n\theaders: Readonly<Record<string, readonly string[]>>;\n\t/** Every `http(s)` link in the email, in order. */\n\tlinks: string[];\n\t/** The first link — the one a sign-in or confirmation email is about. */\n\tlink: string | undefined;\n\t/**\n\t * Its files, read from the raw message by the parser an inbox's handler\n\t * uses — so what survives one survives the other.\n\t */\n\tattachments: ReceivedAttachment[];\n}\n\nexport interface Mailbox {\n\t/** The newest email to this address, waiting for one if none has arrived. */\n\tlast(): Promise<Email>;\n\t/** Every email to this address, newest first. */\n\tall(): Promise<Email[]>;\n\t/** Delete every email to this address. */\n\tclear(): Promise<void>;\n}\n\n/** A way to read the mail sent to one address. */\nexport function createMailbox(\n\toptions: MailboxOptions,\n): (address: string) => Mailbox {\n\tconst inbox = options.inbox.replace(/\\/$/, '');\n\tconst timeout = options.timeout ?? DEFAULT_TIMEOUT;\n\tconst get = (path: string, init?: RequestInit) =>\n\t\t(options.fetch ?? globalThis.fetch)(`${inbox}${path}`, init);\n\n\treturn (address) => {\n\t\tconst query = `?query=${encodeURIComponent(`to:\"${address}\"`)}`;\n\n\t\tconst all = async (): Promise<Email[]> => {\n\t\t\tconst found = await json<SearchResult>(\n\t\t\t\tawait get(`/api/v1/search${query}`),\n\t\t\t\tinbox,\n\t\t\t);\n\t\t\treturn Promise.all(\n\t\t\t\tfound.messages.map(async ({ ID }) => {\n\t\t\t\t\tconst response = await get(`/api/v1/message/${ID}/raw`);\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\tthrow new InboxUnreachable(inbox, response.status);\n\t\t\t\t\t}\n\t\t\t\t\treturn email(ID, new Uint8Array(await response.arrayBuffer()));\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\n\t\treturn {\n\t\t\tall,\n\t\t\tasync last() {\n\t\t\t\tconst deadline = Date.now() + timeout;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst [newest] = await all();\n\t\t\t\t\tif (newest) return newest;\n\t\t\t\t\tif (Date.now() >= deadline) throw new NoMail(address, timeout);\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync clear() {\n\t\t\t\tconst response = await get(`/api/v1/search${query}`, {\n\t\t\t\t\tmethod: 'DELETE',\n\t\t\t\t});\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new InboxUnreachable(inbox, response.status);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t};\n}\n\ninterface SearchResult {\n\tmessages: { ID: string }[];\n}\n\nasync function json<T>(response: Response, inbox: string): Promise<T> {\n\tif (!response.ok) throw new InboxUnreachable(inbox, response.status);\n\treturn (await response.json()) as T;\n}\n\n/** The message, through the one MIME parser everything that reads mail uses. */\nasync function email(id: string, raw: Uint8Array): Promise<Email> {\n\t// emailkit is an optional peer: loaded when mail is read, inside a `try`\n\t// so a bundled test harness for an app that sends none leaves it alone.\n\tlet inbound: typeof import('@geekmidas/emailkit/inbound');\n\ttry {\n\t\tinbound = await import('@geekmidas/emailkit/inbound');\n\t} catch (cause) {\n\t\tthrow new MailboxNeedsEmailkit(cause);\n\t}\n\tconst message = await inbound.parseEmail(raw);\n\tconst html = message.html ?? '';\n\tconst text = message.text ?? '';\n\tconst links = [\n\t\t...new Set(\n\t\t\t[\n\t\t\t\t...html.matchAll(/href=\"(https?:\\/\\/[^\"]+)\"/g),\n\t\t\t\t...text.matchAll(/(https?:\\/\\/[^\\s<>\"]+)/g),\n\t\t\t].map(([, url]) => decodeEntities(url!)),\n\t\t),\n\t];\n\n\treturn {\n\t\tid,\n\t\tfrom: message.from?.address ?? '',\n\t\tto: message.to.map(({ address }) => address),\n\t\tsubject: message.subject ?? '',\n\t\ttext,\n\t\thtml,\n\t\theaders: message.headers,\n\t\tlinks,\n\t\tlink: links[0],\n\t\tattachments: message.attachments,\n\t};\n}\n\n/** `&` in an HTML attribute is `&` in the URL it names. */\nfunction decodeEntities(url: string): string {\n\treturn url.replaceAll('&', '&');\n}\n\n/** No email to an address arrived in time. */\nexport class NoMail extends Error {\n\tconstructor(\n\t\treadonly address: string,\n\t\treadonly timeout: number,\n\t) {\n\t\tsuper(\n\t\t\t`No email to ${address} arrived within ${timeout}ms. Check that the ` +\n\t\t\t\t`code under test sends it, and to that address.`,\n\t\t);\n\t\tthis.name = 'NoMail';\n\t}\n}\n\n/** Reading mail needs `@geekmidas/emailkit`, and it is not installed. */\nexport class MailboxNeedsEmailkit extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(\n\t\t\t'Reading mail from the mailbox parses it with @geekmidas/emailkit, ' +\n\t\t\t\t'which could not be loaded. Add it to the dev dependencies of the ' +\n\t\t\t\t'app whose mail the test reads.',\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'MailboxNeedsEmailkit';\n\t}\n}\n\n/** Mailpit did not answer. */\nexport class InboxUnreachable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`Mailpit at ${inbox} answered ${status}. Is it running? \\`gkm test\\` ` +\n\t\t\t\t`starts it when the app declares an Email construct.`,\n\t\t);\n\t\tthis.name = 'InboxUnreachable';\n\t}\n}\n"],"mappings":";;AAgBA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;;AA0CtB,SAAgB,cACf,SAC+B;CAC/B,MAAM,QAAQ,QAAQ,MAAM,QAAQ,OAAO,EAAE;CAC7C,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,OAAO,MAAc,UACzB,QAAQ,SAAS,WAAW,MAAA,CAAO,GAAG,QAAQ,QAAQ,IAAI;CAE5D,QAAQ,YAAY;EACnB,MAAM,QAAQ,UAAU,mBAAmB,OAAO,QAAQ,EAAE;EAE5D,MAAM,MAAM,YAA8B;GACzC,MAAM,QAAQ,MAAM,KACnB,MAAM,IAAI,iBAAiB,OAAO,GAClC,KACD;GACA,OAAO,QAAQ,IACd,MAAM,SAAS,IAAI,OAAO,EAAE,SAAS;IACpC,MAAM,WAAW,MAAM,IAAI,mBAAmB,GAAG,KAAK;IACtD,IAAI,CAAC,SAAS,IACb,MAAM,IAAI,iBAAiB,OAAO,SAAS,MAAM;IAElD,OAAO,MAAM,IAAI,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC,CAAC;GAC9D,CAAC,CACF;EACD;EAEA,OAAO;GACN;GACA,MAAM,OAAO;IACZ,MAAM,WAAW,KAAK,IAAI,IAAI;IAC9B,SAAS;KACR,MAAM,CAAC,UAAU,MAAM,IAAI;KAC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D,MACC,eAAe,QAAQ,kBAAkB,QAAQ,kEAElD;EANS,KAAA,UAAA;EACA,KAAA,UAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,uBAAb,cAA0C,MAAM;CAC/C,YAAY,OAAgB;EAC3B,MACC,qKAGA,EAAE,MAAM,CACT;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CAFV,YACC,OACA,QACC;EACD,MACC,cAAc,MAAM,YAAY,OAAO,kFAExC;EANS,KAAA,QAAA;EACA,KAAA,SAAA;EAMT,KAAK,OAAO;CACb;AACD"}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
|
|
3
|
+
let pg = require("pg");
|
|
4
|
+
pg = require_rolldown_runtime.__toESM(pg, 1);
|
|
5
|
+
let kysely = require("kysely");
|
|
6
|
+
//#region src/transactions.ts
|
|
7
|
+
/**
|
|
8
|
+
* A transaction per database, per test — as each runs deployed.
|
|
9
|
+
*
|
|
10
|
+
* An app's database and a schema tenant such as the auth server's are separate
|
|
11
|
+
* databases to the code using them: separate connections, credentials, roles
|
|
12
|
+
* and search paths. A test keeps them that way. Each gets its own connection,
|
|
13
|
+
* opened into a transaction the first time the test touches it, and every one
|
|
14
|
+
* is rolled back when the test ends.
|
|
15
|
+
*
|
|
16
|
+
* Code under test must be free to use transactions itself, and better-auth
|
|
17
|
+
* does — it also calls `db.connection()`, which Kysely refuses on a
|
|
18
|
+
* `Transaction`. So what a test hands over is not a `Transaction` but a Kysely
|
|
19
|
+
* over the one connection already inside the test's transaction, on which a
|
|
20
|
+
* `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does
|
|
21
|
+
* can end the transaction the test will roll back.
|
|
22
|
+
*
|
|
23
|
+
* A statement the code runs outside a transaction of its own gets a savepoint
|
|
24
|
+
* too, so a failure — a duplicate key two concurrent requests raced to insert —
|
|
25
|
+
* fails that statement alone, as it would deployed, rather than every request
|
|
26
|
+
* the test makes after it.
|
|
27
|
+
*
|
|
28
|
+
* A savepoint the test or the code opens by name — `savepoint refused`, a
|
|
29
|
+
* statement expected to fail, `rollback to savepoint refused` — is its own
|
|
30
|
+
* transaction control, and passes through untouched. While one is open,
|
|
31
|
+
* statements run in it as they would inside a `begin`: unwrapped, so a failure
|
|
32
|
+
* aborts the transaction until the matching `rollback to savepoint`.
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* The connection settings for a database URL.
|
|
36
|
+
*
|
|
37
|
+
* `?search_path=` is not a libpq parameter: a URL carrying it connects and then
|
|
38
|
+
* resolves every name against `public`. Postgres takes it as a startup option,
|
|
39
|
+
* which is what a schema tenant's URL needs to reach its own tables.
|
|
40
|
+
*/
|
|
41
|
+
function connectionConfig(url) {
|
|
42
|
+
const parsed = new URL(url);
|
|
43
|
+
const searchPath = parsed.searchParams.get("search_path");
|
|
44
|
+
if (!searchPath) return { connectionString: url };
|
|
45
|
+
parsed.searchParams.delete("search_path");
|
|
46
|
+
return {
|
|
47
|
+
connectionString: parsed.toString(),
|
|
48
|
+
options: `-c search_path=${searchPath}`
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Open a connection to `url` and begin the transaction a test will roll back.
|
|
53
|
+
*
|
|
54
|
+
* `config` is what the database's own clients are built with — its plugins
|
|
55
|
+
* above all. The code under test is handed this Kysely in place of its own, so
|
|
56
|
+
* one built without them runs different queries than production does.
|
|
57
|
+
*/
|
|
58
|
+
async function openBoundTransaction(url, config = {}) {
|
|
59
|
+
const client = new pg.default.Client(connectionConfig(url));
|
|
60
|
+
await client.connect();
|
|
61
|
+
await client.query("BEGIN");
|
|
62
|
+
const inTurn = turns();
|
|
63
|
+
const named = [];
|
|
64
|
+
return {
|
|
65
|
+
db: new kysely.Kysely({
|
|
66
|
+
...config,
|
|
67
|
+
dialect: new kysely.PostgresDialect({ pool: {
|
|
68
|
+
connect: async () => savepointing(client, inTurn, named),
|
|
69
|
+
end: async () => {}
|
|
70
|
+
} })
|
|
71
|
+
}),
|
|
72
|
+
async rollback() {
|
|
73
|
+
try {
|
|
74
|
+
await client.query("ROLLBACK");
|
|
75
|
+
} finally {
|
|
76
|
+
await client.end();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The client, with transaction control turned into savepoints.
|
|
83
|
+
*
|
|
84
|
+
* Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the
|
|
85
|
+
* one place they can be caught. A depth counter names the savepoints, so
|
|
86
|
+
* nested transactions nest.
|
|
87
|
+
*/
|
|
88
|
+
function savepointing(client, inTurn, named) {
|
|
89
|
+
let depth = 0;
|
|
90
|
+
const query = client.query.bind(client);
|
|
91
|
+
const wrapped = Object.create(client);
|
|
92
|
+
const closeTransaction = (level) => {
|
|
93
|
+
for (let i = named.length - 1; i >= 0; i--) {
|
|
94
|
+
const savepoint = named[i];
|
|
95
|
+
if (savepoint.checkout === wrapped && savepoint.depth >= level) named.splice(i, 1);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
Object.assign(wrapped, {
|
|
99
|
+
query: (text, ...rest) => {
|
|
100
|
+
if (typeof text !== "string" || typeof rest.at(-1) === "function") return query(text, ...rest);
|
|
101
|
+
const statement = text.trim().toLowerCase();
|
|
102
|
+
if (statement === "begin" || statement.startsWith("start transaction")) {
|
|
103
|
+
const savepoint = `test_sp_${++depth}`;
|
|
104
|
+
return inTurn(() => query(`SAVEPOINT ${savepoint}`));
|
|
105
|
+
}
|
|
106
|
+
if (statement === "commit") {
|
|
107
|
+
const level = depth--;
|
|
108
|
+
closeTransaction(level);
|
|
109
|
+
return inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));
|
|
110
|
+
}
|
|
111
|
+
if (statement === "rollback") {
|
|
112
|
+
const level = depth--;
|
|
113
|
+
closeTransaction(level);
|
|
114
|
+
return inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));
|
|
115
|
+
}
|
|
116
|
+
const control = savepointControl(text);
|
|
117
|
+
if (control) return inTurn(async () => {
|
|
118
|
+
const result = await query(text, ...rest);
|
|
119
|
+
track(named, control, {
|
|
120
|
+
checkout: wrapped,
|
|
121
|
+
depth
|
|
122
|
+
});
|
|
123
|
+
return result;
|
|
124
|
+
});
|
|
125
|
+
if (depth > 0 || named.length > 0) return inTurn(() => query(text, ...rest));
|
|
126
|
+
return inTurn(() => autocommitted(query, text, rest));
|
|
127
|
+
},
|
|
128
|
+
release: () => {}
|
|
129
|
+
});
|
|
130
|
+
return wrapped;
|
|
131
|
+
}
|
|
132
|
+
const IDENTIFIER = String.raw`("(?:[^"]|"")+"|[^\s;"]+)`;
|
|
133
|
+
const SAVEPOINT_CONTROL = [
|
|
134
|
+
["savepoint", new RegExp(String.raw`^savepoint\s+${IDENTIFIER}\s*;?$`, "i")],
|
|
135
|
+
["release", new RegExp(String.raw`^release\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")],
|
|
136
|
+
["rollback to", new RegExp(String.raw`^rollback\s+(?:(?:work|transaction)\s+)?to\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")]
|
|
137
|
+
];
|
|
138
|
+
/**
|
|
139
|
+
* The savepoint a statement opens, releases or rolls back to, named as
|
|
140
|
+
* Postgres names it: an unquoted name folded to lower case, a quoted one as
|
|
141
|
+
* written.
|
|
142
|
+
*/
|
|
143
|
+
function savepointControl(text) {
|
|
144
|
+
const statement = text.trim();
|
|
145
|
+
for (const [action, pattern] of SAVEPOINT_CONTROL) {
|
|
146
|
+
const match = pattern.exec(statement);
|
|
147
|
+
if (!match) continue;
|
|
148
|
+
const identifier = match[1];
|
|
149
|
+
return {
|
|
150
|
+
action,
|
|
151
|
+
name: identifier.startsWith("\"") ? identifier.slice(1, -1).replaceAll("\"\"", "\"") : identifier.toLowerCase()
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Keep the named savepoints as Postgres does: `RELEASE x` ends x and every
|
|
157
|
+
* savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.
|
|
158
|
+
*/
|
|
159
|
+
function track(named, control, at) {
|
|
160
|
+
if (control.action === "savepoint") {
|
|
161
|
+
named.push({
|
|
162
|
+
name: control.name,
|
|
163
|
+
...at
|
|
164
|
+
});
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const index = named.findLastIndex((s) => s.name === control.name);
|
|
168
|
+
if (index === -1) return;
|
|
169
|
+
named.splice(control.action === "release" ? index : index + 1);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* One statement at a time on a connection, in the order they were asked for.
|
|
173
|
+
*
|
|
174
|
+
* The connection runs them one at a time anyway; this keeps a statement and
|
|
175
|
+
* the savepoint around it together, so nothing another request sends lands
|
|
176
|
+
* between them — a `RELEASE` also ends every savepoint opened after its own.
|
|
177
|
+
*/
|
|
178
|
+
function turns() {
|
|
179
|
+
let queue = Promise.resolve();
|
|
180
|
+
return (work) => {
|
|
181
|
+
const turn = queue.then(work, work);
|
|
182
|
+
queue = turn.catch(() => {});
|
|
183
|
+
return turn;
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* A statement run outside any transaction the code opened, failing the way
|
|
188
|
+
* it would deployed: on its own.
|
|
189
|
+
*
|
|
190
|
+
* Deployed, such a statement is its own transaction, so one that fails — a
|
|
191
|
+
* duplicate key two concurrent requests both tried to insert — fails alone,
|
|
192
|
+
* and code written for that (Better Auth's rate limiter reads the row the
|
|
193
|
+
* other request inserted, and carries on) does carry on. Inside the test's
|
|
194
|
+
* transaction a failed statement would abort everything after it, every
|
|
195
|
+
* request of the test included. A savepoint around it puts back what
|
|
196
|
+
* deployed would have.
|
|
197
|
+
*/
|
|
198
|
+
async function autocommitted(query, text, rest) {
|
|
199
|
+
await query("SAVEPOINT test_statement");
|
|
200
|
+
try {
|
|
201
|
+
const result = await query(text, ...rest);
|
|
202
|
+
await query("RELEASE SAVEPOINT test_statement");
|
|
203
|
+
return result;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
await query("ROLLBACK TO SAVEPOINT test_statement");
|
|
206
|
+
await query("RELEASE SAVEPOINT test_statement");
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The transactions one test has opened, by database.
|
|
212
|
+
*
|
|
213
|
+
* `get` opens a database's transaction the first time it is asked for and
|
|
214
|
+
* hands back the same one after that — including to a caller that asks while
|
|
215
|
+
* it is still opening. `rollbackAll` ends every one of them.
|
|
216
|
+
*/
|
|
217
|
+
var TransactionRegistry = class {
|
|
218
|
+
open = /* @__PURE__ */ new Map();
|
|
219
|
+
get(key, url, config) {
|
|
220
|
+
let transaction = this.open.get(key);
|
|
221
|
+
if (!transaction) {
|
|
222
|
+
transaction = openBoundTransaction(url, config);
|
|
223
|
+
this.open.set(key, transaction);
|
|
224
|
+
}
|
|
225
|
+
return transaction.then(({ db }) => db);
|
|
226
|
+
}
|
|
227
|
+
async rollbackAll() {
|
|
228
|
+
const transactions = [...this.open.values()];
|
|
229
|
+
this.open.clear();
|
|
230
|
+
const failed = (await Promise.allSettled(transactions.map(async (transaction) => (await transaction).rollback()))).find((result) => result.status === "rejected");
|
|
231
|
+
if (failed) throw failed.reason;
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
//#endregion
|
|
235
|
+
exports.TransactionRegistry = TransactionRegistry;
|
|
236
|
+
exports.connectionConfig = connectionConfig;
|
|
237
|
+
exports.openBoundTransaction = openBoundTransaction;
|
|
238
|
+
|
|
239
|
+
//# sourceMappingURL=transactions.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transactions.cjs","names":["Kysely","PostgresDialect"],"sources":["../src/transactions.ts"],"sourcesContent":["/**\n * A transaction per database, per test — as each runs deployed.\n *\n * An app's database and a schema tenant such as the auth server's are separate\n * databases to the code using them: separate connections, credentials, roles\n * and search paths. A test keeps them that way. Each gets its own connection,\n * opened into a transaction the first time the test touches it, and every one\n * is rolled back when the test ends.\n *\n * Code under test must be free to use transactions itself, and better-auth\n * does — it also calls `db.connection()`, which Kysely refuses on a\n * `Transaction`. So what a test hands over is not a `Transaction` but a Kysely\n * over the one connection already inside the test's transaction, on which a\n * `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does\n * can end the transaction the test will roll back.\n *\n * A statement the code runs outside a transaction of its own gets a savepoint\n * too, so a failure — a duplicate key two concurrent requests raced to insert —\n * fails that statement alone, as it would deployed, rather than every request\n * the test makes after it.\n *\n * A savepoint the test or the code opens by name — `savepoint refused`, a\n * statement expected to fail, `rollback to savepoint refused` — is its own\n * transaction control, and passes through untouched. While one is open,\n * statements run in it as they would inside a `begin`: unwrapped, so a failure\n * aborts the transaction until the matching `rollback to savepoint`.\n */\n\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport pg from 'pg';\n\n/** How to reach one database: a URL, and its search path as a startup option. */\nexport interface ConnectionConfig {\n\tconnectionString: string;\n\toptions?: string;\n}\n\n/**\n * The connection settings for a database URL.\n *\n * `?search_path=` is not a libpq parameter: a URL carrying it connects and then\n * resolves every name against `public`. Postgres takes it as a startup option,\n * which is what a schema tenant's URL needs to reach its own tables.\n */\nexport function connectionConfig(url: string): ConnectionConfig {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tif (!searchPath) return { connectionString: url };\n\n\tparsed.searchParams.delete('search_path');\n\treturn {\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\n\t};\n}\n\n/** One database's connection, inside a transaction the test will roll back. */\nexport interface BoundTransaction {\n\t/** Everything queried through this runs inside the test's transaction. */\n\treadonly db: Kysely<any>;\n\t/** Undo everything, and let the connection go. */\n\trollback(): Promise<void>;\n}\n\n/**\n * Open a connection to `url` and begin the transaction a test will roll back.\n *\n * `config` is what the database's own clients are built with — its plugins\n * above all. The code under test is handed this Kysely in place of its own, so\n * one built without them runs different queries than production does.\n */\nexport async function openBoundTransaction(\n\turl: string,\n\tconfig: Omit<KyselyConfig, 'dialect'> = {},\n): Promise<BoundTransaction> {\n\tconst client = new pg.Client(connectionConfig(url));\n\tawait client.connect();\n\tawait client.query('BEGIN');\n\t// Shared by every checkout of the connection: concurrent requests in one\n\t// test each check it out, and all of them take turns on it.\n\tconst inTurn = turns();\n\t// The savepoints opened by name, shared by every checkout as the\n\t// connection's transaction is.\n\tconst named: NamedSavepoint[] = [];\n\n\treturn {\n\t\tdb: new Kysely({\n\t\t\t...config,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\t// A \"pool\" of the one connection. Released never, ended never: the\n\t\t\t\t// test owns it, and it closes in `rollback`.\n\t\t\t\tpool: {\n\t\t\t\t\tconnect: async () => savepointing(client, inTurn, named),\n\t\t\t\t\tend: async () => {},\n\t\t\t\t} as unknown as pg.Pool,\n\t\t\t}),\n\t\t}),\n\t\tasync rollback() {\n\t\t\ttry {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The client, with transaction control turned into savepoints.\n *\n * Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the\n * one place they can be caught. A depth counter names the savepoints, so\n * nested transactions nest.\n */\nfunction savepointing(\n\tclient: pg.Client,\n\tinTurn: Turns,\n\tnamed: NamedSavepoint[],\n): pg.PoolClient {\n\tlet depth = 0;\n\tconst query = client.query.bind(client) as (\n\t\t...args: unknown[]\n\t) => Promise<unknown>;\n\tconst wrapped = Object.create(client) as pg.PoolClient;\n\n\t// Ending one of the code's transactions ends every savepoint opened in it.\n\tconst closeTransaction = (level: number) => {\n\t\tfor (let i = named.length - 1; i >= 0; i--) {\n\t\t\tconst savepoint = named[i]!;\n\t\t\tif (savepoint.checkout === wrapped && savepoint.depth >= level) {\n\t\t\t\tnamed.splice(i, 1);\n\t\t\t}\n\t\t}\n\t};\n\n\tObject.assign(wrapped, {\n\t\tquery: (text: unknown, ...rest: unknown[]) => {\n\t\t\t// A cursor, a query config, a callback: not what Kysely sends for a\n\t\t\t// statement, and nothing to wrap.\n\t\t\tif (typeof text !== 'string' || typeof rest.at(-1) === 'function') {\n\t\t\t\treturn query(text, ...rest);\n\t\t\t}\n\t\t\tconst statement = text.trim().toLowerCase();\n\n\t\t\tif (statement === 'begin' || statement.startsWith('start transaction')) {\n\t\t\t\tconst savepoint = `test_sp_${++depth}`;\n\t\t\t\treturn inTurn(() => query(`SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'commit') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\t\t\tif (statement === 'rollback') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\n\t\t\tconst control = savepointControl(text);\n\t\t\tif (control) {\n\t\t\t\treturn inTurn(async () => {\n\t\t\t\t\tconst result = await query(text, ...rest);\n\t\t\t\t\ttrack(named, control, { checkout: wrapped, depth });\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (depth > 0 || named.length > 0) {\n\t\t\t\treturn inTurn(() => query(text, ...rest));\n\t\t\t}\n\t\t\treturn inTurn(() => autocommitted(query, text, rest));\n\t\t},\n\t\trelease: () => {},\n\t});\n\treturn wrapped;\n}\n\n/** A savepoint the test or the code opened by name, and where it opened it. */\ninterface NamedSavepoint {\n\tname: string;\n\t/** The checkout, and its transaction depth, the savepoint was opened at. */\n\tcheckout: pg.PoolClient;\n\tdepth: number;\n}\n\n/** `SAVEPOINT x`, `RELEASE [SAVEPOINT] x`, `ROLLBACK [WORK] TO [SAVEPOINT] x`. */\ninterface SavepointControl {\n\taction: 'savepoint' | 'release' | 'rollback to';\n\tname: string;\n}\n\nconst IDENTIFIER = String.raw`(\"(?:[^\"]|\"\")+\"|[^\\s;\"]+)`;\nconst SAVEPOINT_CONTROL: [SavepointControl['action'], RegExp][] = [\n\t['savepoint', new RegExp(String.raw`^savepoint\\s+${IDENTIFIER}\\s*;?$`, 'i')],\n\t[\n\t\t'release',\n\t\tnew RegExp(\n\t\t\tString.raw`^release\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n\t[\n\t\t'rollback to',\n\t\tnew RegExp(\n\t\t\tString.raw`^rollback\\s+(?:(?:work|transaction)\\s+)?to\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n];\n\n/**\n * The savepoint a statement opens, releases or rolls back to, named as\n * Postgres names it: an unquoted name folded to lower case, a quoted one as\n * written.\n */\nfunction savepointControl(text: string): SavepointControl | undefined {\n\tconst statement = text.trim();\n\tfor (const [action, pattern] of SAVEPOINT_CONTROL) {\n\t\tconst match = pattern.exec(statement);\n\t\tif (!match) continue;\n\t\tconst identifier = match[1]!;\n\t\tconst name = identifier.startsWith('\"')\n\t\t\t? identifier.slice(1, -1).replaceAll('\"\"', '\"')\n\t\t\t: identifier.toLowerCase();\n\t\treturn { action, name };\n\t}\n\treturn undefined;\n}\n\n/**\n * Keep the named savepoints as Postgres does: `RELEASE x` ends x and every\n * savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.\n */\nfunction track(\n\tnamed: NamedSavepoint[],\n\tcontrol: SavepointControl,\n\tat: Omit<NamedSavepoint, 'name'>,\n): void {\n\tif (control.action === 'savepoint') {\n\t\tnamed.push({ name: control.name, ...at });\n\t\treturn;\n\t}\n\tconst index = named.findLastIndex((s) => s.name === control.name);\n\t// One opened before this connection was handed over, or by a name the\n\t// wrapper uses itself: nothing tracked to end.\n\tif (index === -1) return;\n\tnamed.splice(control.action === 'release' ? index : index + 1);\n}\n\n/** Runs work in the order it was asked for, each after the last has settled. */\ntype Turns = <T>(work: () => Promise<T>) => Promise<T>;\n\n/**\n * One statement at a time on a connection, in the order they were asked for.\n *\n * The connection runs them one at a time anyway; this keeps a statement and\n * the savepoint around it together, so nothing another request sends lands\n * between them — a `RELEASE` also ends every savepoint opened after its own.\n */\nfunction turns(): Turns {\n\tlet queue: Promise<unknown> = Promise.resolve();\n\treturn (work) => {\n\t\tconst turn = queue.then(work, work);\n\t\tqueue = turn.catch(() => {});\n\t\treturn turn;\n\t};\n}\n\n/**\n * A statement run outside any transaction the code opened, failing the way\n * it would deployed: on its own.\n *\n * Deployed, such a statement is its own transaction, so one that fails — a\n * duplicate key two concurrent requests both tried to insert — fails alone,\n * and code written for that (Better Auth's rate limiter reads the row the\n * other request inserted, and carries on) does carry on. Inside the test's\n * transaction a failed statement would abort everything after it, every\n * request of the test included. A savepoint around it puts back what\n * deployed would have.\n */\nasync function autocommitted(\n\tquery: (...args: unknown[]) => Promise<unknown>,\n\ttext: string,\n\trest: unknown[],\n): Promise<unknown> {\n\tawait query('SAVEPOINT test_statement');\n\ttry {\n\t\tconst result = await query(text, ...rest);\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\treturn result;\n\t} catch (error) {\n\t\tawait query('ROLLBACK TO SAVEPOINT test_statement');\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\tthrow error;\n\t}\n}\n\n/**\n * The transactions one test has opened, by database.\n *\n * `get` opens a database's transaction the first time it is asked for and\n * hands back the same one after that — including to a caller that asks while\n * it is still opening. `rollbackAll` ends every one of them.\n */\nexport class TransactionRegistry<TKey = string> {\n\tprivate readonly open = new Map<TKey, Promise<BoundTransaction>>();\n\n\tget(\n\t\tkey: TKey,\n\t\turl: string,\n\t\tconfig?: Omit<KyselyConfig, 'dialect'>,\n\t): Promise<Kysely<any>> {\n\t\tlet transaction = this.open.get(key);\n\t\tif (!transaction) {\n\t\t\ttransaction = openBoundTransaction(url, config);\n\t\t\tthis.open.set(key, transaction);\n\t\t}\n\t\treturn transaction.then(({ db }) => db);\n\t}\n\n\tasync rollbackAll(): Promise<void> {\n\t\tconst transactions = [...this.open.values()];\n\t\tthis.open.clear();\n\n\t\tconst results = await Promise.allSettled(\n\t\t\ttransactions.map(async (transaction) => (await transaction).rollback()),\n\t\t);\n\t\tconst failed = results.find(\n\t\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t\t);\n\t\tif (failed) throw failed.reason;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,iBAAiB,KAA+B;CAC/D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,IAAI,CAAC,YAAY,OAAO,EAAE,kBAAkB,IAAI;CAEhD,OAAO,aAAa,OAAO,aAAa;CACxC,OAAO;EACN,kBAAkB,OAAO,SAAS;EAClC,SAAS,kBAAkB;CAC5B;AACD;;;;;;;;AAiBA,eAAsB,qBACrB,KACA,SAAwC,CAAC,GACb;CAC5B,MAAM,SAAS,IAAI,GAAA,QAAG,OAAO,iBAAiB,GAAG,CAAC;CAClD,MAAM,OAAO,QAAQ;CACrB,MAAM,OAAO,MAAM,OAAO;CAG1B,MAAM,SAAS,MAAM;CAGrB,MAAM,QAA0B,CAAC;CAEjC,OAAO;EACN,IAAI,IAAIA,OAAAA,OAAO;GACd,GAAG;GACH,SAAS,IAAIC,OAAAA,gBAAgB,EAG5B,MAAM;IACL,SAAS,YAAY,aAAa,QAAQ,QAAQ,KAAK;IACvD,KAAK,YAAY,CAAC;GACnB,EACD,CAAC;EACF,CAAC;EACD,MAAM,WAAW;GAChB,IAAI;IACH,MAAM,OAAO,MAAM,UAAU;GAC9B,UAAU;IACT,MAAM,OA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