@softistx/janus-kit 0.0.0-stage → 0.6.15

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.
@@ -0,0 +1,115 @@
1
+ import {
2
+ checkShared,
3
+ checkObject,
4
+ oneOf,
5
+ nonEmpty,
6
+ timed,
7
+ assembleKit
8
+ } from "../chunks/index-vw036wd3.js";
9
+
10
+ // src/drizzle/config.ts
11
+ var postgresDatabase = {
12
+ key: "postgres",
13
+ label: "PostgreSQL"
14
+ };
15
+ function defineConfig(config) {
16
+ checkConfig(config, "defineConfig");
17
+ return Object.freeze({ ...config });
18
+ }
19
+ function checkConfig(config, where) {
20
+ checkObject(config, where);
21
+ const { postgres } = config;
22
+ if (typeof postgres !== "object" || postgres === null) {
23
+ throw new TypeError(`${where}: \`postgres\` is required — { url } of Janus's database, or { db }, a Drizzle instance you opened.`);
24
+ }
25
+ oneOf(where, "postgres", postgres, "url", "db");
26
+ if (postgres.url !== undefined) {
27
+ nonEmpty(where, "postgres.url", postgres.url);
28
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(postgres.url)?.[1];
29
+ if (scheme !== "postgres" && scheme !== "postgresql") {
30
+ throw new TypeError(`${where}: \`postgres.url\` is a postgres:// or postgresql:// URL${scheme === undefined ? "" : `, not ${scheme}://`}.`);
31
+ }
32
+ }
33
+ if (config.apiKeys === true && postgres.tables !== undefined && postgres.tables.apiKeys === undefined) {
34
+ throw new TypeError(`${where}: \`apiKeys: true\` needs the \`apiKeys\` table in \`postgres.tables\` — export it from your schema file with defineJanusTables().`);
35
+ }
36
+ checkShared(config, where, postgresDatabase);
37
+ }
38
+ // src/drizzle/connect.ts
39
+ import {
40
+ createDrizzleAdapter,
41
+ createDrizzleApiKeys,
42
+ defineJanusTables
43
+ } from "@softistx/janus-drizzle";
44
+ import { SQL } from "bun";
45
+ import { sql } from "drizzle-orm";
46
+ import { drizzle } from "drizzle-orm/bun-sql";
47
+ import { getTableConfig } from "drizzle-orm/pg-core";
48
+ async function connectKit(config) {
49
+ checkConfig(config, "connectKit");
50
+ return await assembleKit(config, async (closers) => {
51
+ const { db, opened } = openPostgres(config.postgres, closers);
52
+ const {
53
+ socialLinks: _,
54
+ passkeys: __,
55
+ invitations: ___,
56
+ apiKeys,
57
+ ...core
58
+ } = defineJanusTables();
59
+ const withApiKeys = config.apiKeys === true;
60
+ const tables = config.postgres.tables ?? core;
61
+ const {
62
+ invitations: ____,
63
+ apiKeys: ______,
64
+ ...checked
65
+ } = tables;
66
+ const apiKeysTable = withApiKeys ? tables.apiKeys ?? apiKeys : undefined;
67
+ await assertTables(db, apiKeysTable === undefined ? checked : { ...checked, apiKeys: apiKeysTable }, opened);
68
+ const { store, relations } = createDrizzleAdapter(db, { tables });
69
+ return {
70
+ database: postgresDatabase,
71
+ db,
72
+ store,
73
+ relations,
74
+ ...apiKeysTable === undefined ? {} : {
75
+ apiKeyStore: createDrizzleApiKeys(db, {
76
+ tables: { apiKeys: apiKeysTable }
77
+ })
78
+ },
79
+ probe: (timeoutMs) => timed(() => db.execute(sql`select 1`), timeoutMs)
80
+ };
81
+ });
82
+ }
83
+ function openPostgres(postgres, closers) {
84
+ if (postgres.url === undefined)
85
+ return { db: postgres.db, opened: false };
86
+ const client = new SQL(postgres.url);
87
+ closers.push(() => client.close());
88
+ return { db: drizzle({ client }), opened: true };
89
+ }
90
+ async function assertTables(db, tables, opened) {
91
+ const names = Object.values(tables).map((table) => {
92
+ const { name, schema } = getTableConfig(table);
93
+ return schema === undefined ? quoted(name) : `${quoted(schema)}.${quoted(name)}`;
94
+ });
95
+ let reply;
96
+ try {
97
+ reply = await db.execute(sql`select name from unnest(array[${sql.join(names.map((name) => sql`${name}`), sql`, `)}]::text[]) as name where to_regclass(name) is null`);
98
+ } catch (cause) {
99
+ throw new Error(opened ? "connectKit: PostgreSQL did not answer. Check `postgres.url`, and that the database exists." : "connectKit: the Drizzle instance in `postgres.db` did not answer.", { cause });
100
+ }
101
+ const rows = Array.isArray(reply) ? reply : reply.rows;
102
+ if (rows.length > 0) {
103
+ throw new Error(`connectKit: Janus's tables are missing from this database: ${rows.map((row) => row.name).join(", ")}. Apply the migration drizzle-kit generated from defineJanusTables(), to the database \`postgres\` names.`);
104
+ }
105
+ }
106
+ function quoted(identifier) {
107
+ return `"${identifier.replaceAll('"', '""')}"`;
108
+ }
109
+ export {
110
+ connectKit,
111
+ defineConfig
112
+ };
113
+
114
+ //# debugId=1DEB311A5B65749564756E2164756E21
115
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/drizzle/config.ts", "../src/drizzle/connect.ts"],
4
+ "sourcesContent": [
5
+ "import type { PgDatabase } from '@softistx/drizzle/pg';\nimport type { DrizzleAdapterOptions } from '@softistx/janus-drizzle';\nimport {\n\tcheckObject,\n\tcheckShared,\n\ttype Database,\n\tnonEmpty,\n\toneOf,\n\ttype SharedConfig,\n\ttype UncheckedShared,\n} from '../shared/config';\n\n/** PostgreSQL, as `ping` and the messages name it. */\nexport const postgresDatabase: Database<'postgres'> = {\n\tkey: 'postgres',\n\tlabel: 'PostgreSQL',\n};\n\n/**\n * Where users, logins, relations — and sessions and tokens, unless Redis\n * holds them — are kept. **The URL of a database of Janus's own**, which the\n * kit opens over Bun's `SQL` and closes; or a Drizzle instance you opened,\n * which it never closes.\n */\nexport type PostgresConfig =\n\t| {\n\t\t\treadonly url: string;\n\t\t\treadonly db?: never;\n\t\t\t/** What your schema file exports, when the tables are in a PostgreSQL schema of their own. */\n\t\t\treadonly tables?: DrizzleAdapterOptions['tables'];\n\t }\n\t| {\n\t\t\treadonly db: PgDatabase;\n\t\t\treadonly url?: never;\n\t\t\treadonly tables?: DrizzleAdapterOptions['tables'];\n\t };\n\n/** The kit's configuration over PostgreSQL: `postgres`, then the shared keys. */\nexport interface KitConfig<\n\tA extends object,\n\tP extends object,\n\tWithApiKeys extends boolean = false,\n> extends SharedConfig<A, P, WithApiKeys> {\n\treadonly postgres: PostgresConfig;\n}\n\n/**\n * The configuration, **checked once, where the application starts**. It\n * connects to nothing and reads no environment variable: write\n * `process.env.JANUS_DATABASE_URL!` where your other settings are read.\n *\n * ```ts\n * export const config = defineConfig({\n * postgres: { url: process.env.JANUS_DATABASE_URL! },\n * redis: { url: process.env.REDIS_URL! },\n * auth: (adapters) => janus({ user, password: { login: 'email' }, hasher: scryptHasher(), ...adapters }),\n * });\n * ```\n */\nexport function defineConfig<\n\tA extends object,\n\tP extends object = never,\n\tconst WithApiKeys extends boolean = false,\n>(config: KitConfig<A, P, WithApiKeys>): KitConfig<A, P, WithApiKeys> {\n\tcheckConfig(config, 'defineConfig');\n\treturn Object.freeze({ ...config });\n}\n\n/**\n * The checks, run by `defineConfig` and again by `connectKit`: a configuration\n * is often built in one file and connected in another, and one that skipped\n * `defineConfig` must not reach Bun's `SQL`, which reads `DATABASE_URL` for a\n * missing URL.\n */\nexport function checkConfig(\n\tconfig: UncheckedShared & { readonly postgres: PostgresConfig },\n\twhere: string,\n): void {\n\tcheckObject(config, where);\n\tconst { postgres } = config;\n\tif (typeof postgres !== 'object' || postgres === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`postgres\\` is required — { url } of Janus's database, or { db }, a Drizzle instance you opened.`,\n\t\t);\n\t}\n\toneOf(where, 'postgres', postgres, 'url', 'db');\n\tif (postgres.url !== undefined) {\n\t\tnonEmpty(where, 'postgres.url', postgres.url);\n\t\t// Bun's `SQL` picks its driver from the scheme: `mysql://` and\n\t\t// `sqlite://` open another database. Only the scheme is named: the\n\t\t// URL may hold a password.\n\t\tconst scheme = /^([a-z][a-z0-9+.-]*):/i.exec(postgres.url)?.[1];\n\t\tif (scheme !== 'postgres' && scheme !== 'postgresql') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: \\`postgres.url\\` is a postgres:// or postgresql:// URL${scheme === undefined ? '' : `, not ${scheme}://`}.`,\n\t\t\t);\n\t\t}\n\t}\n\tif (\n\t\tconfig.apiKeys === true &&\n\t\tpostgres.tables !== undefined &&\n\t\t(postgres.tables as { apiKeys?: unknown }).apiKeys === undefined\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`apiKeys: true\\` needs the \\`apiKeys\\` table in \\`postgres.tables\\` — export it from your schema file with defineJanusTables().`,\n\t\t);\n\t}\n\tcheckShared(config, where, postgresDatabase);\n}\n",
6
+ "import type { PgDatabase } from '@softistx/drizzle/pg';\nimport {\n\tcreateDrizzleAdapter,\n\tcreateDrizzleApiKeys,\n\tdefineJanusTables,\n\ttype JanusTables,\n} from '@softistx/janus-drizzle';\nimport { SQL } from 'bun';\nimport { sql } from 'drizzle-orm';\nimport { drizzle } from 'drizzle-orm/bun-sql';\nimport { getTableConfig } from 'drizzle-orm/pg-core';\nimport type { HealthOf } from '../shared/health';\nimport { timed } from '../shared/health';\nimport { assembleKit, type Closers, type KitOf } from '../shared/kit';\nimport {\n\tcheckConfig,\n\ttype KitConfig,\n\ttype PostgresConfig,\n\tpostgresDatabase,\n} from './config';\n\n/** What `ping` answers: `{ ok, postgres, redis? }`. */\nexport type Health = HealthOf<'postgres'>;\n\n/** What `connectKit` answers: `auth`, `access` when configured, and the rest. */\nexport type Kit<A extends object, P extends object> = KitOf<\n\tA,\n\tP,\n\tPgDatabase,\n\t'postgres'\n>;\n\n/**\n * Opens the connections, checks that Janus's tables are there, and builds\n * `auth` and `access` over them.\n *\n * ```ts\n * export const kit = await connectKit(config);\n * const current = await kit.auth.authenticate(request);\n * await kit.close(); // or `await using kit = await connectKit(config)`\n * ```\n *\n * **It fails here, not at the first sign-in**: a database that does not\n * answer, or one without the tables your migrations create, rejects with an\n * `Error` naming what to do, after closing whatever it had opened.\n */\nexport async function connectKit<\n\tA extends object,\n\tP extends object = never,\n\tconst WithApiKeys extends boolean = false,\n>(config: KitConfig<A, P, WithApiKeys>): Promise<Kit<A, P>> {\n\tcheckConfig(config, 'connectKit');\n\treturn await assembleKit(config, async (closers) => {\n\t\tconst { db, opened } = openPostgres(config.postgres, closers);\n\t\t// Without `tables`, the five tables every setup has: `social_links`\n\t\t// and `passkeys` are checked and wired only when the application's\n\t\t// tables define them. `invitations` is never checked (no invitation\n\t\t// store is wired); `api_keys` is checked and wired only with\n\t\t// `apiKeys: true`.\n\t\tconst {\n\t\t\tsocialLinks: _,\n\t\t\tpasskeys: __,\n\t\t\tinvitations: ___,\n\t\t\tapiKeys,\n\t\t\t...core\n\t\t} = defineJanusTables();\n\t\tconst withApiKeys = config.apiKeys === true;\n\t\tconst tables = config.postgres.tables ?? core;\n\t\tconst {\n\t\t\tinvitations: ____,\n\t\t\tapiKeys: ______,\n\t\t\t...checked\n\t\t}: Partial<JanusTables> = tables;\n\t\t// With `apiKeys: true`, the table the application gave, else the default.\n\t\tconst apiKeysTable = withApiKeys\n\t\t\t? ((tables as Partial<JanusTables>).apiKeys ?? apiKeys)\n\t\t\t: undefined;\n\t\tawait assertTables(\n\t\t\tdb,\n\t\t\tapiKeysTable === undefined\n\t\t\t\t? checked\n\t\t\t\t: { ...checked, apiKeys: apiKeysTable },\n\t\t\topened,\n\t\t);\n\t\tconst { store, relations } = createDrizzleAdapter(db, { tables });\n\t\treturn {\n\t\t\tdatabase: postgresDatabase,\n\t\t\tdb,\n\t\t\tstore,\n\t\t\trelations,\n\t\t\t...(apiKeysTable === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tapiKeyStore: createDrizzleApiKeys(db, {\n\t\t\t\t\t\t\ttables: { apiKeys: apiKeysTable },\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\tprobe: (timeoutMs) => timed(() => db.execute(sql`select 1`), timeoutMs),\n\t\t};\n\t});\n}\n\nfunction openPostgres(\n\tpostgres: PostgresConfig,\n\tclosers: Closers,\n): { db: PgDatabase; opened: boolean } {\n\tif (postgres.url === undefined) return { db: postgres.db, opened: false };\n\tconst client = new SQL(postgres.url);\n\tclosers.push(() => client.close());\n\treturn { db: drizzle({ client }) as unknown as PgDatabase, opened: true };\n}\n\n/**\n * Every table the stores query, by the name the configuration gives it. A\n * missing one is the most likely first-run mistake — migrations not applied,\n * or applied to another database — and would otherwise surface as the first\n * sign-up's `STORE_FAILED`.\n */\nasync function assertTables(\n\tdb: PgDatabase,\n\ttables: Partial<JanusTables>,\n\topened: boolean,\n) {\n\tconst names = Object.values(tables).map((table) => {\n\t\tconst { name, schema } = getTableConfig(table);\n\t\treturn schema === undefined\n\t\t\t? quoted(name)\n\t\t\t: `${quoted(schema)}.${quoted(name)}`;\n\t});\n\tlet reply: unknown;\n\ttry {\n\t\treply = await db.execute(\n\t\t\tsql`select name from unnest(array[${sql.join(\n\t\t\t\tnames.map((name) => sql`${name}`),\n\t\t\t\tsql`, `,\n\t\t\t)}]::text[]) as name where to_regclass(name) is null`,\n\t\t);\n\t} catch (cause) {\n\t\tthrow new Error(\n\t\t\topened\n\t\t\t\t? 'connectKit: PostgreSQL did not answer. Check `postgres.url`, and that the database exists.'\n\t\t\t\t: 'connectKit: the Drizzle instance in `postgres.db` did not answer.',\n\t\t\t{ cause },\n\t\t);\n\t}\n\tconst rows = (\n\t\tArray.isArray(reply) ? reply : (reply as { rows: unknown[] }).rows\n\t) as { name: string }[];\n\tif (rows.length > 0) {\n\t\tthrow new Error(\n\t\t\t`connectKit: Janus's tables are missing from this database: ${rows\n\t\t\t\t.map((row) => row.name)\n\t\t\t\t.join(\n\t\t\t\t\t', ',\n\t\t\t\t)}. Apply the migration drizzle-kit generated from defineJanusTables(), to the database \\`postgres\\` names.`,\n\t\t);\n\t}\n}\n\n/** A PostgreSQL identifier, quoted as `to_regclass` reads it. */\nfunction quoted(identifier: string): string {\n\treturn `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;;AAaO,IAAM,mBAAyC;AAAA,EACrD,KAAK;AAAA,EACL,OAAO;AACR;AA2CO,SAAS,YAIf,CAAC,QAAoE;AAAA,EACrE,YAAY,QAAQ,cAAc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,+FACA,qEACH,EAAE,MAAM,CACT;AAAA;AAAA,EAED,MAAM,OACL,MAAM,QAAQ,KAAK,IAAI,QAAS,MAA8B;AAAA,EAE/D,IAAI,KAAK,SAAS,GAAG;AAAA,IACpB,MAAM,IAAI,MACT,8DAA8D,KAC5D,IAAI,CAAC,QAAQ,IAAI,IAAI,EACrB,KACA,IACD,4GACF;AAAA,EACD;AAAA;AAID,SAAS,MAAM,CAAC,YAA4B;AAAA,EAC3C,OAAO,IAAI,WAAW,WAAW,KAAK,IAAI;AAAA;",
9
+ "debugId": "1DEB311A5B65749564756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,45 @@
1
+ import type { Db, MongoClientOptions } from 'mongodb';
2
+ import { type Database, type SharedConfig, type UncheckedShared } from '../shared/config';
3
+ /** MongoDB, as `ping` and the messages name it. */
4
+ export declare const mongoDatabase: Database<'mongo'>;
5
+ /**
6
+ * Where users, relations — and sessions and tokens, unless Redis holds them —
7
+ * are kept. **The URL of a database of Janus's own**, its path naming the
8
+ * database, which the kit opens with `@softistx/mongo`'s `connectMongo` and
9
+ * closes; or a `Db` you opened, which it never closes.
10
+ */
11
+ export type MongoConfig = {
12
+ readonly url: string;
13
+ readonly db?: never;
14
+ /** The driver's options, over the kit's `{ serverSelectionTimeoutMS: 5_000 }`. */
15
+ readonly clientOptions?: MongoClientOptions;
16
+ } | {
17
+ readonly db: Db;
18
+ readonly url?: never;
19
+ readonly clientOptions?: never;
20
+ };
21
+ /** The kit's configuration over MongoDB: `mongo`, then the shared keys. */
22
+ export interface KitConfig<A extends object, P extends object, WithApiKeys extends boolean = false> extends SharedConfig<A, P, WithApiKeys> {
23
+ readonly mongo: MongoConfig;
24
+ }
25
+ /**
26
+ * The configuration, **checked once, where the application starts**. It
27
+ * connects to nothing and reads no environment variable.
28
+ *
29
+ * ```ts
30
+ * export const config = defineConfig({
31
+ * mongo: { url: process.env.JANUS_MONGO_URL! },
32
+ * redis: { url: process.env.REDIS_URL! },
33
+ * auth: (adapters) => janus({ user, password: { login: 'email' }, hasher: scryptHasher(), ...adapters }),
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function defineConfig<A extends object, P extends object = never, const WithApiKeys extends boolean = false>(config: KitConfig<A, P, WithApiKeys>): KitConfig<A, P, WithApiKeys>;
38
+ /**
39
+ * The checks, run by `defineConfig` and again by `connectKit`: a configuration
40
+ * is often built in one file and connected in another.
41
+ */
42
+ export declare function checkConfig(config: UncheckedShared & {
43
+ readonly mongo: MongoConfig;
44
+ }, where: string): void;
45
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/mongo/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,EAGN,KAAK,QAAQ,EAGb,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,MAAM,kBAAkB,CAAC;AAE1B,mDAAmD;AACnD,eAAO,MAAM,aAAa,EAAE,QAAQ,CAAC,OAAO,CAG3C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACpB;IACA,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC;IACpB,kFAAkF;IAClF,QAAQ,CAAC,aAAa,CAAC,EAAE,kBAAkB,CAAC;CAC3C,GACD;IACA,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC;IAChB,QAAQ,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,aAAa,CAAC,EAAE,KAAK,CAAC;CAC9B,CAAC;AAEL,2EAA2E;AAC3E,MAAM,WAAW,SAAS,CACzB,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,EAChB,WAAW,SAAS,OAAO,GAAG,KAAK,CAClC,SAAQ,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;CAC5B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,YAAY,CAC3B,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,GAAG,KAAK,EACxB,KAAK,CAAC,WAAW,SAAS,OAAO,GAAG,KAAK,EACxC,MAAM,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,GAAG,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,CAGpE;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAC1B,MAAM,EAAE,eAAe,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAA;CAAE,EACzD,KAAK,EAAE,MAAM,GACX,IAAI,CAyBN"}
@@ -0,0 +1,26 @@
1
+ import { type Db } from 'mongodb';
2
+ import type { HealthOf } from '../shared/health';
3
+ import { type KitOf } from '../shared/kit';
4
+ import { type KitConfig } from './config';
5
+ /** What `ping` answers: `{ ok, mongo, redis? }`. */
6
+ export type Health = HealthOf<'mongo'>;
7
+ /** What `connectKit` answers: `auth`, `access` when configured, and the rest. */
8
+ export type Kit<A extends object, P extends object> = KitOf<A, P, Db, 'mongo'>;
9
+ /**
10
+ * Opens the connections, checks that Janus's collections are in sync, and
11
+ * builds `auth` and `access` over them.
12
+ *
13
+ * ```ts
14
+ * export const kit = await connectKit(config);
15
+ * const current = await kit.auth.authenticate(request);
16
+ * await kit.close(); // or `await using kit = await connectKit(config)`
17
+ * ```
18
+ *
19
+ * **It fails here, not at the first sign-in**: a MongoDB that does not
20
+ * answer, or a collection or index `syncMongoAdapter` has not created,
21
+ * rejects with an `Error` naming what to do — a URL the driver cannot read,
22
+ * with a `TypeError` — after closing whatever it had opened. Collections that
23
+ * only differ from these definitions start, with a process warning.
24
+ */
25
+ export declare function connectKit<A extends object, P extends object = never, const WithApiKeys extends boolean = false>(config: KitConfig<A, P, WithApiKeys>): Promise<Kit<A, P>>;
26
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/mongo/connect.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,EAAE,EAAqB,MAAM,SAAS,CAAC;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAA6B,KAAK,KAAK,EAAE,MAAM,eAAe,CAAC;AAEtE,OAAO,EAEN,KAAK,SAAS,EAGd,MAAM,UAAU,CAAC;AAElB,oDAAoD;AACpD,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;AAEvC,iFAAiF;AACjF,MAAM,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;AAE/E;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,UAAU,CAC/B,CAAC,SAAS,MAAM,EAChB,CAAC,SAAS,MAAM,GAAG,KAAK,EACxB,KAAK,CAAC,WAAW,SAAS,OAAO,GAAG,KAAK,EACxC,MAAM,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAgB1D"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@softistx/janus-kit/mongo` — `@softistx/janus` wired in one call, over MongoDB
3
+ * through `@softistx/janus-mongo`.
4
+ *
5
+ * `defineConfig` checks where MongoDB and Redis are, and holds the two
6
+ * functions that build `auth` and `access`; `connectKit` opens the
7
+ * connections, checks that Janus's collections are in sync, and answers
8
+ * `{ auth, access, db, redis, ping, close }`. It defines **no error class**:
9
+ * a refusal of the configuration is a `TypeError`, a database that cannot be
10
+ * reached an `Error` with its `cause`.
11
+ */
12
+ export type { AccessWiring, Adapters, KitApiKeyStore, RedisConfig, } from '../shared/config';
13
+ export type { PingResult } from '../shared/health';
14
+ export { defineConfig, type KitConfig, type MongoConfig } from './config';
15
+ export { connectKit, type Health, type Kit } from './connect';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mongo/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,YAAY,EACX,YAAY,EACZ,QAAQ,EACR,cAAc,EACd,WAAW,GACX,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,KAAK,MAAM,EAAE,KAAK,GAAG,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,134 @@
1
+ import {
2
+ checkShared,
3
+ checkObject,
4
+ oneOf,
5
+ nonEmpty,
6
+ timed,
7
+ isUriConflict,
8
+ assembleKit
9
+ } from "../chunks/index-vw036wd3.js";
10
+
11
+ // src/mongo/config.ts
12
+ var mongoDatabase = {
13
+ key: "mongo",
14
+ label: "MongoDB"
15
+ };
16
+ function defineConfig(config) {
17
+ checkConfig(config, "defineConfig");
18
+ return Object.freeze({ ...config });
19
+ }
20
+ function checkConfig(config, where) {
21
+ checkObject(config, where);
22
+ const { mongo } = config;
23
+ if (typeof mongo !== "object" || mongo === null) {
24
+ throw new TypeError(`${where}: \`mongo\` is required — { url } of Janus's database, or { db }, a Db you opened.`);
25
+ }
26
+ oneOf(where, "mongo", mongo, "url", "db");
27
+ if (mongo.url !== undefined) {
28
+ nonEmpty(where, "mongo.url", mongo.url);
29
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(mongo.url)?.[1];
30
+ if (scheme !== "mongodb" && scheme !== "mongodb+srv") {
31
+ throw new TypeError(`${where}: \`mongo.url\` is a mongodb:// or mongodb+srv:// URL${scheme === undefined ? "" : `, not ${scheme}://`}.`);
32
+ }
33
+ }
34
+ if (mongo.db !== undefined && mongo.clientOptions !== undefined) {
35
+ throw new TypeError(`${where}: \`mongo.clientOptions\` beside \`mongo.db\` — its client is already open with its own. Pass the options where you opened it.`);
36
+ }
37
+ checkShared(config, where, mongoDatabase);
38
+ }
39
+ // src/mongo/connect.ts
40
+ import {
41
+ createMongoAdapter,
42
+ createMongoApiKeys,
43
+ syncMongoAdapter,
44
+ syncMongoApiKeys
45
+ } from "@softistx/janus-mongo";
46
+ import { connectMongo } from "@softistx/mongo";
47
+ import { MongoRuntimeError } from "mongodb";
48
+ async function connectKit(config) {
49
+ checkConfig(config, "connectKit");
50
+ return await assembleKit(config, async (closers) => {
51
+ const { db, opened } = await openMongo(config.mongo, closers);
52
+ const withApiKeys = config.apiKeys === true;
53
+ await assertSynced(db, opened, withApiKeys);
54
+ const { store, relations } = createMongoAdapter(db);
55
+ return {
56
+ database: mongoDatabase,
57
+ db,
58
+ store,
59
+ relations,
60
+ ...withApiKeys ? { apiKeyStore: createMongoApiKeys(db) } : {},
61
+ probe: (timeoutMs) => timed(() => db.command({ ping: 1 }), timeoutMs)
62
+ };
63
+ });
64
+ }
65
+ async function openMongo(mongo, closers) {
66
+ if (mongo.url === undefined)
67
+ return { db: mongo.db, opened: false };
68
+ const connection = await connectMongo(mongo.url, {
69
+ serverSelectionTimeoutMS: 5000,
70
+ ...mongo.clientOptions
71
+ }).catch((cause) => {
72
+ if (cause instanceof TypeError || isUriConflict(cause))
73
+ throw cause;
74
+ if (cause instanceof MongoRuntimeError || cause instanceof Error && cause.name === "MongoParseError") {
75
+ throw new TypeError("connectKit: `mongo.url` is not a connection string the driver can read.", { cause });
76
+ }
77
+ throw new Error("connectKit: MongoDB did not answer. Check `mongo.url`, and that the server is reachable.", { cause });
78
+ });
79
+ closers.push(() => connection.close());
80
+ return { db: connection.db, opened: true };
81
+ }
82
+ async function assertSynced(db, opened, withApiKeys) {
83
+ let reports;
84
+ try {
85
+ reports = [
86
+ ...await syncMongoAdapter(db, { dryRun: true }),
87
+ ...withApiKeys ? await syncMongoApiKeys(db, { dryRun: true }) : []
88
+ ];
89
+ } catch (cause) {
90
+ throw new Error(opened ? "connectKit: MongoDB did not answer. Check `mongo.url`, and that the server is reachable." : "connectKit: the Db in `mongo.db` did not answer.", { cause });
91
+ }
92
+ const unsafeReports = reports.filter((report) => unsafe(report).length > 0);
93
+ const missing = unsafeReports.map((report) => `${report.name} (${unsafe(report).join(", ")})`);
94
+ if (missing.length > 0) {
95
+ throw new Error(`connectKit: Janus's collections are not in sync with @softistx/janus-mongo: ${missing.join(", ")}. Run ${syncHint(unsafeReports)}, a deployment step, against the database \`mongo\` names.`);
96
+ }
97
+ const driftedReports = reports.filter((report) => drift(report).length > 0);
98
+ const drifted = driftedReports.map((report) => `${report.name} (${drift(report).join(", ")})`);
99
+ if (drifted.length > 0) {
100
+ process.emitWarning(`connectKit: Janus's collections differ from this @softistx/janus-mongo's definitions: ${drifted.join(", ")}. Run ${syncHint(driftedReports)} once every instance runs this version.`, { code: "JANUS_KIT_COLLECTIONS_DRIFTED" });
101
+ }
102
+ }
103
+ function syncHint(reports) {
104
+ const apiKeys = reports.some((report) => report.name === "apiKeys");
105
+ const others = reports.some((report) => report.name !== "apiKeys");
106
+ if (!apiKeys)
107
+ return "syncMongoAdapter(db)";
108
+ return others ? "syncMongoAdapter(db) and syncMongoApiKeys(db)" : "syncMongoApiKeys(db)";
109
+ }
110
+ function unsafe(report) {
111
+ if (report.created)
112
+ return ["missing"];
113
+ return report.indexes.created.length > 0 ? ["indexes"] : [];
114
+ }
115
+ function drift(report) {
116
+ if (report.created)
117
+ return [];
118
+ const differs = [];
119
+ if (report.validator !== "unchanged")
120
+ differs.push("validator");
121
+ if (report.options.changed.length > 0 || report.options.immutable.length > 0) {
122
+ differs.push("options");
123
+ }
124
+ if (report.indexes.recreated.length > 0)
125
+ differs.push("indexes");
126
+ return differs;
127
+ }
128
+ export {
129
+ connectKit,
130
+ defineConfig
131
+ };
132
+
133
+ //# debugId=B8F2123FF24A991164756E2164756E21
134
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/mongo/config.ts", "../src/mongo/connect.ts"],
4
+ "sourcesContent": [
5
+ "import type { Db, MongoClientOptions } from 'mongodb';\nimport {\n\tcheckObject,\n\tcheckShared,\n\ttype Database,\n\tnonEmpty,\n\toneOf,\n\ttype SharedConfig,\n\ttype UncheckedShared,\n} from '../shared/config';\n\n/** MongoDB, as `ping` and the messages name it. */\nexport const mongoDatabase: Database<'mongo'> = {\n\tkey: 'mongo',\n\tlabel: 'MongoDB',\n};\n\n/**\n * Where users, relations — and sessions and tokens, unless Redis holds them —\n * are kept. **The URL of a database of Janus's own**, its path naming the\n * database, which the kit opens with `@softistx/mongo`'s `connectMongo` and\n * closes; or a `Db` you opened, which it never closes.\n */\nexport type MongoConfig =\n\t| {\n\t\t\treadonly url: string;\n\t\t\treadonly db?: never;\n\t\t\t/** The driver's options, over the kit's `{ serverSelectionTimeoutMS: 5_000 }`. */\n\t\t\treadonly clientOptions?: MongoClientOptions;\n\t }\n\t| {\n\t\t\treadonly db: Db;\n\t\t\treadonly url?: never;\n\t\t\treadonly clientOptions?: never;\n\t };\n\n/** The kit's configuration over MongoDB: `mongo`, then the shared keys. */\nexport interface KitConfig<\n\tA extends object,\n\tP extends object,\n\tWithApiKeys extends boolean = false,\n> extends SharedConfig<A, P, WithApiKeys> {\n\treadonly mongo: MongoConfig;\n}\n\n/**\n * The configuration, **checked once, where the application starts**. It\n * connects to nothing and reads no environment variable.\n *\n * ```ts\n * export const config = defineConfig({\n * mongo: { url: process.env.JANUS_MONGO_URL! },\n * redis: { url: process.env.REDIS_URL! },\n * auth: (adapters) => janus({ user, password: { login: 'email' }, hasher: scryptHasher(), ...adapters }),\n * });\n * ```\n */\nexport function defineConfig<\n\tA extends object,\n\tP extends object = never,\n\tconst WithApiKeys extends boolean = false,\n>(config: KitConfig<A, P, WithApiKeys>): KitConfig<A, P, WithApiKeys> {\n\tcheckConfig(config, 'defineConfig');\n\treturn Object.freeze({ ...config });\n}\n\n/**\n * The checks, run by `defineConfig` and again by `connectKit`: a configuration\n * is often built in one file and connected in another.\n */\nexport function checkConfig(\n\tconfig: UncheckedShared & { readonly mongo: MongoConfig },\n\twhere: string,\n): void {\n\tcheckObject(config, where);\n\tconst { mongo } = config;\n\tif (typeof mongo !== 'object' || mongo === null) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`mongo\\` is required — { url } of Janus's database, or { db }, a Db you opened.`,\n\t\t);\n\t}\n\toneOf(where, 'mongo', mongo, 'url', 'db');\n\tif (mongo.url !== undefined) {\n\t\tnonEmpty(where, 'mongo.url', mongo.url);\n\t\t// Only the scheme is named: the URL may hold a password.\n\t\tconst scheme = /^([a-z][a-z0-9+.-]*):/i.exec(mongo.url)?.[1];\n\t\tif (scheme !== 'mongodb' && scheme !== 'mongodb+srv') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: \\`mongo.url\\` is a mongodb:// or mongodb+srv:// URL${scheme === undefined ? '' : `, not ${scheme}://`}.`,\n\t\t\t);\n\t\t}\n\t}\n\tif (mongo.db !== undefined && mongo.clientOptions !== undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: \\`mongo.clientOptions\\` beside \\`mongo.db\\` — its client is already open with its own. Pass the options where you opened it.`,\n\t\t);\n\t}\n\tcheckShared(config, where, mongoDatabase);\n}\n",
6
+ "import {\n\tcreateMongoAdapter,\n\tcreateMongoApiKeys,\n\tsyncMongoAdapter,\n\tsyncMongoApiKeys,\n} from '@softistx/janus-mongo';\nimport { connectMongo, type SyncReport } from '@softistx/mongo';\nimport { type Db, MongoRuntimeError } from 'mongodb';\nimport type { HealthOf } from '../shared/health';\nimport { timed } from '../shared/health';\nimport { assembleKit, type Closers, type KitOf } from '../shared/kit';\nimport { isUriConflict } from '../shared/uri-conflict';\nimport {\n\tcheckConfig,\n\ttype KitConfig,\n\ttype MongoConfig,\n\tmongoDatabase,\n} from './config';\n\n/** What `ping` answers: `{ ok, mongo, redis? }`. */\nexport type Health = HealthOf<'mongo'>;\n\n/** What `connectKit` answers: `auth`, `access` when configured, and the rest. */\nexport type Kit<A extends object, P extends object> = KitOf<A, P, Db, 'mongo'>;\n\n/**\n * Opens the connections, checks that Janus's collections are in sync, and\n * builds `auth` and `access` over them.\n *\n * ```ts\n * export const kit = await connectKit(config);\n * const current = await kit.auth.authenticate(request);\n * await kit.close(); // or `await using kit = await connectKit(config)`\n * ```\n *\n * **It fails here, not at the first sign-in**: a MongoDB that does not\n * answer, or a collection or index `syncMongoAdapter` has not created,\n * rejects with an `Error` naming what to do — a URL the driver cannot read,\n * with a `TypeError` — after closing whatever it had opened. Collections that\n * only differ from these definitions start, with a process warning.\n */\nexport async function connectKit<\n\tA extends object,\n\tP extends object = never,\n\tconst WithApiKeys extends boolean = false,\n>(config: KitConfig<A, P, WithApiKeys>): Promise<Kit<A, P>> {\n\tcheckConfig(config, 'connectKit');\n\treturn await assembleKit(config, async (closers) => {\n\t\tconst { db, opened } = await openMongo(config.mongo, closers);\n\t\tconst withApiKeys = config.apiKeys === true;\n\t\tawait assertSynced(db, opened, withApiKeys);\n\t\tconst { store, relations } = createMongoAdapter(db);\n\t\treturn {\n\t\t\tdatabase: mongoDatabase,\n\t\t\tdb,\n\t\t\tstore,\n\t\t\trelations,\n\t\t\t...(withApiKeys ? { apiKeyStore: createMongoApiKeys(db) } : {}),\n\t\t\tprobe: (timeoutMs) => timed(() => db.command({ ping: 1 }), timeoutMs),\n\t\t};\n\t});\n}\n\nasync function openMongo(\n\tmongo: MongoConfig,\n\tclosers: Closers,\n): Promise<{ db: Db; opened: boolean }> {\n\tif (mongo.url === undefined) return { db: mongo.db, opened: false };\n\tconst connection = await connectMongo(mongo.url, {\n\t\tserverSelectionTimeoutMS: 5_000,\n\t\t...mongo.clientOptions,\n\t}).catch((cause: unknown) => {\n\t\t// A refused configuration — this URL already connected with other\n\t\t// options — is not an outage: it passes through as it is. Before\n\t\t// @softistx/mongo 0.30 it is a TypeError, from 0.30 a UriConflictError\n\t\t// with code URI_CONFLICT; the peer range accepts both.\n\t\tif (cause instanceof TypeError || isUriConflict(cause)) throw cause;\n\t\t// Nor is a URL the driver cannot read, refused before any server is\n\t\t// contacted — as Bun's `SQL` refuses one for `/drizzle`. Never quoted:\n\t\t// it may hold a password. `mongodb-connection-string-url` throws a\n\t\t// `MongoParseError` of its own, not the driver's class — measured — so\n\t\t// it is matched by name.\n\t\tif (\n\t\t\tcause instanceof MongoRuntimeError ||\n\t\t\t(cause instanceof Error && cause.name === 'MongoParseError')\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'connectKit: `mongo.url` is not a connection string the driver can read.',\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t\tthrow new Error(\n\t\t\t'connectKit: MongoDB did not answer. Check `mongo.url`, and that the server is reachable.',\n\t\t\t{ cause },\n\t\t);\n\t});\n\tclosers.push(() => connection.close());\n\treturn { db: connection.db, opened: true };\n}\n\n/**\n * The six collections (seven with `apiKeys: true`), compared with\n * `@softistx/janus-mongo`'s definitions and nothing written. A missing collection is worse here than a missing table:\n * MongoDB creates it on the first write, **without the unique index on\n * logins**, and two users could then share one.\n */\nasync function assertSynced(db: Db, opened: boolean, withApiKeys: boolean) {\n\tlet reports: SyncReport[];\n\ttry {\n\t\treports = [\n\t\t\t...(await syncMongoAdapter(db, { dryRun: true })),\n\t\t\t...(withApiKeys ? await syncMongoApiKeys(db, { dryRun: true }) : []),\n\t\t];\n\t} catch (cause) {\n\t\tthrow new Error(\n\t\t\topened\n\t\t\t\t? 'connectKit: MongoDB did not answer. Check `mongo.url`, and that the server is reachable.'\n\t\t\t\t: 'connectKit: the Db in `mongo.db` did not answer.',\n\t\t\t{ cause },\n\t\t);\n\t}\n\tconst unsafeReports = reports.filter((report) => unsafe(report).length > 0);\n\tconst missing = unsafeReports.map(\n\t\t(report) => `${report.name} (${unsafe(report).join(', ')})`,\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new Error(\n\t\t\t`connectKit: Janus's collections are not in sync with @softistx/janus-mongo: ${missing.join(', ')}. Run ${syncHint(unsafeReports)}, a deployment step, against the database \\`mongo\\` names.`,\n\t\t);\n\t}\n\tconst driftedReports = reports.filter((report) => drift(report).length > 0);\n\tconst drifted = driftedReports.map(\n\t\t(report) => `${report.name} (${drift(report).join(', ')})`,\n\t);\n\tif (drifted.length > 0) {\n\t\tprocess.emitWarning(\n\t\t\t`connectKit: Janus's collections differ from this @softistx/janus-mongo's definitions: ${drifted.join(', ')}. Run ${syncHint(driftedReports)} once every instance runs this version.`,\n\t\t\t{ code: 'JANUS_KIT_COLLECTIONS_DRIFTED' },\n\t\t);\n\t}\n}\n\n/**\n * The sync call that fixes these reports: `syncMongoApiKeys` owns the\n * `apiKeys` collection, `syncMongoAdapter` the other six.\n */\nfunction syncHint(reports: SyncReport[]): string {\n\tconst apiKeys = reports.some((report) => report.name === 'apiKeys');\n\tconst others = reports.some((report) => report.name !== 'apiKeys');\n\tif (!apiKeys) return 'syncMongoAdapter(db)';\n\treturn others\n\t\t? 'syncMongoAdapter(db) and syncMongoApiKeys(db)'\n\t\t: 'syncMongoApiKeys(db)';\n}\n\n/**\n * What would make the stores unsafe: a missing collection, or a missing\n * index — the login index keeps two users from sharing a login. It stops\n * the kit.\n */\nfunction unsafe(report: SyncReport): string[] {\n\tif (report.created) return ['missing'];\n\treturn report.indexes.created.length > 0 ? ['indexes'] : [];\n}\n\n/**\n * What differs from this process's definitions, in either direction: a\n * validator, an option, an index with other options. **Only a warning**: in a\n * rolling deploy, or a rollback, the previous release meets the next one's\n * collections, and must still start.\n */\nfunction drift(report: SyncReport): string[] {\n\tif (report.created) return [];\n\tconst differs: string[] = [];\n\tif (report.validator !== 'unchanged') differs.push('validator');\n\tif (\n\t\treport.options.changed.length > 0 ||\n\t\treport.options.immutable.length > 0\n\t) {\n\t\tdiffers.push('options');\n\t}\n\tif (report.indexes.recreated.length > 0) differs.push('indexes');\n\treturn differs;\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;;;AAYO,IAAM,gBAAmC;AAAA,EAC/C,KAAK;AAAA,EACL,OAAO;AACR;AA0CO,SAAS,YAIf,CAAC,QAAoE;AAAA,EACrE,YAAY,QAAQ,cAAc;AAAA,EAClC,OAAO,OAAO,OAAO,KAAK,OAAO,CAAC;AAAA;AAO5B,SAAS,WAAW,CAC1B,QACA,OACO;AAAA,EACP,YAAY,QAAQ,KAAK;AAAA,EACzB,QAAQ,UAAU;AAAA,EAClB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAAA,IAChD,MAAM,IAAI,UACT,GAAG,yFACJ;AAAA,EACD;AAAA,EACA,MAAM,OAAO,SAAS,OAAO,OAAO,IAAI;AAAA,EACxC,IAAI,MAAM,QAAQ,WAAW;AAAA,IAC5B,SAAS,OAAO,aAAa,MAAM,GAAG;AAAA,IAEtC,MAAM,SAAS,yBAAyB,KAAK,MAAM,GAAG,IAAI;AAAA,IAC1D,IAAI,WAAW,aAAa,WAAW,eAAe;AAAA,MACrD,MAAM,IAAI,UACT,GAAG,6DAA6D,WAAW,YAAY,KAAK,SAAS,cACtG;AAAA,IACD;AAAA,EACD;AAAA,EACA,IAAI,MAAM,OAAO,aAAa,MAAM,kBAAkB,WAAW;AAAA,IAChE,MAAM,IAAI,UACT,GAAG,qIACJ;AAAA,EACD;AAAA,EACA,YAAY,QAAQ,OAAO,aAAa;AAAA;;ACjGzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA;AACA;AAkCO,eAAe,UAIrB,CAAC,QAA0D;AAAA,EAC3D,YAAY,QAAQ,YAAY;AAAA,EAChC,OAAO,MAAM,YAAY,QAAQ,OAAO,YAAY;AAAA,IACnD,QAAQ,IAAI,WAAW,MAAM,UAAU,OAAO,OAAO,OAAO;AAAA,IAC5D,MAAM,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AO,CAAC;AAAA,EAC5B,MAAM,UAAoB,CAAC;AAAA,EAC3B,IAAI,OAAO,cAAc;AAAA,IAAa,QAAQ,KAAK,WAAW;AAAA,EAC9D,IACC,OAAO,QAAQ,QAAQ,SAAS,KAChC,OAAO,QAAQ,UAAU,SAAS,GACjC;AAAA,IACD,QAAQ,KAAK,SAAS;AAAA,EACvB;AAAA,EACA,IAAI,OAAO,QAAQ,UAAU,SAAS;AAAA,IAAG,QAAQ,KAAK,SAAS;AAAA,EAC/D,OAAO;AAAA;",
9
+ "debugId": "B8F2123FF24A991164756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,90 @@
1
+ import type { ApiKeyBoundMethods, ApiKeyExpiryNoticeMethods, ApiKeyStore, ApiKeyUserBoundMethods, JanusStores } from '@softistx/janus';
2
+ import type { RelationStore } from '@softistx/janus/permissions';
3
+ import type { RedisConnection } from '@softistx/redis';
4
+ import type { RedisOptions } from 'bun';
5
+ /**
6
+ * Where sessions and one-time tokens are kept instead. The URL, which the kit
7
+ * connects to with `enableOfflineQueue: false` unless `clientOptions` says
8
+ * otherwise, and closes; or a connection you opened, which it never closes.
9
+ */
10
+ export type RedisConfig = {
11
+ readonly url: string;
12
+ readonly connection?: never;
13
+ /** Bun's `RedisOptions`, over the kit's `{ enableOfflineQueue: false }`. */
14
+ readonly clientOptions?: RedisOptions;
15
+ /** What every key starts with: `janus:` by default. */
16
+ readonly prefix?: string;
17
+ } | {
18
+ readonly connection: RedisConnection;
19
+ readonly url?: never;
20
+ readonly clientOptions?: never;
21
+ readonly prefix?: string;
22
+ };
23
+ /** The API key store the kit builds when `apiKeys` is `true`, with every optional capability. */
24
+ export type KitApiKeyStore = ApiKeyStore & ApiKeyBoundMethods & ApiKeyUserBoundMethods & ApiKeyExpiryNoticeMethods;
25
+ /**
26
+ * What `auth` is built from: spread it into `janus()`. With `apiKeys: true`
27
+ * it also holds `apiKeyStore`, for `janus({ apiKeys: { store: adapters.apiKeyStore, … } })`.
28
+ */
29
+ export type Adapters<WithApiKeys extends boolean = boolean> = BaseAdapters & ([WithApiKeys] extends [true] ? {
30
+ readonly apiKeyStore: KitApiKeyStore;
31
+ } : unknown);
32
+ /** What `auth` is built from, whatever the options. */
33
+ export interface BaseAdapters {
34
+ /** Users from the database; sessions and tokens from Redis when it is wired. */
35
+ readonly store: JanusStores;
36
+ /** The relation store: deleting a user deletes every tuple naming them. */
37
+ readonly relations: RelationStore;
38
+ }
39
+ /** What `access` is built from. */
40
+ export interface AccessWiring<A> {
41
+ readonly relations: RelationStore;
42
+ /** The instance `auth` returned: its `types` are the model's subjects. */
43
+ readonly auth: A;
44
+ }
45
+ /**
46
+ * The keys every kit shares, whatever the database. **`auth` and `access`
47
+ * are yours to write**, so `janus()` and `defineModel()` infer every type
48
+ * where you call them; the kit hands them the stores.
49
+ */
50
+ export interface SharedConfig<A extends object, P extends object, WithApiKeys extends boolean = false> {
51
+ readonly redis?: RedisConfig;
52
+ /**
53
+ * `true` opts in to API keys: the kit checks their table (or collection and
54
+ * indexes) and hands `auth` the store as `adapters.apiKeyStore`. Without it
55
+ * nothing API-key related is checked, created or required.
56
+ */
57
+ readonly apiKeys?: WithApiKeys;
58
+ /**
59
+ * `true` wraps `auth` and `access` with `@softistx/janus-telemetry`'s
60
+ * `instrumentJanus` and `instrumentPermissions`, an optional peer.
61
+ */
62
+ readonly telemetry?: boolean;
63
+ readonly auth: (adapters: Adapters<WithApiKeys>) => A;
64
+ readonly access?: (wiring: AccessWiring<A>) => P;
65
+ }
66
+ /** What the checks read: every shared key, whatever `auth` and `access` build. */
67
+ export interface UncheckedShared {
68
+ readonly redis?: RedisConfig | undefined;
69
+ readonly telemetry?: boolean | undefined;
70
+ readonly apiKeys?: boolean | undefined;
71
+ readonly auth: unknown;
72
+ readonly access?: unknown;
73
+ }
74
+ /**
75
+ * A database the kit wires, named once per module: `key`, the name `ping`
76
+ * reports it under; `label`, the name a message gives it, as where sessions
77
+ * stay without Redis.
78
+ */
79
+ export interface Database<Key extends string> {
80
+ readonly key: Key;
81
+ readonly label: string;
82
+ }
83
+ /** The shared keys' checks, after the database's own. */
84
+ export declare function checkShared(config: UncheckedShared, where: string, database: Database<string>): void;
85
+ /** Refuses a configuration that is not an object at all. */
86
+ export declare function checkObject(config: unknown, where: string): void;
87
+ /** Exactly one of `first` and `second`. */
88
+ export declare function oneOf(where: string, name: string, value: object, first: string, second: string): void;
89
+ export declare function nonEmpty(where: string, name: string, value: unknown): void;
90
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/shared/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,kBAAkB,EAClB,yBAAyB,EACzB,WAAW,EACX,sBAAsB,EACtB,WAAW,EACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,KAAK,CAAC;AAExC;;;;GAIG;AACH,MAAM,MAAM,WAAW,GACpB;IACA,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC;IAC5B,4EAA4E;IAC5E,QAAQ,CAAC,aAAa,CAAC,EAAE,YAAY,CAAC;IACtC,uDAAuD;IACvD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACxB,GACD;IACA,QAAQ,CAAC,UAAU,EAAE,eAAe,CAAC;IACrC,QAAQ,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,aAAa,CAAC,EAAE,KAAK,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEL,iGAAiG;AACjG,MAAM,MAAM,cAAc,GAAG,WAAW,GACvC,kBAAkB,GAClB,s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C;IACzC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ,CAAC,GAAG,SAAS,MAAM;IAC3C,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;IAClB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAED,yDAAyD;AACzD,wBAAgB,WAAW,CAC1B,MAAM,EAAE,eAAe,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,GACxB,IAAI,CAmCN;AAED,4DAA4D;AAC5D,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAIhE;AAED,2CAA2C;AAC3C,wBAAgB,KAAK,CACpB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GACZ,IAAI,CAUN;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAI1E"}
@@ -0,0 +1,33 @@
1
+ /** What one round trip found. It never throws: a health check reports. */
2
+ export type PingResult = {
3
+ readonly ok: true;
4
+ readonly latencyMs: number;
5
+ } | {
6
+ readonly ok: false;
7
+ readonly error: unknown;
8
+ };
9
+ /**
10
+ * The database, under its own name — `postgres`, `mongo` — and `redis` when
11
+ * it is wired; `ok` when every one answered.
12
+ */
13
+ export type HealthOf<Database extends string> = {
14
+ readonly ok: boolean;
15
+ readonly redis?: PingResult;
16
+ } & {
17
+ readonly [Name in Database]: PingResult;
18
+ };
19
+ export type Probe = (timeoutMs: number) => Promise<PingResult>;
20
+ /** The database's probe under its own name, and Redis's when it is wired. */
21
+ export type Probes<Database extends string> = {
22
+ readonly [Name in Database]: Probe;
23
+ } & {
24
+ readonly redis?: Probe;
25
+ };
26
+ /** Every probe at once, each within `timeoutMs`. */
27
+ export declare function probe<Database extends string>(probes: Probes<Database>, timeoutMs: number): Promise<HealthOf<Database>>;
28
+ /**
29
+ * `run`, answered within `timeoutMs`, as `ping` reports it: a round trip that
30
+ * throws or takes longer is `{ ok: false, error }`.
31
+ */
32
+ export declare function timed(run: () => Promise<unknown>, timeoutMs: number): Promise<PingResult>;
33
+ //# sourceMappingURL=health.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../../src/shared/health.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,MAAM,UAAU,GACnB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,QAAQ,CAAC,QAAQ,SAAS,MAAM,IAAI;IAC/C,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC;CAC5B,GAAG;IAAE,QAAQ,EAAE,IAAI,IAAI,QAAQ,GAAG,UAAU;CAAE,CAAC;AAEhD,MAAM,MAAM,KAAK,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;AAE/D,6EAA6E;AAC7E,MAAM,MAAM,MAAM,CAAC,QAAQ,SAAS,MAAM,IAAI;IAC7C,QAAQ,EAAE,IAAI,IAAI,QAAQ,GAAG,KAAK;CAClC,GAAG;IAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE/B,oDAAoD;AACpD,wBAAsB,KAAK,CAAC,QAAQ,SAAS,MAAM,EAClD,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,EACxB,SAAS,EAAE,MAAM,GACf,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAW7B;AAED;;;GAGG;AACH,wBAAsB,KAAK,CAC1B,GAAG,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,EAC3B,SAAS,EAAE,MAAM,GACf,OAAO,CAAC,UAAU,CAAC,CAmBrB"}
@@ -0,0 +1,71 @@
1
+ import type { JanusStores } from '@softistx/janus';
2
+ import type { RelationStore } from '@softistx/janus/permissions';
3
+ import type { RedisConnection } from '@softistx/redis';
4
+ import type { Database, KitApiKeyStore, SharedConfig } from './config';
5
+ import { type HealthOf, type Probe } from './health';
6
+ /**
7
+ * What `connectKit` answers, whatever the database: `auth`, `access` when
8
+ * configured, `db`, and the rest. `Key` is the name `ping` reports the
9
+ * database under.
10
+ */
11
+ export type KitOf<A extends object, P extends object, Db, Key extends string> = {
12
+ /** What your `auth` returned, instrumented when `telemetry` is on. */
13
+ readonly auth: A;
14
+ /** The database Janus's stores query. */
15
+ readonly db: Db;
16
+ /** The Redis connection, when `redis` is configured. */
17
+ readonly redis: RedisConnection | undefined;
18
+ /**
19
+ * The database's and Redis's answers to a round trip, within `timeoutMs`
20
+ * (2 s by default). **Never throws**: a health route always has something
21
+ * to report.
22
+ */
23
+ ping(options?: {
24
+ readonly timeoutMs?: number;
25
+ }): Promise<HealthOf<Key>>;
26
+ /**
27
+ * Closes what the kit opened — Redis, then the database — and nothing it
28
+ * was handed. Idempotent.
29
+ */
30
+ close(): Promise<void>;
31
+ } & ([P] extends [never] ? unknown : {
32
+ /** What your `access` returned, instrumented when `telemetry` is on. */
33
+ readonly access: P;
34
+ }) & AsyncDisposable;
35
+ /** A close, pushed as soon as what it closes is open. */
36
+ export type Closers = (() => Promise<void>)[];
37
+ /** What the database's module opened, and checked, for the kit to wire. */
38
+ export interface Opened<Db, Key extends string> {
39
+ readonly database: Database<Key>;
40
+ readonly db: Db;
41
+ /** Its identity stores and relation store, built over `db`. */
42
+ readonly store: JanusStores;
43
+ readonly relations: RelationStore;
44
+ /** The API key store, built only when `apiKeys` is `true`. */
45
+ readonly apiKeyStore?: KitApiKeyStore;
46
+ readonly probe: Probe;
47
+ }
48
+ /**
49
+ * Everything after the database: Redis, telemetry, `auth` and `access`,
50
+ * `ping`, `close`. `open` opens and checks the database, pushing its close
51
+ * onto `closers` as soon as there is something to close; **whatever fails
52
+ * closes what was opened** before the error is seen.
53
+ */
54
+ export declare function assembleKit<A extends object, P extends object, Db, Key extends string, WithApiKeys extends boolean = false>(config: SharedConfig<A, P, WithApiKeys>, open: (closers: Closers) => Promise<Opened<Db, Key>>): Promise<KitOf<A, P, Db, Key>>;
55
+ /**
56
+ * The closes, in reverse of the opens — Redis before the database. `close`
57
+ * is the kit's, idempotent, rejecting with the one failure or an
58
+ * `AggregateError`; `failStart` closes on the way out of a failed start and
59
+ * rethrows the error that stopped it.
60
+ */
61
+ export declare function lifecycle(): {
62
+ closers: Closers;
63
+ close: () => Promise<void>;
64
+ failStart: (error: unknown) => Promise<never>;
65
+ };
66
+ /** `@softistx/janus-telemetry`, an optional peer: loaded only when asked for. */
67
+ export declare function loadTelemetry(): Promise<{
68
+ janus: <A>(auth: A) => A;
69
+ permissions: <P>(access: P) => P;
70
+ }>;
71
+ //# sourceMappingURL=kit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kit.d.ts","sourceRoot":"","sources":["../../src/shared/kit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAEX,QAAQ,EACR,cAAc,EAEd,YAAY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