@webiny/api-storage-pg 0.0.0-stage β†’ 0.0.0-unstable.292eb6dc15

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @webiny/api-storage-pg
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ πŸ“˜ **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,22 @@
1
+ export interface PgConnectionStringValues {
2
+ host?: string;
3
+ port?: number | string;
4
+ user?: string;
5
+ password?: string;
6
+ database?: string;
7
+ }
8
+ /**
9
+ * Writes connection settings into a Postgres connection string, so they win over it. node-postgres
10
+ * reads a connection string over the separate settings (`host`, `password`, …), and the string's
11
+ * query parameters (`?host=`, `?port=`, `?user=`, `?password=`) over its own parts. So each value is
12
+ * written into the string and the query parameter of the same name is removed. Values that aren't
13
+ * set (`undefined` or `""`) leave the string's own as they are.
14
+ *
15
+ * A string node-postgres can't parse either is returned as it is, so node-postgres reports it.
16
+ */
17
+ export declare function applyToPgConnectionString(connectionString: string, values: PgConnectionStringValues): string;
18
+ /**
19
+ * The password a connection string carries, in its query (which wins) or in the URI, as written
20
+ * there (still percent-encoded). It tells whether the string has a password, not what it is.
21
+ */
22
+ export declare function pgConnectionStringPassword(connectionString: string): string;
@@ -0,0 +1,64 @@
1
+ const DUMMY_HOST = "___dummy___";
2
+ function applyToPgConnectionString(connectionString, values) {
3
+ const url = parsePgConnectionString(connectionString);
4
+ if (!url) return connectionString;
5
+ const isSet = (value)=>void 0 !== value && "" !== value;
6
+ if (isSet(values.host)) {
7
+ const host = values.host;
8
+ url.searchParams.delete("host");
9
+ if (host.startsWith("/")) url.searchParams.set("host", host);
10
+ else url.hostname = host;
11
+ }
12
+ if (isSet(values.port)) {
13
+ url.searchParams.delete("port");
14
+ if (url.hostname === DUMMY_HOST) url.searchParams.set("port", String(values.port));
15
+ else url.port = String(values.port);
16
+ }
17
+ if (isSet(values.user)) {
18
+ url.searchParams.delete("user");
19
+ url.username = encodeURIComponent(values.user);
20
+ }
21
+ if (void 0 !== values.password) {
22
+ url.searchParams.delete("password");
23
+ url.password = encodeURIComponent(values.password);
24
+ }
25
+ if (isSet(values.database)) url.pathname = pgDatabasePath(values.database);
26
+ if (url.hostname !== DUMMY_HOST) return url.toString();
27
+ if ("" === url.pathname) url.pathname = "/";
28
+ return url.toString().replace(new RegExp(`^([a-z][a-z0-9+.-]*://(?:[^/@]*@)?)${DUMMY_HOST}`, "i"), "$1");
29
+ }
30
+ function pgConnectionStringPassword(connectionString) {
31
+ const url = parsePgConnectionString(connectionString);
32
+ if (!url) return "";
33
+ return url.searchParams.get("password") || url.password;
34
+ }
35
+ function parsePgConnectionString(connectionString) {
36
+ if (connectionString.startsWith("/")) {
37
+ const [host, database] = connectionString.split(" ");
38
+ const url = new URL(`postgres://${DUMMY_HOST}`);
39
+ url.searchParams.set("host", host);
40
+ if (database) url.pathname = pgDatabasePath(database);
41
+ return url;
42
+ }
43
+ let str = connectionString;
44
+ if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) str = encodeURI(str).replace(/%25(\d\d)/g, "%$1");
45
+ let url;
46
+ try {
47
+ url = new URL(str);
48
+ } catch {
49
+ try {
50
+ url = new URL(str.replace("@/", `@${DUMMY_HOST}/`));
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ if ("" === url.hostname) url.hostname = DUMMY_HOST;
56
+ return url;
57
+ }
58
+ function pgDatabasePath(database) {
59
+ if (/[#?]/.test(database)) throw new Error(`The Postgres database name "${database}" can't be written into a connection string: it contains "#" or "?".`);
60
+ return `/${encodeURI(database)}`;
61
+ }
62
+ export { applyToPgConnectionString, pgConnectionStringPassword };
63
+
64
+ //# sourceMappingURL=applyToPgConnectionString.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"applyToPgConnectionString.js","sources":["../src/applyToPgConnectionString.ts"],"sourcesContent":["export interface PgConnectionStringValues {\n host?: string;\n port?: number | string;\n user?: string;\n password?: string;\n database?: string;\n}\n\n/**\n * Stands in for a missing host while the string is a `URL`, as node-postgres does: `URL` rejects\n * `postgres://user:pw@/db` and won't take a user, password or port on a URL without a host.\n */\nconst DUMMY_HOST = \"___dummy___\";\n\n/**\n * Writes connection settings into a Postgres connection string, so they win over it. node-postgres\n * reads a connection string over the separate settings (`host`, `password`, …), and the string's\n * query parameters (`?host=`, `?port=`, `?user=`, `?password=`) over its own parts. So each value is\n * written into the string and the query parameter of the same name is removed. Values that aren't\n * set (`undefined` or `\"\"`) leave the string's own as they are.\n *\n * A string node-postgres can't parse either is returned as it is, so node-postgres reports it.\n */\nexport function applyToPgConnectionString(\n connectionString: string,\n values: PgConnectionStringValues\n): string {\n const url = parsePgConnectionString(connectionString);\n if (!url) {\n return connectionString;\n }\n const isSet = (value: unknown): boolean => value !== undefined && value !== \"\";\n\n if (isSet(values.host)) {\n const host = values.host as string;\n url.searchParams.delete(\"host\");\n if (host.startsWith(\"/\")) {\n // A Unix socket directory can't be a URL host; node-postgres reads it from the query.\n url.searchParams.set(\"host\", host);\n } else {\n url.hostname = host;\n }\n }\n if (isSet(values.port)) {\n url.searchParams.delete(\"port\");\n if (url.hostname === DUMMY_HOST) {\n // The dummy host is removed again below, and a port can't follow an empty host.\n url.searchParams.set(\"port\", String(values.port));\n } else {\n url.port = String(values.port);\n }\n }\n if (isSet(values.user)) {\n url.searchParams.delete(\"user\");\n url.username = encodeURIComponent(values.user as string);\n }\n if (values.password !== undefined) {\n url.searchParams.delete(\"password\");\n url.password = encodeURIComponent(values.password);\n }\n if (isSet(values.database)) {\n url.pathname = pgDatabasePath(values.database as string);\n }\n\n if (url.hostname !== DUMMY_HOST) {\n return url.toString();\n }\n if (url.pathname === \"\") {\n // `user:pw@?…` doesn't parse, and node-postgres only puts a host back before `@/`. It reads\n // the path `/` as no database, as it reads an empty one.\n url.pathname = \"/\";\n }\n return url\n .toString()\n .replace(new RegExp(`^([a-z][a-z0-9+.-]*://(?:[^/@]*@)?)${DUMMY_HOST}`, \"i\"), \"$1\");\n}\n\n/**\n * The password a connection string carries, in its query (which wins) or in the URI, as written\n * there (still percent-encoded). It tells whether the string has a password, not what it is.\n */\nexport function pgConnectionStringPassword(connectionString: string): string {\n const url = parsePgConnectionString(connectionString);\n if (!url) {\n return \"\";\n }\n return url.searchParams.get(\"password\") || url.password;\n}\n\n/**\n * Parses a connection string as node-postgres (pg-connection-string) does, with `DUMMY_HOST` where\n * it has no host. `null` when node-postgres can't parse it either.\n */\nfunction parsePgConnectionString(connectionString: string): URL | null {\n // libpq's socket form: \"<socket directory> [database]\".\n if (connectionString.startsWith(\"/\")) {\n const [host, database] = connectionString.split(\" \");\n const url = new URL(`postgres://${DUMMY_HOST}`);\n url.searchParams.set(\"host\", host);\n if (database) {\n url.pathname = pgDatabasePath(database);\n }\n return url;\n }\n\n let str = connectionString;\n if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {\n // Spaces and stray \"%\" are encoded first, as node-postgres does.\n str = encodeURI(str).replace(/%25(\\d\\d)/g, \"%$1\");\n }\n let url: URL;\n try {\n url = new URL(str);\n } catch {\n try {\n url = new URL(str.replace(\"@/\", `@${DUMMY_HOST}/`));\n } catch {\n return null;\n }\n }\n if (url.hostname === \"\") {\n url.hostname = DUMMY_HOST;\n }\n return url;\n}\n\n/**\n * The URL path for a database name. node-postgres reads the path back with `decodeURI`, which\n * decodes everything `encodeURI` encodes and leaves the escapes of `#` and `?` as they are, so those\n * two can't be written at all (the `?database=` query is overwritten by the path).\n */\nfunction pgDatabasePath(database: string): string {\n if (/[#?]/.test(database)) {\n throw new Error(\n `The Postgres database name \"${database}\" can't be written into a connection string: it contains \"#\" or \"?\".`\n );\n }\n return `/${encodeURI(database)}`;\n}\n"],"names":["DUMMY_HOST","applyToPgConnectionString","connectionString","values","url","parsePgConnectionString","isSet","value","undefined","host","String","encodeURIComponent","pgDatabasePath","RegExp","pgConnectionStringPassword","database","URL","str","encodeURI","Error"],"mappings":"AAYA,MAAMA,aAAa;AAWZ,SAASC,0BACZC,gBAAwB,EACxBC,MAAgC;IAEhC,MAAMC,MAAMC,wBAAwBH;IACpC,IAAI,CAACE,KACD,OAAOF;IAEX,MAAMI,QAAQ,CAACC,QAA4BA,AAAUC,WAAVD,SAAuBA,AAAU,OAAVA;IAElE,IAAID,MAAMH,OAAO,IAAI,GAAG;QACpB,MAAMM,OAAON,OAAO,IAAI;QACxBC,IA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iB,KAAK,CAAC;QAChD,MAAME,MAAM,IAAIY,IAAI,CAAC,WAAW,EAAEhB,YAAY;QAC9CI,IAAI,YAAY,CAAC,GAAG,CAAC,QAAQK;QAC7B,IAAIM,UACAX,IAAI,QAAQ,GAAGQ,eAAeG;QAElC,OAAOX;IACX;IAEA,IAAIa,MAAMf;IACV,IAAI,mCAAmC,IAAI,CAACe,MAExCA,MAAMC,UAAUD,KAAK,OAAO,CAAC,cAAc;IAE/C,IAAIb;IACJ,IAAI;QACAA,MAAM,IAAIY,IAAIC;IAClB,EAAE,OAAM;QACJ,IAAI;YACAb,MAAM,IAAIY,IAAIC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,EAAEjB,WAAW,CAAC,CAAC;QACrD,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IACA,IAAII,AAAiB,OAAjBA,IAAI,QAAQ,EACZA,IAAI,QAAQ,GAAGJ;IAEnB,OAAOI;AACX;AAOA,SAASQ,eAAeG,QAAgB;IACpC,IAAI,OAAO,IAAI,CAACA,WACZ,MAAM,IAAII,MACN,CAAC,4BAA4B,EAAEJ,SAAS,oEAAoE,CAAC;IAGrH,OAAO,CAAC,CAAC,EAAEG,UAAUH,WAAW;AACpC"}
@@ -0,0 +1,33 @@
1
+ import { type Knex } from "knex";
2
+ export interface CreatePgConnectionOptions {
3
+ host?: string;
4
+ port?: number;
5
+ user?: string;
6
+ password?: string;
7
+ database?: string;
8
+ /**
9
+ * Optional additional Knex connection config (SSL, pool size, etc.).
10
+ * Overrides values from env vars when both are set.
11
+ */
12
+ connection?: Partial<Knex.PgConnectionConfig>;
13
+ /**
14
+ * How long to retry a read or transaction that lost its connection (failover, restart), in
15
+ * milliseconds; 0 turns retries off. Default: `WEBINY_PG_RETRY_MS`, else 15,000.
16
+ */
17
+ retryMs?: number;
18
+ /**
19
+ * Where the `WEBINY_PG_*` settings are read from. Default: `process.env`, the default storage's.
20
+ * An extra storage passes its own settings, under the same names, or `{}` to take only the
21
+ * explicit options: the default storage's settings must never fill in for it.
22
+ */
23
+ env?: Record<string, string | undefined>;
24
+ }
25
+ /**
26
+ * A Knex client for Postgres, for a long-running process (the standalone server): Postgres, PGlite
27
+ * (`<Infra.Pglite>`) or Aurora from a server. Connection parameters are read from the `WEBINY_PG_*`
28
+ * env vars `<Infra.Postgres>` sets, with explicit options taking precedence. A connection string
29
+ * (`WEBINY_PG_CONNECTION_STRING` or `options.connection.connectionString`) is enough on its own:
30
+ * node-postgres reads host, port, user, password and database from it. On AWS Lambda, use
31
+ * `createLambdaPgConnection` (`@webiny/api-composition-aws-pg`) instead.
32
+ */
33
+ export declare function createPgConnection(options?: CreatePgConnectionOptions): Knex;
@@ -0,0 +1,60 @@
1
+ import knex from "knex";
2
+ import { withPgConnectionRetry } from "@webiny/api-core-sql";
3
+ import { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from "./readPgConnectionEnv.js";
4
+ import { applyToPgConnectionString } from "./applyToPgConnectionString.js";
5
+ const definedOnly = (values)=>Object.fromEntries(Object.entries(values).filter(([, value])=>!!value));
6
+ const assertSet = (value, message)=>{
7
+ if (!value) throw new Error(message);
8
+ };
9
+ function createPgConnection(options = {}) {
10
+ const env = readPgConnectionEnv(options.env);
11
+ const explicitConnection = options.connection || {};
12
+ const explicit = {
13
+ ...definedOnly({
14
+ host: options.host,
15
+ port: options.port,
16
+ user: options.user,
17
+ password: options.password,
18
+ database: options.database
19
+ }),
20
+ ...definedOnly({
21
+ host: explicitConnection.host,
22
+ port: explicitConnection.port,
23
+ user: explicitConnection.user,
24
+ password: "string" == typeof explicitConnection.password ? explicitConnection.password : void 0,
25
+ database: explicitConnection.database
26
+ })
27
+ };
28
+ const connectionConfig = {
29
+ ...env.connection,
30
+ ...explicit,
31
+ ...explicitConnection
32
+ };
33
+ if (connectionConfig.connectionString && Object.keys(explicit).length > 0) connectionConfig.connectionString = applyToPgConnectionString(connectionConfig.connectionString, explicit);
34
+ if (!connectionConfig.connectionString) {
35
+ assertSet(connectionConfig.host, 'Postgres host is not set. Configure via <Infra.Postgres host="..." /> in webiny.config.');
36
+ assertSet(connectionConfig.port, "Postgres port is not set. Configure via <Infra.Postgres port={...} /> in webiny.config.");
37
+ assertSet(connectionConfig.user, 'Postgres user is not set. Configure via <Infra.Postgres user="..." /> in webiny.config.');
38
+ assertSet(connectionConfig.password, 'Postgres password is not set. Configure via <Infra.Postgres password="..." /> in webiny.config.');
39
+ assertSet(connectionConfig.database, 'Postgres database is not set. Configure via <Infra.Postgres database="..." /> in webiny.config.');
40
+ }
41
+ const poolMax = env.poolMax;
42
+ const client = knex({
43
+ client: "pg",
44
+ connection: connectionConfig,
45
+ ...void 0 !== poolMax ? {
46
+ pool: {
47
+ min: Math.min(2, poolMax),
48
+ max: poolMax
49
+ }
50
+ } : {}
51
+ });
52
+ const retryMs = options.retryMs ?? env.retryMs ?? DEFAULT_PG_RETRY_MS;
53
+ if (retryMs > 0) withPgConnectionRetry(client, {
54
+ maxRetryMs: retryMs
55
+ });
56
+ return client;
57
+ }
58
+ export { createPgConnection };
59
+
60
+ //# sourceMappingURL=createPgConnection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPgConnection.js","sources":["../src/createPgConnection.ts"],"sourcesContent":["import knex, { type Knex } from \"knex\";\nimport { withPgConnectionRetry } from \"@webiny/api-core-sql\";\nimport { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from \"./readPgConnectionEnv.js\";\nimport { applyToPgConnectionString } from \"./applyToPgConnectionString.js\";\n\nconst definedOnly = <T extends Record<string, unknown>>(values: T): Partial<T> => {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => !!value)) as Partial<T>;\n};\n\nconst assertSet = (value: unknown, message: string): void => {\n if (!value) {\n throw new Error(message);\n }\n};\n\nexport interface CreatePgConnectionOptions {\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n /**\n * Optional additional Knex connection config (SSL, pool size, etc.).\n * Overrides values from env vars when both are set.\n */\n connection?: Partial<Knex.PgConnectionConfig>;\n /**\n * How long to retry a read or transaction that lost its connection (failover, restart), in\n * milliseconds; 0 turns retries off. Default: `WEBINY_PG_RETRY_MS`, else 15,000.\n */\n retryMs?: number;\n /**\n * Where the `WEBINY_PG_*` settings are read from. Default: `process.env`, the default storage's.\n * An extra storage passes its own settings, under the same names, or `{}` to take only the\n * explicit options: the default storage's settings must never fill in for it.\n */\n env?: Record<string, string | undefined>;\n}\n\n/**\n * A Knex client for Postgres, for a long-running process (the standalone server): Postgres, PGlite\n * (`<Infra.Pglite>`) or Aurora from a server. Connection parameters are read from the `WEBINY_PG_*`\n * env vars `<Infra.Postgres>` sets, with explicit options taking precedence. A connection string\n * (`WEBINY_PG_CONNECTION_STRING` or `options.connection.connectionString`) is enough on its own:\n * node-postgres reads host, port, user, password and database from it. On AWS Lambda, use\n * `createLambdaPgConnection` (`@webiny/api-composition-aws-pg`) instead.\n */\nexport function createPgConnection(options: CreatePgConnectionOptions = {}): Knex {\n const env = readPgConnectionEnv(options.env);\n const explicitConnection = options.connection || {};\n // The connection parts the caller set: the options, then `options.connection`.\n const explicit = {\n ...definedOnly({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.database\n }),\n ...definedOnly({\n host: explicitConnection.host,\n port: explicitConnection.port,\n user: explicitConnection.user,\n // A password function can't go into a connection string.\n password:\n typeof explicitConnection.password === \"string\"\n ? explicitConnection.password\n : undefined,\n database: explicitConnection.database\n })\n };\n // Env first, then the explicit options, then `options.connection`: validated as Knex gets it.\n const connectionConfig: Knex.PgConnectionConfig = {\n ...env.connection,\n ...explicit,\n ...explicitConnection\n };\n // node-postgres reads a connection string over the separate parts, so the parts the caller set\n // go into the string too (the env's own parts don't: the string is the env's whole connection).\n if (connectionConfig.connectionString && Object.keys(explicit).length > 0) {\n connectionConfig.connectionString = applyToPgConnectionString(\n connectionConfig.connectionString,\n explicit\n );\n }\n\n // A connection string holds the whole connection; otherwise each part must be set.\n if (!connectionConfig.connectionString) {\n assertSet(\n connectionConfig.host,\n 'Postgres host is not set. Configure via <Infra.Postgres host=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.port,\n \"Postgres port is not set. Configure via <Infra.Postgres port={...} /> in webiny.config.\"\n );\n assertSet(\n connectionConfig.user,\n 'Postgres user is not set. Configure via <Infra.Postgres user=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.password,\n 'Postgres password is not set. Configure via <Infra.Postgres password=\"...\" /> in webiny.config.'\n );\n assertSet(\n connectionConfig.database,\n 'Postgres database is not set. Configure via <Infra.Postgres database=\"...\" /> in webiny.config.'\n );\n }\n\n const poolMax = env.poolMax;\n\n const client = knex({\n client: \"pg\",\n connection: connectionConfig,\n // knex's default minimum (2) must not exceed the maximum.\n ...(poolMax !== undefined ? { pool: { min: Math.min(2, poolMax), max: poolMax } } : {})\n });\n\n // Reads and transactions that lose their connection run again on a new one (see\n // withPgConnectionRetry); writes outside a transaction are not retried.\n const retryMs = options.retryMs ?? env.retryMs ?? DEFAULT_PG_RETRY_MS;\n if (retryMs > 0) {\n withPgConnectionRetry(client, { maxRetryMs: retryMs });\n }\n return client;\n}\n"],"names":["definedOnly","values","Object","value","assertSet","message","Error","createPgConnection","options","env","readPgConnectionEnv","explicitConnection","explicit","undefined","connectionConfig","applyToPgConnectionString","poolMax","client","knex","Math","retryMs","DEFAULT_PG_RETRY_MS","withPgConnectionRetry"],"mappings":";;;;AAKA,MAAMA,cAAc,CAAoCC,SAC7CC,OAAO,WAAW,CAACA,OAAO,OAAO,CAACD,QAAQ,MAAM,CAAC,CAAC,GAAGE,MAAM,GAAK,CAAC,CAACA;AAG7E,MAAMC,YAAY,CAACD,OAAgBE;IAC/B,IAAI,CAACF,OACD,MAAM,IAAIG,MAAMD;AAExB;AAkCO,SAASE,mBAAmBC,UAAqC,CAAC,CAAC;IACtE,MAAMC,MAAMC,oBAAoBF,QAAQ,GAAG;IAC3C,MAAMG,qBAAqBH,QAAQ,UAAU,IAAI,CAAC;IAElD,MAAMI,W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1,30 @@
1
+ import type { Knex } from "knex";
2
+ import { type SqlStorage, type SqlStorageIdentityParams } from "@webiny/api-core-sql";
3
+ export interface CreatePgStorageParams extends SqlStorageIdentityParams {
4
+ /** The connection: `createPgConnection()` on a server, `createLambdaPgConnection()` on Lambda. */
5
+ knex: Knex;
6
+ tableNamePrefix?: string;
7
+ /**
8
+ * The schema was set up before the API took traffic (at deploy time, by the schema-setup
9
+ * event), so no part of the storage checks for or creates tables at runtime. Off by default:
10
+ * the storage becomes schema-managed once its `SqlSchemaSetupRunner` ran, and until then checks
11
+ * and creates each table on first use.
12
+ */
13
+ schemaManaged?: boolean;
14
+ }
15
+ /**
16
+ * The Postgres SQL storage of the Webiny API, shared by every transport that runs it on Postgres
17
+ * (the standalone server and AWS Lambda): SQL core, websockets and audit logs. It is the deploy's
18
+ * default storage, or, with an `id`, an extra storage that only the tenants naming it in
19
+ * `settings.storage` run on (see `SqlStorage.register`). Generic: it holds no
20
+ * CMS and no ACO. Those are modules the project adds with its extensions (`<HeadlessCmsPg />`,
21
+ * `<AcoPg />`), which run on what the storage registers: the connection, the table prefix and the
22
+ * schema-managed setting. Without the CMS module, its schema setup fails, naming it.
23
+ *
24
+ * In the root it registers only the connection and its settings, and its `SqlSchemaSetupRunner`;
25
+ * its storages register in each request's container (`RequestStorage`).
26
+ *
27
+ * Identity is not part of it: each transport brings its own (self-hosted auth on the standalone
28
+ * server, the project's identity provider on Lambda).
29
+ */
30
+ export declare function createPgStorage(params: CreatePgStorageParams): SqlStorage;
@@ -0,0 +1,111 @@
1
+ import { RequestStorage } from "@webiny/api-core";
2
+ import { ApiCoreSqlFeature, SqlConnectionFeature, SqlSchemaSetupRunner, createSqlRequestStorage, createSqlTenantStorageBackend, registerTenantStorageBackend, runSchemaSetupSteps, setSqlServiceManifestLoader } from "@webiny/api-core-sql";
3
+ import { TenantStorageId, createDefaultTenantStorageBackend } from "@webiny/api-core/features/tenancy/TenantStorages/index.js";
4
+ import { WebsocketsSqlFeature } from "@webiny/api-websockets-sql";
5
+ import { AuditLogsSqlFeature } from "@webiny/api-audit-logs-sql";
6
+ const REQUIRED_MODULES = [
7
+ {
8
+ name: "cms",
9
+ message: "The Postgres storage has no CMS storage: add <HeadlessCmsPg /> (from @webiny/api-headless-cms-pg/project) to webiny.config.tsx."
10
+ }
11
+ ];
12
+ const PG_STORAGE_TYPE = "postgres";
13
+ const PG_DIALECT = "postgres";
14
+ const PG_STORAGE_LABEL = "Postgres";
15
+ const registerPgParts = (container)=>{
16
+ ApiCoreSqlFeature.register(container);
17
+ AuditLogsSqlFeature.register(container);
18
+ WebsocketsSqlFeature.register(container);
19
+ };
20
+ const PgRequestStorage = createSqlRequestStorage(registerPgParts);
21
+ const setupLockKey = (tableNamePrefix)=>`${tableNamePrefix ?? ""}webiny_schema_setup`;
22
+ class PgSchemaSetupRunner {
23
+ constructor(root, knex, tableNamePrefix, state, storage, backendOn){
24
+ this.root = root;
25
+ this.knex = knex;
26
+ this.tableNamePrefix = tableNamePrefix;
27
+ this.state = state;
28
+ this.storage = storage;
29
+ this.backendOn = backendOn;
30
+ }
31
+ async run(params) {
32
+ const knex = params.knex ?? this.knex;
33
+ const done = await knex.transaction(async (trx)=>{
34
+ await trx.raw("SELECT pg_advisory_xact_lock(hashtext(?))", [
35
+ setupLockKey(this.tableNamePrefix)
36
+ ]);
37
+ return runSchemaSetupSteps({
38
+ root: this.root,
39
+ knex: trx,
40
+ dialect: PG_DIALECT,
41
+ tableNamePrefix: this.tableNamePrefix,
42
+ request: params.request,
43
+ required: REQUIRED_MODULES,
44
+ backend: this.backendOn?.(trx)
45
+ });
46
+ });
47
+ this.state.managed = true;
48
+ return done;
49
+ }
50
+ }
51
+ class PgStorage {
52
+ constructor(params){
53
+ this.storageId = TenantStorageId.from(params.id);
54
+ this.id = this.storageId.toString();
55
+ this.label = params.label ?? PG_STORAGE_LABEL;
56
+ this.retired = true === params.retired;
57
+ this.knex = params.knex;
58
+ this.tableNamePrefix = params.tableNamePrefix;
59
+ this.state = {
60
+ managed: true === params.schemaManaged
61
+ };
62
+ }
63
+ register(container) {
64
+ if (this.storageId.isDefault()) return void this.registerAsDefault(container);
65
+ this.registerAsExtra(container);
66
+ }
67
+ registerAsDefault(container) {
68
+ SqlConnectionFeature.register(container, {
69
+ knex: this.knex,
70
+ dialect: PG_DIALECT,
71
+ tableNamePrefix: this.tableNamePrefix,
72
+ schemaManaged: ()=>this.state.managed
73
+ });
74
+ setSqlServiceManifestLoader({
75
+ knex: this.knex,
76
+ tableNamePrefix: this.tableNamePrefix,
77
+ schemaManaged: ()=>this.state.managed
78
+ });
79
+ container.registerInstance(RequestStorage, PgRequestStorage);
80
+ registerTenantStorageBackend(container, createDefaultTenantStorageBackend({
81
+ type: PG_STORAGE_TYPE,
82
+ label: this.label
83
+ }));
84
+ container.registerInstance(SqlSchemaSetupRunner, new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id));
85
+ }
86
+ registerAsExtra(container) {
87
+ registerTenantStorageBackend(container, this.backendOn(this.knex, ()=>this.state.managed));
88
+ container.registerInstance(SqlSchemaSetupRunner, new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id, (knex)=>this.backendOn(knex, ()=>false)));
89
+ }
90
+ backendOn(knex, schemaManaged) {
91
+ return createSqlTenantStorageBackend({
92
+ id: this.id,
93
+ label: this.label,
94
+ type: PG_STORAGE_TYPE,
95
+ retired: this.retired,
96
+ connection: {
97
+ knex,
98
+ dialect: PG_DIALECT,
99
+ tableNamePrefix: this.tableNamePrefix,
100
+ schemaManaged
101
+ },
102
+ registerParts: registerPgParts
103
+ });
104
+ }
105
+ }
106
+ function createPgStorage(params) {
107
+ return new PgStorage(params);
108
+ }
109
+ export { createPgStorage };
110
+
111
+ //# sourceMappingURL=createPgStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPgStorage.js","sources":["../src/createPgStorage.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/di\";\nimport { RequestStorage } from \"@webiny/api-core\";\nimport {\n ApiCoreSqlFeature,\n createSqlRequestStorage,\n createSqlTenantStorageBackend,\n registerTenantStorageBackend,\n runSchemaSetupSteps,\n setSqlServiceManifestLoader,\n SqlConnectionFeature,\n type SqlDialect,\n SqlSchemaSetupRunner,\n type SqlStorage,\n type SqlStorageIdentityParams\n} from \"@webiny/api-core-sql\";\nimport {\n createDefaultTenantStorageBackend,\n TenantStorageId,\n type TenantStorageBackend\n} from \"@webiny/api-core/features/tenancy/TenantStorages/index.js\";\nimport { WebsocketsSqlFeature } from \"@webiny/api-websockets-sql\";\nimport { AuditLogsSqlFeature } from \"@webiny/api-audit-logs-sql\";\n\nexport interface CreatePgStorageParams extends SqlStorageIdentityParams {\n /** The connection: `createPgConnection()` on a server, `createLambdaPgConnection()` on Lambda. */\n knex: Knex;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (at deploy time, by the schema-setup\n * event), so no part of the storage checks for or creates tables at runtime. Off by default:\n * the storage becomes schema-managed once its `SqlSchemaSetupRunner` ran, and until then checks\n * and creates each table on first use.\n */\n schemaManaged?: boolean;\n}\n\n/** What the API on Postgres can't run without: the CMS storage is a module the project adds. */\nconst REQUIRED_MODULES = [\n {\n name: \"cms\",\n message:\n \"The Postgres storage has no CMS storage: add <HeadlessCmsPg /> (from @webiny/api-headless-cms-pg/project) to webiny.config.tsx.\"\n }\n];\n\n/** The storage's family, as `TenantStorages` lists it. */\nconst PG_STORAGE_TYPE = \"postgres\";\n/** The connection's database family, registered with it as `SqlDialect`. */\nconst PG_DIALECT: SqlDialect.Name = \"postgres\";\nconst PG_STORAGE_LABEL = \"Postgres\";\n\n/*\n * The storage's parts of a tenant scope: SQL core (tenancy, security, users, key-value store), audit\n * logs and the websocket connection registry. Each runs on the scope's connection and table settings:\n * the root's for the default storage, the scope's own for an extra one.\n */\nconst registerPgParts = (container: Container): void => {\n ApiCoreSqlFeature.register(container);\n AuditLogsSqlFeature.register(container);\n WebsocketsSqlFeature.register(container);\n};\n\nconst PgRequestStorage: RequestStorage.Interface = createSqlRequestStorage(registerPgParts);\n\n/**\n * The advisory lock every schema setup of one storage takes. Keyed by the table prefix, so storages\n * of different prefixes in one database don't wait for each other.\n */\nconst setupLockKey = (tableNamePrefix?: string): string => {\n return `${tableNamePrefix ?? \"\"}webiny_schema_setup`;\n};\n\n/** Whether the storage's schema is set up. Shared by the storage's root settings and its runner. */\ninterface SchemaState {\n managed: boolean;\n}\n\n/*\n * It all runs in one transaction that first takes an advisory lock, so several processes starting\n * together run it one after another: the second finds everything in place. A failure rolls the\n * whole setup back. The parts that lock on their own (the CMS and the folder catalog) nest in this\n * transaction, so they don't wait for themselves.\n */\nclass PgSchemaSetupRunner implements SqlSchemaSetupRunner.Interface {\n public constructor(\n private readonly root: Container,\n private readonly knex: Knex,\n private readonly tableNamePrefix: string | undefined,\n private readonly state: SchemaState,\n public readonly storage: string,\n /** An extra storage's backend on the setup's connection; none for the default storage. */\n private readonly backendOn?: (knex: Knex) => TenantStorageBackend.Interface\n ) {}\n\n public async run(params: SqlSchemaSetupRunner.RunParams): Promise<string[]> {\n const knex = params.knex ?? this.knex;\n const done = await knex.transaction(async trx => {\n await trx.raw(\"SELECT pg_advisory_xact_lock(hashtext(?))\", [\n setupLockKey(this.tableNamePrefix)\n ]);\n return runSchemaSetupSteps({\n root: this.root,\n knex: trx,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n request: params.request,\n required: REQUIRED_MODULES,\n backend: this.backendOn?.(trx)\n });\n });\n this.state.managed = true;\n return done;\n }\n}\n\nclass PgStorage implements SqlStorage {\n public readonly id: string;\n public readonly knex: Knex;\n private readonly storageId: TenantStorageId;\n public readonly tableNamePrefix?: string;\n private readonly label: string;\n private readonly retired: boolean;\n private readonly state: SchemaState;\n\n public constructor(params: CreatePgStorageParams) {\n this.storageId = TenantStorageId.from(params.id);\n this.id = this.storageId.toString();\n this.label = params.label ?? PG_STORAGE_LABEL;\n this.retired = params.retired === true;\n this.knex = params.knex;\n this.tableNamePrefix = params.tableNamePrefix;\n this.state = { managed: params.schemaManaged === true };\n }\n\n public register(container: Container): void {\n if (this.storageId.isDefault()) {\n this.registerAsDefault(container);\n return;\n }\n this.registerAsExtra(container);\n }\n\n /*\n * The root gets the connection and its settings, the schema setup runner, and service discovery\n * reads the manifests on the connection. Every storage is registered per scope, by\n * `PgRequestStorage`, which the default storage's backend registers.\n */\n private registerAsDefault(container: Container): void {\n SqlConnectionFeature.register(container, {\n knex: this.knex,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n setSqlServiceManifestLoader({\n knex: this.knex,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged: () => this.state.managed\n });\n container.registerInstance(RequestStorage, PgRequestStorage);\n registerTenantStorageBackend(\n container,\n createDefaultTenantStorageBackend({ type: PG_STORAGE_TYPE, label: this.label })\n );\n container.registerInstance(\n SqlSchemaSetupRunner,\n new PgSchemaSetupRunner(container, this.knex, this.tableNamePrefix, this.state, this.id)\n );\n }\n\n /*\n * The root gets only the storage's backend and its schema setup runner: the connection is\n * registered in each scope on the storage, never in the root, where it would replace the default\n * storage's. Service discovery stays on the default storage.\n */\n private registerAsExtra(container: Container): void {\n registerTenantStorageBackend(\n container,\n this.backendOn(this.knex, () => this.state.managed)\n );\n container.registerInstance(\n SqlSchemaSetupRunner,\n new PgSchemaSetupRunner(\n container,\n this.knex,\n this.tableNamePrefix,\n this.state,\n this.id,\n // The setup's connection is a transaction: nothing is set up yet.\n knex => this.backendOn(knex, () => false)\n )\n );\n }\n\n private backendOn(knex: Knex, schemaManaged: () => boolean): TenantStorageBackend.Interface {\n return createSqlTenantStorageBackend({\n id: this.id,\n label: this.label,\n type: PG_STORAGE_TYPE,\n retired: this.retired,\n connection: {\n knex,\n dialect: PG_DIALECT,\n tableNamePrefix: this.tableNamePrefix,\n schemaManaged\n },\n registerParts: registerPgParts\n });\n }\n}\n\n/**\n * The Postgres SQL storage of the Webiny API, shared by every transport that runs it on Postgres\n * (the standalone server and AWS Lambda): SQL core, websockets and audit logs. It is the deploy's\n * default storage, or, with an `id`, an extra storage that only the tenants naming it in\n * `settings.storage` run on (see `SqlStorage.register`). Generic: it holds no\n * CMS and no ACO. Those are modules the project adds with its extensions (`<HeadlessCmsPg />`,\n * `<AcoPg />`), which run on what the storage registers: the connection, the table prefix and the\n * schema-managed setting. Without the CMS module, its schema setup fails, naming it.\n *\n * In the root it registers only the connection and its settings, and its `SqlSchemaSetupRunner`;\n * its storages register in each request's container (`RequestStorage`).\n *\n * Identity is not part of it: each transport brings its own (self-hosted auth on the standalone\n * server, the project's identity provider on Lambda).\n */\nexport function createPgStorage(params: CreatePgStorageParams): SqlStorage {\n return new PgStorage(params);\n}\n"],"names":["REQUIRED_MODULES","PG_STORAGE_TYPE","PG_DIALECT","PG_STORAGE_LABEL","registerPgParts","container","ApiCoreSqlFeature","AuditLogsSqlFeature","WebsocketsSqlFeature","PgRequestStorage","createSqlRequestStorage","setupLockKey","tableNamePrefix","PgSchemaSetupRunner","root","knex","state","storage","backendOn","params","done","trx","runSchemaSetupSteps","PgStorage","TenantStorageId","SqlConnectionFeature","setSqlServiceManifestLoader","RequestStorage","registerTenantStorageBackend","createDefaultTenantStorageBackend","SqlSchemaSetupRunner","schemaManaged","createSqlTenantStorageBackend","createPgStorage"],"mappings":";;;;;AAsCA,MAAMA,mBAAmB;IACrB;QACI,MAAM;QACN,SACI;IACR;CACH;AAGD,MAAMC,kBAAkB;AAExB,MAAMC,aAA8B;AACpC,MAAMC,mBAAmB;AAOzB,MAAMC,kBAAkB,CAACC;IACrBC,kBAAkB,QAAQ,CAACD;IAC3BE,oBAAoB,QAAQ,CAACF;IAC7BG,qBAAqB,QAAQ,CAACH;AAClC;AAEA,MAAMI,mBAA6CC,wBAAwBN;AAM3E,MAAMO,eAAe,CAACC,kBACX,GAAGA,mBAAmB,GAAG,mBAAmB,CAAC;AAcxD,MAAMC;I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iBAAiB,IAAI,CAAC,eAAe;gBACrC6B;YACJ;YACA,eAAe3B;QACnB;IACJ;AACJ;AAiBO,SAAS6B,gBAAgBd,MAA6B;IACzD,OAAO,IAAII,UAAUJ;AACzB"}
@@ -0,0 +1,39 @@
1
+ import type { Knex } from "knex";
2
+ import type { SqlStorage } from "@webiny/api-core-sql";
3
+ /** The env var the extra storages are read from. `webiny watch` and `serve` set it from the config. */
4
+ export declare const TENANT_STORAGES_ENV = "WEBINY_TENANT_STORAGES";
5
+ /** One extra storage in `WEBINY_TENANT_STORAGES`. */
6
+ export interface TenantStorageEnvEntry {
7
+ id: string;
8
+ label: string;
9
+ retired?: boolean;
10
+ /** The storage's family. Only `postgres` is read here. */
11
+ type: string;
12
+ /** The storage's connection, under the `WEBINY_PG_*` names `<Infra.Postgres>` uses. */
13
+ connection: Record<string, string>;
14
+ }
15
+ type Env = Record<string, string | undefined>;
16
+ /**
17
+ * The extra storages in `WEBINY_TENANT_STORAGES`, checked: a malformed value stops the API with a
18
+ * message naming the variable, rather than a connection error later. Unset or empty means none.
19
+ */
20
+ export declare function readTenantStoragesEnv(env?: Env): TenantStorageEnvEntry[];
21
+ export interface CreatePgTenantStoragesParams {
22
+ /**
23
+ * The ids of the storages the build declares (`<Infra.TenantStorage.*>`). Each must be in the
24
+ * env, and the env may hold no other: a storage the build doesn't know would put tenants on a
25
+ * database nobody declared.
26
+ */
27
+ ids: string[];
28
+ /** Where `WEBINY_TENANT_STORAGES` is read from. Default: `process.env`. */
29
+ env?: Env;
30
+ /** Builds a storage's connection from its settings. Default: `createPgConnection`. */
31
+ connect?: (connection: Record<string, string>) => Knex;
32
+ }
33
+ /**
34
+ * The extra Postgres storages of the standalone API, each with its own connection pool, for
35
+ * `createSqlApiHandler({ storages })`. Their connections are read from `WEBINY_TENANT_STORAGES` when
36
+ * the API starts; the default storage's `WEBINY_PG_*` settings never fill in for one.
37
+ */
38
+ export declare function createPgTenantStorages(params: CreatePgTenantStoragesParams): SqlStorage[];
39
+ export {};
@@ -0,0 +1,41 @@
1
+ import { createPgConnection } from "./createPgConnection.js";
2
+ import { createPgStorage } from "./createPgStorage.js";
3
+ const TENANT_STORAGES_ENV = "WEBINY_TENANT_STORAGES";
4
+ const isRecord = (value)=>"object" == typeof value && null !== value && !Array.isArray(value);
5
+ const isStringRecord = (value)=>isRecord(value) && Object.values(value).every((item)=>"string" == typeof item);
6
+ function readTenantStoragesEnv(env = process.env) {
7
+ const raw = env[TENANT_STORAGES_ENV];
8
+ if (!raw) return [];
9
+ let parsed;
10
+ try {
11
+ parsed = JSON.parse(raw);
12
+ } catch (error) {
13
+ throw new Error(`${TENANT_STORAGES_ENV} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}.`);
14
+ }
15
+ if (!Array.isArray(parsed)) throw new Error(`${TENANT_STORAGES_ENV} must be a JSON list of storages.`);
16
+ return parsed.map((entry, index)=>{
17
+ const valid = isRecord(entry) && "string" == typeof entry.id && entry.id.length > 0 && "string" == typeof entry.label && "string" == typeof entry.type && (void 0 === entry.retired || "boolean" == typeof entry.retired) && isStringRecord(entry.connection);
18
+ if (!valid) throw new Error(`${TENANT_STORAGES_ENV}[${index}] must have a string "id", "label" and "type", an optional boolean "retired", and a "connection" of string settings.`);
19
+ return entry;
20
+ });
21
+ }
22
+ function createPgTenantStorages(params) {
23
+ const entries = readTenantStoragesEnv(params.env);
24
+ const connect = params.connect ?? ((connection)=>createPgConnection({
25
+ env: connection
26
+ }));
27
+ for (const id of params.ids)if (!entries.some((entry)=>entry.id === id)) throw new Error(`Storage "${id}" is declared in webiny.config, but ${TENANT_STORAGES_ENV} has no connection for it. \`webiny watch\` and \`webiny-standalone serve\` set it from the config; a server started otherwise needs it in its environment.`);
28
+ return entries.map((entry)=>{
29
+ if (!params.ids.includes(entry.id)) throw new Error(`${TENANT_STORAGES_ENV} has storage "${entry.id}", which webiny.config doesn't declare. Declare it with <Infra.TenantStorage.*> and build again.`);
30
+ if ("postgres" !== entry.type) throw new Error(`Storage "${entry.id}" in ${TENANT_STORAGES_ENV} is of type "${entry.type}"; the standalone API runs extra storages on Postgres only.`);
31
+ return createPgStorage({
32
+ id: entry.id,
33
+ label: entry.label,
34
+ retired: true === entry.retired,
35
+ knex: connect(entry.connection)
36
+ });
37
+ });
38
+ }
39
+ export { TENANT_STORAGES_ENV, createPgTenantStorages, readTenantStoragesEnv };
40
+
41
+ //# sourceMappingURL=createPgTenantStorages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPgTenantStorages.js","sources":["../src/createPgTenantStorages.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { SqlStorage } from \"@webiny/api-core-sql\";\nimport { createPgConnection } from \"./createPgConnection.js\";\nimport { createPgStorage } from \"./createPgStorage.js\";\n\n/** The env var the extra storages are read from. `webiny watch` and `serve` set it from the config. */\nexport const TENANT_STORAGES_ENV = \"WEBINY_TENANT_STORAGES\";\n\n/** One extra storage in `WEBINY_TENANT_STORAGES`. */\nexport interface TenantStorageEnvEntry {\n id: string;\n label: string;\n retired?: boolean;\n /** The storage's family. Only `postgres` is read here. */\n type: string;\n /** The storage's connection, under the `WEBINY_PG_*` names `<Infra.Postgres>` uses. */\n connection: Record<string, string>;\n}\n\ntype Env = Record<string, string | undefined>;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst isStringRecord = (value: unknown): value is Record<string, string> => {\n return isRecord(value) && Object.values(value).every(item => typeof item === \"string\");\n};\n\n/**\n * The extra storages in `WEBINY_TENANT_STORAGES`, checked: a malformed value stops the API with a\n * message naming the variable, rather than a connection error later. Unset or empty means none.\n */\nexport function readTenantStoragesEnv(env: Env = process.env): TenantStorageEnvEntry[] {\n const raw = env[TENANT_STORAGES_ENV];\n if (!raw) {\n return [];\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new Error(\n `${TENANT_STORAGES_ENV} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}.`\n );\n }\n if (!Array.isArray(parsed)) {\n throw new Error(`${TENANT_STORAGES_ENV} must be a JSON list of storages.`);\n }\n\n return parsed.map((entry, index) => {\n const valid =\n isRecord(entry) &&\n typeof entry.id === \"string\" &&\n entry.id.length > 0 &&\n typeof entry.label === \"string\" &&\n typeof entry.type === \"string\" &&\n (entry.retired === undefined || typeof entry.retired === \"boolean\") &&\n isStringRecord(entry.connection);\n if (!valid) {\n throw new Error(\n `${TENANT_STORAGES_ENV}[${index}] must have a string \"id\", \"label\" and \"type\", an optional boolean \"retired\", and a \"connection\" of string settings.`\n );\n }\n return entry as unknown as TenantStorageEnvEntry;\n });\n}\n\nexport interface CreatePgTenantStoragesParams {\n /**\n * The ids of the storages the build declares (`<Infra.TenantStorage.*>`). Each must be in the\n * env, and the env may hold no other: a storage the build doesn't know would put tenants on a\n * database nobody declared.\n */\n ids: string[];\n /** Where `WEBINY_TENANT_STORAGES` is read from. Default: `process.env`. */\n env?: Env;\n /** Builds a storage's connection from its settings. Default: `createPgConnection`. */\n connect?: (connection: Record<string, string>) => Knex;\n}\n\n/**\n * The extra Postgres storages of the standalone API, each with its own connection pool, for\n * `createSqlApiHandler({ storages })`. Their connections are read from `WEBINY_TENANT_STORAGES` when\n * the API starts; the default storage's `WEBINY_PG_*` settings never fill in for one.\n */\nexport function createPgTenantStorages(params: CreatePgTenantStoragesParams): SqlStorage[] {\n const entries = readTenantStoragesEnv(params.env);\n const connect =\n params.connect ??\n ((connection: Record<string, string>) => createPgConnection({ env: connection }));\n\n for (const id of params.ids) {\n if (!entries.some(entry => entry.id === id)) {\n throw new Error(\n `Storage \"${id}\" is declared in webiny.config, but ${TENANT_STORAGES_ENV} has no connection for it. \\`webiny watch\\` and \\`webiny-standalone serve\\` set it from the config; a server started otherwise needs it in its environment.`\n );\n }\n }\n\n return entries.map(entry => {\n if (!params.ids.includes(entry.id)) {\n throw new Error(\n `${TENANT_STORAGES_ENV} has storage \"${entry.id}\", which webiny.config doesn't declare. Declare it with <Infra.TenantStorage.*> and build again.`\n );\n }\n if (entry.type !== \"postgres\") {\n throw new Error(\n `Storage \"${entry.id}\" in ${TENANT_STORAGES_ENV} is of type \"${entry.type}\"; the standalone API runs extra storages on Postgres only.`\n );\n }\n return createPgStorage({\n id: entry.id,\n label: entry.label,\n retired: entry.retired === true,\n knex: connect(entry.connection)\n });\n });\n}\n"],"names":["TENANT_STORAGES_ENV","isRecord","value","Array","isStringRecord","Object","item","readTenantStoragesEnv","env","process","raw","parsed","JSON","error","Error","String","entry","index","valid","undefined","createPgTenantStorages","params","entries","connect","connection","createPgConnection","id","createPgStorage"],"mappings":";;AAMO,MAAMA,sBAAsB;AAenC,MAAMC,WAAW,CAACC,QACP,AAAiB,YAAjB,OAAOA,SAAsBA,AAAU,SAAVA,SAAkB,CAACC,MAAM,OAAO,CAACD;AAGzE,MAAME,iBAAiB,CAACF,QACbD,SAASC,UAAUG,OAAO,MAAM,CAACH,OAAO,KAAK,CAACI,CAAAA,OAAQ,AAAgB,YAAhB,OAAOA;AAOjE,SAASC,sBAAsBC,MAAWC,QAAQ,GAAG;IACxD,MAAMC,MAAMF,GAAG,CAACR,oBAAoB;IACpC,IAAI,CAACU,KACD,OAAO,EAAE;IAGb,IAAIC;IACJ,IAAI;QACAA,SAASC,KAAK,KAAK,CAACF;IACxB,EAAE,OAAOG,OAAO;QACZ,MAAM,IAAIC,MACN,GAAGd,oBAAoB,mBAAmB,EAAEa,iBAAiBC,QAAQD,MAAM,OAAO,GAAGE,OAAOF,OAAO,CAAC,CAAC;IAE7G;IACA,IAAI,CAACV,MAAM,OAAO,CAACQ,SACf,MAAM,IAAIG,MAAM,GAAGd,oBAAoB,iCAAiC,CAAC;IAG7E,OAAOW,OAAO,GAAG,CAAC,CAACK,OAAOC;QACtB,MAAMC,QACFjB,SAASe,UACT,AAAoB,YAApB,OAAOA,MAAM,EAAE,IACfA,MAAM,EAAE,CAAC,MAAM,GAAG,KAClB,AAAuB,YAAvB,OAAOA,M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";
2
+ export type { CreatePgStorageParams } from "./createPgStorage.js";
3
+ export { createPgConnection } from "./createPgConnection.js";
4
+ export type { CreatePgConnectionOptions } from "./createPgConnection.js";
5
+ export { applyToPgConnectionString, pgConnectionStringPassword } from "./applyToPgConnectionString.js";
6
+ export type { PgConnectionStringValues } from "./applyToPgConnectionString.js";
7
+ export { readPgConnectionEnv, DEFAULT_PG_RETRY_MS } from "./readPgConnectionEnv.js";
8
+ export type { PgConnectionEnv } from "./readPgConnectionEnv.js";
9
+ export { createPgTenantStorages, readTenantStoragesEnv, TENANT_STORAGES_ENV } from "./createPgTenantStorages.js";
10
+ export type { CreatePgTenantStoragesParams, TenantStorageEnvEntry } from "./createPgTenantStorages.js";
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createPgStorage } from "./createPgStorage.js";
2
+ export { createPgConnection } from "./createPgConnection.js";
3
+ export { applyToPgConnectionString, pgConnectionStringPassword } from "./applyToPgConnectionString.js";
4
+ export { DEFAULT_PG_RETRY_MS, readPgConnectionEnv } from "./readPgConnectionEnv.js";
5
+ export { TENANT_STORAGES_ENV, createPgTenantStorages, readTenantStoragesEnv } from "./createPgTenantStorages.js";
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
- "name": "@webiny/api-storage-pg",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@webiny/api-storage-pg",
3
+ "version": "0.0.0-unstable.292eb6dc15",
4
+ "type": "module",
5
+ "main": "index.js",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./*": "./*"
9
+ },
10
+ "types": "index.d.ts",
11
+ "description": "EXPERIMENTAL: The Postgres SQL storage of the Webiny API and its connection, shared by every transport that runs it on Postgres.",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/webiny/webiny-js.git"
15
+ },
16
+ "contributors": [
17
+ "Webiny Team"
18
+ ],
19
+ "license": "MIT",
20
+ "dependencies": {
21
+ "@webiny/api-audit-logs-sql": "0.0.0-unstable.292eb6dc15",
22
+ "@webiny/api-core": "0.0.0-unstable.292eb6dc15",
23
+ "@webiny/api-core-sql": "0.0.0-unstable.292eb6dc15",
24
+ "@webiny/api-websockets-sql": "0.0.0-unstable.292eb6dc15",
25
+ "@webiny/stdlib": "0.0.21",
26
+ "knex": "3.3.0",
27
+ "pg": "8.23.1"
28
+ },
29
+ "peerDependencies": {
30
+ "@webiny/di": "^2.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@electric-sql/pglite": "0.5.17",
34
+ "@electric-sql/pglite-socket": "0.2.20",
35
+ "@webiny/api-audit-logs": "0.0.0-unstable.292eb6dc15",
36
+ "@webiny/api-websockets": "0.0.0-unstable.292eb6dc15",
37
+ "@webiny/build-tools": "0.0.0-unstable.292eb6dc15",
38
+ "@webiny/di": "2.0.0",
39
+ "rimraf": "6.1.4",
40
+ "typescript": "7.0.2",
41
+ "vitest": "5.1.1"
42
+ },
43
+ "adio": {
44
+ "ignore": {
45
+ "dependencies": [
46
+ "pg"
47
+ ]
48
+ }
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "webiny": {
54
+ "publishFrom": "dist"
55
+ }
56
+ }
@@ -0,0 +1,29 @@
1
+ import type { Knex } from "knex";
2
+ type Env = Record<string, string | undefined>;
3
+ /** How long a read or transaction that lost its connection is retried by default, in milliseconds. */
4
+ export declare const DEFAULT_PG_RETRY_MS = 15000;
5
+ export interface PgConnectionEnv {
6
+ /**
7
+ * The connection settings that are set in the env. Each is left out when its variable isn't set,
8
+ * so a caller's own defaults apply.
9
+ */
10
+ connection: Knex.PgConnectionConfig;
11
+ /** Pool size (`WEBINY_PG_POOL_MAX`). */
12
+ poolMax?: number;
13
+ /**
14
+ * How long to retry a read or transaction that lost its connection (`WEBINY_PG_RETRY_MS`);
15
+ * 0 turns retries off.
16
+ */
17
+ retryMs?: number;
18
+ }
19
+ /**
20
+ * The Postgres connection settings in the env, under the `WEBINY_PG_*` names `<Infra.Postgres>`
21
+ * sets. Shared by every handler that connects to Postgres (the standalone server and Lambda), so
22
+ * they read the same variables the same way.
23
+ *
24
+ * TLS is set either in `WEBINY_PG_CONNECTION_STRING` (`sslmode`, `sslrootcert`, …) or with the
25
+ * `WEBINY_PG_SSL*` variables, not both: node-postgres lets the connection string's TLS settings
26
+ * replace the others, so a private CA in `WEBINY_PG_SSL_CA` would be dropped without a word.
27
+ */
28
+ export declare function readPgConnectionEnv(env?: Env): PgConnectionEnv;
29
+ export {};
@@ -0,0 +1,81 @@
1
+ import node_fs from "node:fs";
2
+ import { toBoolean } from "@webiny/stdlib";
3
+ const CONNECTION_STRING_TLS = /[?&](ssl|sslmode|sslrootcert|sslcert|sslkey|sslnegotiation)=/i;
4
+ const TLS_VARS = [
5
+ "WEBINY_PG_SSL",
6
+ "WEBINY_PG_SSL_CA",
7
+ "WEBINY_PG_SSL_KEY",
8
+ "WEBINY_PG_SSL_CERT",
9
+ "WEBINY_PG_SSL_REJECT_UNAUTHORIZED"
10
+ ];
11
+ const DEFAULT_PG_RETRY_MS = 15000;
12
+ function readPgConnectionEnv(env = process.env) {
13
+ const envBool = (name)=>{
14
+ const value = env[name];
15
+ return value ? toBoolean(value) : void 0;
16
+ };
17
+ const envInt = (name)=>{
18
+ const value = env[name];
19
+ if (void 0 === value) return;
20
+ const n = Number(value);
21
+ return isNaN(n) ? void 0 : n;
22
+ };
23
+ const connection = {};
24
+ const host = env.WEBINY_PG_HOST;
25
+ if (host) connection.host = host;
26
+ const port = envInt("WEBINY_PG_PORT");
27
+ if (port) connection.port = port;
28
+ const user = env.WEBINY_PG_USER;
29
+ if (user) connection.user = user;
30
+ const password = env.WEBINY_PG_PASSWORD;
31
+ if (password) connection.password = password;
32
+ const database = env.WEBINY_PG_DATABASE;
33
+ if (database) connection.database = database;
34
+ const connectionString = env.WEBINY_PG_CONNECTION_STRING;
35
+ if (connectionString) {
36
+ connection.connectionString = connectionString;
37
+ const tlsVars = TLS_VARS.filter((name)=>!!env[name]);
38
+ if (CONNECTION_STRING_TLS.test(connectionString) && tlsVars.length > 0) throw new Error(`TLS is set twice: in WEBINY_PG_CONNECTION_STRING and in ${tlsVars.join(", ")}. The connection string's TLS settings would replace the others, so set TLS in one place.`);
39
+ }
40
+ const sslCa = env.WEBINY_PG_SSL_CA;
41
+ const sslKey = env.WEBINY_PG_SSL_KEY;
42
+ const sslCert = env.WEBINY_PG_SSL_CERT;
43
+ const sslRejectUnauthorized = envBool("WEBINY_PG_SSL_REJECT_UNAUTHORIZED");
44
+ if (sslCa || sslKey || sslCert || void 0 !== sslRejectUnauthorized) {
45
+ const sslConfig = {};
46
+ if (sslCa) sslConfig.ca = node_fs.readFileSync(sslCa, "utf8");
47
+ if (sslKey) sslConfig.key = node_fs.readFileSync(sslKey, "utf8");
48
+ if (sslCert) sslConfig.cert = node_fs.readFileSync(sslCert, "utf8");
49
+ if (void 0 !== sslRejectUnauthorized) sslConfig.rejectUnauthorized = sslRejectUnauthorized;
50
+ connection.ssl = sslConfig;
51
+ } else {
52
+ const ssl = envBool("WEBINY_PG_SSL");
53
+ if (void 0 !== ssl) connection.ssl = ssl;
54
+ }
55
+ const applicationName = env.WEBINY_PG_APPLICATION_NAME;
56
+ if (applicationName) connection.application_name = applicationName;
57
+ const connectionTimeoutMillis = envInt("WEBINY_PG_CONNECTION_TIMEOUT_MILLIS");
58
+ if (void 0 !== connectionTimeoutMillis) connection.connectionTimeoutMillis = connectionTimeoutMillis;
59
+ const statementTimeout = envInt("WEBINY_PG_STATEMENT_TIMEOUT");
60
+ if (void 0 !== statementTimeout) connection.statement_timeout = statementTimeout;
61
+ const queryTimeout = envInt("WEBINY_PG_QUERY_TIMEOUT");
62
+ if (void 0 !== queryTimeout) connection.query_timeout = queryTimeout;
63
+ const idleInTransactionSessionTimeout = envInt("WEBINY_PG_IDLE_IN_TRANSACTION_SESSION_TIMEOUT");
64
+ if (void 0 !== idleInTransactionSessionTimeout) connection.idle_in_transaction_session_timeout = idleInTransactionSessionTimeout;
65
+ const parseInputDatesAsUTC = envBool("WEBINY_PG_PARSE_INPUT_DATES_AS_UTC");
66
+ if (void 0 !== parseInputDatesAsUTC) connection.parseInputDatesAsUTC = parseInputDatesAsUTC;
67
+ const pgOptions = env.WEBINY_PG_OPTIONS;
68
+ if (pgOptions) connection.options = pgOptions;
69
+ const keepAlive = envBool("WEBINY_PG_KEEP_ALIVE");
70
+ if (void 0 !== keepAlive) connection.keepAlive = keepAlive;
71
+ const keepAliveInitialDelayMillis = envInt("WEBINY_PG_KEEP_ALIVE_INITIAL_DELAY_MILLIS");
72
+ if (void 0 !== keepAliveInitialDelayMillis) connection.keepAliveInitialDelayMillis = keepAliveInitialDelayMillis;
73
+ return {
74
+ connection,
75
+ poolMax: envInt("WEBINY_PG_POOL_MAX"),
76
+ retryMs: envInt("WEBINY_PG_RETRY_MS")
77
+ };
78
+ }
79
+ export { DEFAULT_PG_RETRY_MS, readPgConnectionEnv };
80
+
81
+ //# sourceMappingURL=readPgConnectionEnv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readPgConnectionEnv.js","sources":["../src/readPgConnectionEnv.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { Knex } from \"knex\";\nimport type { ConnectionOptions } from \"node:tls\";\nimport { toBoolean } from \"@webiny/stdlib\";\n\ntype Env = Record<string, string | undefined>;\n\n/*\n * The connection string's own TLS parameters (node-postgres reads these from it).\n * `sslnegotiation=direct` turns TLS on by itself.\n */\nconst CONNECTION_STRING_TLS = /[?&](ssl|sslmode|sslrootcert|sslcert|sslkey|sslnegotiation)=/i;\n\nconst TLS_VARS = [\n \"WEBINY_PG_SSL\",\n \"WEBINY_PG_SSL_CA\",\n \"WEBINY_PG_SSL_KEY\",\n \"WEBINY_PG_SSL_CERT\",\n \"WEBINY_PG_SSL_REJECT_UNAUTHORIZED\"\n];\n\n/** How long a read or transaction that lost its connection is retried by default, in milliseconds. */\nexport const DEFAULT_PG_RETRY_MS = 15_000;\n\nexport interface PgConnectionEnv {\n /**\n * The connection settings that are set in the env. Each is left out when its variable isn't set,\n * so a caller's own defaults apply.\n */\n connection: Knex.PgConnectionConfig;\n /** Pool size (`WEBINY_PG_POOL_MAX`). */\n poolMax?: number;\n /**\n * How long to retry a read or transaction that lost its connection (`WEBINY_PG_RETRY_MS`);\n * 0 turns retries off.\n */\n retryMs?: number;\n}\n\n/**\n * The Postgres connection settings in the env, under the `WEBINY_PG_*` names `<Infra.Postgres>`\n * sets. Shared by every handler that connects to Postgres (the standalone server and Lambda), so\n * they read the same variables the same way.\n *\n * TLS is set either in `WEBINY_PG_CONNECTION_STRING` (`sslmode`, `sslrootcert`, …) or with the\n * `WEBINY_PG_SSL*` variables, not both: node-postgres lets the connection string's TLS settings\n * replace the others, so a private CA in `WEBINY_PG_SSL_CA` would be dropped without a word.\n */\nexport function readPgConnectionEnv(env: Env = process.env): PgConnectionEnv {\n const envBool = (name: string): boolean | undefined => {\n const value = env[name];\n // Only convert when the var is actually set β€” an unset (or empty) var must stay `undefined`,\n // not become `false`. Callers rely on the `undefined` distinction (e.g. the SSL config is\n // only applied when a WEBINY_PG_SSL* var is explicitly present); returning `false` for unset\n // would always trigger it. Deploy tooling often exports unused vars as \"\", so \"\" is unset.\n return value ? toBoolean(value) : undefined;\n };\n\n const envInt = (name: string): number | undefined => {\n const value = env[name];\n if (value === undefined) {\n return undefined;\n }\n const n = Number(value);\n return isNaN(n) ? undefined : n;\n };\n\n const connection: Knex.PgConnectionConfig = {};\n\n const host = env.WEBINY_PG_HOST;\n if (host) {\n connection.host = host;\n }\n const port = envInt(\"WEBINY_PG_PORT\");\n if (port) {\n connection.port = port;\n }\n const user = env.WEBINY_PG_USER;\n if (user) {\n connection.user = user;\n }\n const password = env.WEBINY_PG_PASSWORD;\n if (password) {\n connection.password = password;\n }\n const database = env.WEBINY_PG_DATABASE;\n if (database) {\n connection.database = database;\n }\n\n const connectionString = env.WEBINY_PG_CONNECTION_STRING;\n if (connectionString) {\n connection.connectionString = connectionString;\n // An empty var configures nothing below, so it doesn't count as setting TLS.\n const tlsVars = TLS_VARS.filter(name => !!env[name]);\n if (CONNECTION_STRING_TLS.test(connectionString) && tlsVars.length > 0) {\n throw new Error(\n `TLS is set twice: in WEBINY_PG_CONNECTION_STRING and in ${tlsVars.join(\", \")}. ` +\n \"The connection string's TLS settings would replace the others, so set TLS in one place.\"\n );\n }\n }\n\n const sslCa = env.WEBINY_PG_SSL_CA;\n const sslKey = env.WEBINY_PG_SSL_KEY;\n const sslCert = env.WEBINY_PG_SSL_CERT;\n const sslRejectUnauthorized = envBool(\"WEBINY_PG_SSL_REJECT_UNAUTHORIZED\");\n\n if (sslCa || sslKey || sslCert || sslRejectUnauthorized !== undefined) {\n const sslConfig: ConnectionOptions = {};\n if (sslCa) {\n sslConfig.ca = fs.readFileSync(sslCa, \"utf8\");\n }\n if (sslKey) {\n sslConfig.key = fs.readFileSync(sslKey, \"utf8\");\n }\n if (sslCert) {\n sslConfig.cert = fs.readFileSync(sslCert, \"utf8\");\n }\n if (sslRejectUnauthorized !== undefined) {\n sslConfig.rejectUnauthorized = sslRejectUnauthorized;\n }\n connection.ssl = sslConfig;\n } else {\n const ssl = envBool(\"WEBINY_PG_SSL\");\n if (ssl !== undefined) {\n connection.ssl = ssl;\n }\n }\n\n const applicationName = env.WEBINY_PG_APPLICATION_NAME;\n if (applicationName) {\n connection.application_name = applicationName;\n }\n\n const connectionTimeoutMillis = envInt(\"WEBINY_PG_CONNECTION_TIMEOUT_MILLIS\");\n if (connectionTimeoutMillis !== undefined) {\n connection.connectionTimeoutMillis = connectionTimeoutMillis;\n }\n\n const statementTimeout = envInt(\"WEBINY_PG_STATEMENT_TIMEOUT\");\n if (statementTimeout !== undefined) {\n connection.statement_timeout = statementTimeout;\n }\n\n const queryTimeout = envInt(\"WEBINY_PG_QUERY_TIMEOUT\");\n if (queryTimeout !== undefined) {\n connection.query_timeout = queryTimeout;\n }\n\n const idleInTransactionSessionTimeout = envInt(\"WEBINY_PG_IDLE_IN_TRANSACTION_SESSION_TIMEOUT\");\n if (idleInTransactionSessionTimeout !== undefined) {\n connection.idle_in_transaction_session_timeout = idleInTransactionSessionTimeout;\n }\n\n const parseInputDatesAsUTC = envBool(\"WEBINY_PG_PARSE_INPUT_DATES_AS_UTC\");\n if (parseInputDatesAsUTC !== undefined) {\n connection.parseInputDatesAsUTC = parseInputDatesAsUTC;\n }\n\n const pgOptions = env.WEBINY_PG_OPTIONS;\n if (pgOptions) {\n connection.options = pgOptions;\n }\n\n const keepAlive = envBool(\"WEBINY_PG_KEEP_ALIVE\");\n if (keepAlive !== undefined) {\n connection.keepAlive = keepAlive;\n }\n\n const keepAliveInitialDelayMillis = envInt(\"WEBINY_PG_KEEP_ALIVE_INITIAL_DELAY_MILLIS\");\n if (keepAliveInitialDelayMillis !== undefined) {\n connection.keepAliveInitialDelayMillis = keepAliveInitialDelayMillis;\n }\n\n return {\n connection,\n // A database that serves one connection at a time (`<Infra.Pglite>`) sets the pool size.\n poolMax: envInt(\"WEBINY_PG_POOL_MAX\"),\n retryMs: envInt(\"WEBINY_PG_RETRY_MS\")\n };\n}\n"],"names":["CONNECTION_STRING_TLS","TLS_VARS","DEFAULT_PG_RETRY_MS","readPgConnectionEnv","env","process","envBool","name","value","toBoolean","undefined","envInt","n","Number","isNaN","connection","host","port","user","password","database","connectionString","tlsVars","Error","sslCa","sslKey","sslCert","sslRejectUnauthorized","sslConfig","fs","ssl","applicationName","connectionTimeoutMillis","statementTimeout","queryTimeout","idleInTransactionSessionTimeout","parseInputDatesAsUTC","pgOptions","keepAlive","keepAliveInitialDelayMillis"],"mappings":";;AAWA,MAAMA,wBAAwB;AAE9B,MAAMC,WAAW;IACb;IACA;IACA;IACA;IACA;CACH;AAGM,MAAMC,sBAAsB;AA0B5B,SAASC,oBAAoBC,MAAWC,QAAQ,GAAG;IACtD,MAAMC,UAAU,CAACC;QACb,MAAMC,QAAQJ,GAAG,CAACG,KAAK;QAKvB,OAAOC,QAAQC,UAAUD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