@cossackframework/database 0.7.7 → 0.8.0-distprobe.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.d.ts +4 -0
- package/dist/adapter/index.d.ts.map +1 -0
- package/dist/adapter/index.js +3 -0
- package/dist/adapter/index.js.map +1 -0
- package/dist/adapter/memory.d.ts +23 -0
- package/dist/adapter/memory.d.ts.map +1 -0
- package/dist/adapter/memory.js +53 -0
- package/dist/adapter/memory.js.map +1 -0
- package/dist/adapter/scope.d.ts +7 -0
- package/dist/adapter/scope.d.ts.map +1 -0
- package/dist/adapter/scope.js +7 -0
- package/dist/adapter/scope.js.map +1 -0
- package/dist/adapter/types.d.ts +73 -0
- package/dist/adapter/types.d.ts.map +1 -0
- package/dist/adapter/types.js +2 -0
- package/dist/adapter/types.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -0
- package/dist/codec.d.ts +4 -0
- package/dist/codec.d.ts.map +1 -0
- package/dist/codec.js +52 -0
- package/dist/codec.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -0
- package/dist/cossack/index.d.ts +49 -0
- package/dist/cossack/index.d.ts.map +1 -0
- package/dist/cossack/index.js +254 -0
- package/dist/cossack/index.js.map +1 -0
- package/dist/dialect/dialects.d.ts +6 -0
- package/dist/dialect/dialects.d.ts.map +1 -0
- package/dist/dialect/dialects.js +102 -0
- package/dist/dialect/dialects.js.map +1 -0
- package/dist/entity/base-entity.d.ts +21 -0
- package/dist/entity/base-entity.d.ts.map +1 -0
- package/dist/entity/base-entity.js +64 -0
- package/dist/entity/base-entity.js.map +1 -0
- package/dist/entity/manager.d.ts +25 -0
- package/dist/entity/manager.d.ts.map +1 -0
- package/dist/entity/manager.js +72 -0
- package/dist/entity/manager.js.map +1 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +62 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata/decorators.d.ts +27 -0
- package/dist/metadata/decorators.d.ts.map +1 -0
- package/dist/metadata/decorators.js +271 -0
- package/dist/metadata/decorators.js.map +1 -0
- package/dist/metadata/finalize.d.ts +4 -0
- package/dist/metadata/finalize.d.ts.map +1 -0
- package/dist/metadata/finalize.js +267 -0
- package/dist/metadata/finalize.js.map +1 -0
- package/dist/metadata/naming.d.ts +9 -0
- package/dist/metadata/naming.d.ts.map +1 -0
- package/dist/metadata/naming.js +21 -0
- package/dist/metadata/naming.js.map +1 -0
- package/dist/metadata/stage3.d.ts +26 -0
- package/dist/metadata/stage3.d.ts.map +1 -0
- package/dist/metadata/stage3.js +38 -0
- package/dist/metadata/stage3.js.map +1 -0
- package/dist/metadata/store.d.ts +29 -0
- package/dist/metadata/store.d.ts.map +1 -0
- package/dist/metadata/store.js +22 -0
- package/dist/metadata/store.js.map +1 -0
- package/dist/metadata/types.d.ts +83 -0
- package/dist/metadata/types.d.ts.map +1 -0
- package/dist/metadata/types.js +2 -0
- package/dist/metadata/types.js.map +1 -0
- package/dist/migration/runner.d.ts +22 -0
- package/dist/migration/runner.d.ts.map +1 -0
- package/dist/migration/runner.js +182 -0
- package/dist/migration/runner.js.map +1 -0
- package/dist/migration/types.d.ts +26 -0
- package/dist/migration/types.d.ts.map +1 -0
- package/dist/migration/types.js +2 -0
- package/dist/migration/types.js.map +1 -0
- package/dist/orm.d.ts +63 -0
- package/dist/orm.d.ts.map +1 -0
- package/dist/orm.js +643 -0
- package/dist/orm.js.map +1 -0
- package/dist/query/builder.d.ts +63 -0
- package/dist/query/builder.d.ts.map +1 -0
- package/dist/query/builder.js +303 -0
- package/dist/query/builder.js.map +1 -0
- package/dist/query/expression.d.ts +27 -0
- package/dist/query/expression.d.ts.map +1 -0
- package/dist/query/expression.js +90 -0
- package/dist/query/expression.js.map +1 -0
- package/dist/query/types.d.ts +33 -0
- package/dist/query/types.d.ts.map +1 -0
- package/dist/query/types.js +11 -0
- package/dist/query/types.js.map +1 -0
- package/dist/runtime/bun.d.ts +30 -0
- package/dist/runtime/bun.d.ts.map +1 -0
- package/dist/runtime/bun.js +63 -0
- package/dist/runtime/bun.js.map +1 -0
- package/dist/runtime/cloudflare.d.ts +70 -0
- package/dist/runtime/cloudflare.d.ts.map +1 -0
- package/dist/runtime/cloudflare.js +230 -0
- package/dist/runtime/cloudflare.js.map +1 -0
- package/dist/runtime/deno.d.ts +26 -0
- package/dist/runtime/deno.d.ts.map +1 -0
- package/dist/runtime/deno.js +40 -0
- package/dist/runtime/deno.js.map +1 -0
- package/dist/runtime/helpers.d.ts +4 -0
- package/dist/runtime/helpers.d.ts.map +1 -0
- package/dist/runtime/helpers.js +22 -0
- package/dist/runtime/helpers.js.map +1 -0
- package/dist/runtime/node.d.ts +88 -0
- package/dist/runtime/node.d.ts.map +1 -0
- package/dist/runtime/node.js +221 -0
- package/dist/runtime/node.js.map +1 -0
- package/dist/schema/builder.d.ts +16 -0
- package/dist/schema/builder.d.ts.map +1 -0
- package/dist/schema/builder.js +49 -0
- package/dist/schema/builder.js.map +1 -0
- package/dist/schema/ddl.d.ts +7 -0
- package/dist/schema/ddl.d.ts.map +1 -0
- package/dist/schema/ddl.js +114 -0
- package/dist/schema/ddl.js.map +1 -0
- package/dist/schema/diff.d.ts +8 -0
- package/dist/schema/diff.d.ts.map +1 -0
- package/dist/schema/diff.js +224 -0
- package/dist/schema/diff.js.map +1 -0
- package/dist/schema/introspection.d.ts +8 -0
- package/dist/schema/introspection.d.ts.map +1 -0
- package/dist/schema/introspection.js +165 -0
- package/dist/schema/introspection.js.map +1 -0
- package/dist/schema/operations.d.ts +44 -0
- package/dist/schema/operations.d.ts.map +1 -0
- package/dist/schema/operations.js +2 -0
- package/dist/schema/operations.js.map +1 -0
- package/dist/schema/types.d.ts +76 -0
- package/dist/schema/types.d.ts.map +1 -0
- package/dist/schema/types.js +2 -0
- package/dist/schema/types.js.map +1 -0
- package/dist/scope.d.ts +5 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +28 -0
- package/dist/scope.js.map +1 -0
- package/dist/seeding/runner.d.ts +14 -0
- package/dist/seeding/runner.d.ts.map +1 -0
- package/dist/seeding/runner.js +107 -0
- package/dist/seeding/runner.js.map +1 -0
- package/dist/seeding/types.d.ts +33 -0
- package/dist/seeding/types.d.ts.map +1 -0
- package/dist/seeding/types.js +4 -0
- package/dist/seeding/types.js.map +1 -0
- package/dist/sql/client.d.ts +16 -0
- package/dist/sql/client.d.ts.map +1 -0
- package/dist/sql/client.js +71 -0
- package/dist/sql/client.js.map +1 -0
- package/dist/sql/executable.d.ts +8 -0
- package/dist/sql/executable.d.ts.map +1 -0
- package/dist/sql/executable.js +11 -0
- package/dist/sql/executable.js.map +1 -0
- package/dist/sql/fragment.d.ts +37 -0
- package/dist/sql/fragment.d.ts.map +1 -0
- package/dist/sql/fragment.js +40 -0
- package/dist/sql/fragment.js.map +1 -0
- package/dist/sql/tag.d.ts +20 -0
- package/dist/sql/tag.d.ts.map +1 -0
- package/dist/sql/tag.js +123 -0
- package/dist/sql/tag.js.map +1 -0
- package/dist/tooling/generate.d.ts +9 -0
- package/dist/tooling/generate.d.ts.map +1 -0
- package/dist/tooling/generate.js +83 -0
- package/dist/tooling/generate.js.map +1 -0
- package/dist/tooling/index.d.ts +12 -0
- package/dist/tooling/index.d.ts.map +1 -0
- package/dist/tooling/index.js +389 -0
- package/dist/tooling/index.js.map +1 -0
- package/package.json +93 -21
- package/LICENSE +0 -21
- package/README.md +0 -188
- package/src/accessor.ts +0 -27
- package/src/als.ts +0 -29
- package/src/cache-store.ts +0 -285
- package/src/create-database.ts +0 -36
- package/src/dialects/d1.ts +0 -215
- package/src/dialects/libsql.ts +0 -104
- package/src/index.ts +0 -67
- package/src/middleware.ts +0 -42
- package/src/migrations/migrator.ts +0 -90
- package/src/seeder/runner.ts +0 -73
- package/src/session-als.ts +0 -46
- package/src/session-middleware.ts +0 -98
- package/src/session-store.ts +0 -201
- package/src/session.ts +0 -59
- package/src/store.ts +0 -38
- package/src/types.ts +0 -108
package/src/index.ts
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
// src/index.ts
|
|
2
|
-
|
|
3
|
-
// Re-export all of Kysely so consumers don't need to install it separately.
|
|
4
|
-
// `Kysely`, `Generated`, `sql`, `Insertable`, `Selectable`, etc. are all
|
|
5
|
-
// available via `import { ... } from '@cossackframework/database'`.
|
|
6
|
-
export * from 'kysely';
|
|
7
|
-
export { Migrator, FileMigrationProvider, NO_MIGRATIONS } from 'kysely/migration';
|
|
8
|
-
export type {
|
|
9
|
-
Migration,
|
|
10
|
-
MigrationProvider,
|
|
11
|
-
MigrationResultSet,
|
|
12
|
-
MigrationResult,
|
|
13
|
-
MigrationInfo,
|
|
14
|
-
} from 'kysely/migration';
|
|
15
|
-
|
|
16
|
-
// Core API
|
|
17
|
-
export { createDatabase } from './create-database';
|
|
18
|
-
export { createDbMiddleware } from './middleware';
|
|
19
|
-
export type { DbMiddlewareOptions } from './middleware';
|
|
20
|
-
export { getDb } from './accessor';
|
|
21
|
-
export { db, setDbStoreGetter } from './store';
|
|
22
|
-
export { ensureDbAlsWired, runWithDb } from './als';
|
|
23
|
-
|
|
24
|
-
// Sessions
|
|
25
|
-
export { SessionStore } from './session-store';
|
|
26
|
-
export type { SessionRow } from './session-store';
|
|
27
|
-
export { session } from './session';
|
|
28
|
-
export { createSessionMiddleware } from './session-middleware';
|
|
29
|
-
export type { SessionMiddlewareOptions } from './session-middleware';
|
|
30
|
-
export { runWithSession, ensureSessionAlsWired } from './session-als';
|
|
31
|
-
export type { SessionScope } from './session-als';
|
|
32
|
-
|
|
33
|
-
// Cache (database-backed driver; structurally compatible with core's CacheStore)
|
|
34
|
-
export { DatabaseCacheStore } from './cache-store';
|
|
35
|
-
export type { CacheItemRow, CacheStoreLike } from './cache-store';
|
|
36
|
-
|
|
37
|
-
// Dialects (advanced — for custom Kysely instances)
|
|
38
|
-
export { D1Adapter, D1Dialect } from './dialects/d1';
|
|
39
|
-
export { LibsqlDialect } from './dialects/libsql';
|
|
40
|
-
|
|
41
|
-
// Migrations & seeders
|
|
42
|
-
export {
|
|
43
|
-
runMigrations,
|
|
44
|
-
resetMigrations,
|
|
45
|
-
getMigrationStatus,
|
|
46
|
-
formatMigrationResult,
|
|
47
|
-
defaultMigrationsFolder,
|
|
48
|
-
} from './migrations/migrator';
|
|
49
|
-
export type { RunMigrationsOptions, MigrationDirection } from './migrations/migrator';
|
|
50
|
-
export { runSeeders, defaultSeedersFolder } from './seeder/runner';
|
|
51
|
-
export type { Seeder, RunSeedersOptions } from './seeder/runner';
|
|
52
|
-
|
|
53
|
-
// Types
|
|
54
|
-
export type {
|
|
55
|
-
Database,
|
|
56
|
-
DbClient,
|
|
57
|
-
DbConfig,
|
|
58
|
-
D1Config,
|
|
59
|
-
LibsqlConfig,
|
|
60
|
-
D1DatabaseLike,
|
|
61
|
-
D1PreparedStatementLike,
|
|
62
|
-
D1ResultLike,
|
|
63
|
-
LibsqlClientLike,
|
|
64
|
-
LibsqlInStatement,
|
|
65
|
-
LibsqlResultSetLike,
|
|
66
|
-
LibsqlRowLike,
|
|
67
|
-
} from './types';
|
package/src/middleware.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
// src/middleware.ts
|
|
2
|
-
import type { MiddlewareHandler } from 'hono';
|
|
3
|
-
import { ensureDbAlsWired, runWithDb } from './als';
|
|
4
|
-
import type { DbClient } from './types';
|
|
5
|
-
|
|
6
|
-
export interface DbMiddlewareOptions {
|
|
7
|
-
/**
|
|
8
|
-
* The Kysely client to expose on the request, or a factory that builds one
|
|
9
|
-
* per request (e.g. reading a D1 binding off `c.env`).
|
|
10
|
-
*
|
|
11
|
-
* For stateless HTTP clients (Turso) pass a single shared instance.
|
|
12
|
-
* For D1 pass `(c) => createDatabase({ dialect: 'd1', binding: c.env.DB })`.
|
|
13
|
-
*/
|
|
14
|
-
client: DbClient | ((c: any) => DbClient | Promise<DbClient>);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Hono middleware that exposes the database on the request:
|
|
19
|
-
*
|
|
20
|
-
* - sets `c.set('db', client)` so routes read it via `getDb(c)` / `c.get('db')`,
|
|
21
|
-
* - wraps the rest of the request in `runWithDb` so the global `db()` helper
|
|
22
|
-
* resolves to the same per-request client.
|
|
23
|
-
*
|
|
24
|
-
* Register it globally next to your auth/locale middleware.
|
|
25
|
-
*
|
|
26
|
-
* ```ts
|
|
27
|
-
* import { createDbMiddleware, createDatabase } from '@cossackframework/database'
|
|
28
|
-
*
|
|
29
|
-
* app.use('*', createDbMiddleware({
|
|
30
|
-
* client: (c) => createDatabase({ dialect: 'd1', binding: c.env.DB }),
|
|
31
|
-
* }))
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
export function createDbMiddleware(options: DbMiddlewareOptions): MiddlewareHandler {
|
|
35
|
-
return async (c, next) => {
|
|
36
|
-
ensureDbAlsWired();
|
|
37
|
-
const client =
|
|
38
|
-
typeof options.client === 'function' ? await options.client(c) : options.client;
|
|
39
|
-
(c as any).set('db', client);
|
|
40
|
-
return runWithDb(client, () => next());
|
|
41
|
-
};
|
|
42
|
-
}
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
// src/migrations/migrator.ts
|
|
2
|
-
import { promises as fs } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { FileMigrationProvider, Migrator, NO_MIGRATIONS } from 'kysely/migration';
|
|
5
|
-
import type { MigrationResultSet } from 'kysely/migration';
|
|
6
|
-
import type { DbClient } from '../types';
|
|
7
|
-
|
|
8
|
-
export interface RunMigrationsOptions {
|
|
9
|
-
client: DbClient;
|
|
10
|
-
/** Absolute path to the folder holding migration files (default `src/migrations`). */
|
|
11
|
-
folder?: string;
|
|
12
|
-
/** Name of the migrations bookkeeping table (Kysely default `kysely_migration`). */
|
|
13
|
-
migrationTableName?: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export type MigrationDirection = 'up' | 'down' | 'latest';
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Runs Kysely migrations discovered as `.ts`/`.js` files in `folder`.
|
|
20
|
-
*
|
|
21
|
-
* - `up` / `latest` — apply all pending migrations (`migrateToLatest`).
|
|
22
|
-
* - `down` — revert the single most recent migration (`migrateDown`).
|
|
23
|
-
*
|
|
24
|
-
* Use {@link resetMigrations} to roll everything back.
|
|
25
|
-
*/
|
|
26
|
-
export async function runMigrations(
|
|
27
|
-
direction: MigrationDirection,
|
|
28
|
-
options: RunMigrationsOptions,
|
|
29
|
-
): Promise<MigrationResultSet> {
|
|
30
|
-
const folder = options.folder ?? defaultMigrationsFolder();
|
|
31
|
-
const migrator = new Migrator({
|
|
32
|
-
db: options.client as any,
|
|
33
|
-
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
34
|
-
migrationTableName: options.migrationTableName,
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
const result =
|
|
38
|
-
direction === 'down' ? await migrator.migrateDown() : await migrator.migrateToLatest();
|
|
39
|
-
return result;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Rolls back every migration (runs all `down` handlers down to nothing).
|
|
44
|
-
*/
|
|
45
|
-
export async function resetMigrations(options: RunMigrationsOptions): Promise<MigrationResultSet> {
|
|
46
|
-
const folder = options.folder ?? defaultMigrationsFolder();
|
|
47
|
-
const migrator = new Migrator({
|
|
48
|
-
db: options.client as any,
|
|
49
|
-
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
50
|
-
migrationTableName: options.migrationTableName,
|
|
51
|
-
});
|
|
52
|
-
return migrator.migrateTo(NO_MIGRATIONS);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Returns each migration with its execution state (executedAt if run). */
|
|
56
|
-
export async function getMigrationStatus(
|
|
57
|
-
options: RunMigrationsOptions,
|
|
58
|
-
): Promise<Array<{ name: string; executedAt?: Date }>> {
|
|
59
|
-
const folder = options.folder ?? defaultMigrationsFolder();
|
|
60
|
-
const migrator = new Migrator({
|
|
61
|
-
db: options.client as any,
|
|
62
|
-
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
63
|
-
migrationTableName: options.migrationTableName,
|
|
64
|
-
});
|
|
65
|
-
const infos = await migrator.getMigrations();
|
|
66
|
-
return infos.map((it) => ({ name: it.name, executedAt: it.executedAt }));
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** Prints a human-readable summary of a migration result set. */
|
|
70
|
-
export function formatMigrationResult(result: MigrationResultSet): string {
|
|
71
|
-
if (result.error) {
|
|
72
|
-
const msg = result.error instanceof Error ? result.error.message : String(result.error);
|
|
73
|
-
return `Migration failed: ${msg}`;
|
|
74
|
-
}
|
|
75
|
-
const items = result.results ?? [];
|
|
76
|
-
if (items.length === 0) {
|
|
77
|
-
return 'No migrations to run.';
|
|
78
|
-
}
|
|
79
|
-
return items
|
|
80
|
-
.map((it) => {
|
|
81
|
-
const tag = it.status === 'Success' ? '✓' : it.status === 'Error' ? '✗' : '·';
|
|
82
|
-
return `${tag} ${it.direction.toLowerCase()} ${it.migrationName}`;
|
|
83
|
-
})
|
|
84
|
-
.join('\n');
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Default migration folder, resolved relative to the current working directory. */
|
|
88
|
-
export function defaultMigrationsFolder(): string {
|
|
89
|
-
return path.resolve(process.cwd(), 'src', 'migrations');
|
|
90
|
-
}
|
package/src/seeder/runner.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
// src/seeder/runner.ts
|
|
2
|
-
import { promises as fs } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { pathToFileURL } from 'node:url';
|
|
5
|
-
import type { DbClient } from '../types';
|
|
6
|
-
|
|
7
|
-
export interface Seeder {
|
|
8
|
-
run(db: DbClient): Promise<void>;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export interface RunSeedersOptions {
|
|
12
|
-
client: DbClient;
|
|
13
|
-
/** Absolute path to the folder holding seeder files (default `src/seeders`). */
|
|
14
|
-
folder?: string;
|
|
15
|
-
/** Run only seeders whose filename matches this substring. */
|
|
16
|
-
only?: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Imports every `.ts`/`.js` seeder in `folder` (sorted by filename) and calls
|
|
21
|
-
* its default export's `run(db)` method in order.
|
|
22
|
-
*
|
|
23
|
-
* Each seeder file default-exports a {@link Seeder}:
|
|
24
|
-
*
|
|
25
|
-
* ```ts
|
|
26
|
-
* export default {
|
|
27
|
-
* async run(db) {
|
|
28
|
-
* await db.insertInto('users').values({ email: 'demo@cossack.dev' }).execute()
|
|
29
|
-
* },
|
|
30
|
-
* }
|
|
31
|
-
* ```
|
|
32
|
-
*/
|
|
33
|
-
export async function runSeeders(options: RunSeedersOptions): Promise<string[]> {
|
|
34
|
-
const folder = options.folder ?? defaultSeedersFolder();
|
|
35
|
-
let entries: string[];
|
|
36
|
-
try {
|
|
37
|
-
entries = await fs.readdir(folder);
|
|
38
|
-
} catch (err: any) {
|
|
39
|
-
if (err.code === 'ENOENT') return [];
|
|
40
|
-
throw err;
|
|
41
|
-
}
|
|
42
|
-
const files = entries.filter(
|
|
43
|
-
(f) => (f.endsWith('.ts') || f.endsWith('.js')) && !f.endsWith('.d.ts'),
|
|
44
|
-
);
|
|
45
|
-
const filtered = options.only
|
|
46
|
-
? files.filter((f) => f.includes(options.only as string))
|
|
47
|
-
: files;
|
|
48
|
-
filtered.sort();
|
|
49
|
-
|
|
50
|
-
const ran: string[] = [];
|
|
51
|
-
for (const file of filtered) {
|
|
52
|
-
const fullPath = path.resolve(folder, file);
|
|
53
|
-
// `/* @vite-ignore */` suppresses Vite's "cannot analyze dynamic import"
|
|
54
|
-
// warning: the specifiers are built at runtime from a directory listing
|
|
55
|
-
// (user seeder files), so static analysis is impossible by design. This
|
|
56
|
-
// is intentional and matches Vite's documented escape hatch.
|
|
57
|
-
const mod = await import(
|
|
58
|
-
/* @vite-ignore */ `${pathToFileURL(fullPath).href}?t=${Date.now()}`
|
|
59
|
-
);
|
|
60
|
-
const seeder: Seeder = mod.default ?? mod;
|
|
61
|
-
if (typeof seeder?.run !== 'function') {
|
|
62
|
-
throw new Error(`Seeder "${file}" has no \`run(db)\` method (or default export).`);
|
|
63
|
-
}
|
|
64
|
-
await seeder.run(options.client);
|
|
65
|
-
ran.push(file);
|
|
66
|
-
}
|
|
67
|
-
return ran;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** Default seeder folder, resolved relative to the current working directory. */
|
|
71
|
-
export function defaultSeedersFolder(): string {
|
|
72
|
-
return path.resolve(process.cwd(), 'src', 'seeders');
|
|
73
|
-
}
|
package/src/session-als.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
// src/session-als.ts
|
|
2
|
-
//
|
|
3
|
-
// Per-request session scoping. The framework's session middleware resolves the
|
|
4
|
-
// session ID (from the auth cookie or the anonymous `cossack_sid` cookie),
|
|
5
|
-
// loads/creates the row, and wraps the request in this scope so the global
|
|
6
|
-
// `session()` helper resolves it.
|
|
7
|
-
//
|
|
8
|
-
// Mirrors the db() ALS pattern (see `als.ts` + `store.ts`).
|
|
9
|
-
|
|
10
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
|
-
import type { SessionStore } from './session-store';
|
|
12
|
-
|
|
13
|
-
/** The per-request session scope: the store + the active session ID. */
|
|
14
|
-
export interface SessionScope {
|
|
15
|
-
/** The active session ID for this request (auth's, or an anonymous one). */
|
|
16
|
-
sessionId: string;
|
|
17
|
-
/** The SessionStore (backed by the scoped `db()` client). */
|
|
18
|
-
store: SessionStore;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const sessionAls = new AsyncLocalStorage<SessionScope>();
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* One-time wiring hook (kept for symmetry with db/i18n; the `session()` helper
|
|
25
|
-
* reads `sessionAls` directly since it lives in the same package). Idempotent.
|
|
26
|
-
*/
|
|
27
|
-
let wired = false;
|
|
28
|
-
export function ensureSessionAlsWired(): void {
|
|
29
|
-
wired = true;
|
|
30
|
-
}
|
|
31
|
-
export function _isSessionAlsWired(): boolean {
|
|
32
|
-
return wired;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Runs `fn` inside a session scope. `session()` inside `fn` resolves the scope. */
|
|
36
|
-
export function runWithSession<T>(
|
|
37
|
-
scope: SessionScope,
|
|
38
|
-
fn: () => T | Promise<T>,
|
|
39
|
-
): T | Promise<T> {
|
|
40
|
-
return sessionAls.run(scope, fn as () => T);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** @internal Returns the active session scope, if any. Used by `session()`. */
|
|
44
|
-
export function getSessionScope(): SessionScope | undefined {
|
|
45
|
-
return sessionAls.getStore();
|
|
46
|
-
}
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
// src/session-middleware.ts
|
|
2
|
-
//
|
|
3
|
-
// Per-request session middleware. Resolves the session ID (from an optional
|
|
4
|
-
// auth-cookie reader, else the anonymous `cossack_sid` cookie), creates one if
|
|
5
|
-
// missing, and scopes a `SessionStore` into AsyncLocalStorage so `session()`
|
|
6
|
-
// works context-free. Ensures the ID cookie is set on the response when a new
|
|
7
|
-
// anonymous session is issued.
|
|
8
|
-
//
|
|
9
|
-
// Register via `cossack add database` (same pattern as `dbMiddleware`):
|
|
10
|
-
//
|
|
11
|
-
// // src/middlewares/session.ts
|
|
12
|
-
// import { createSessionMiddleware } from '@cossackframework/database';
|
|
13
|
-
// export const sessionMiddleware = createSessionMiddleware();
|
|
14
|
-
//
|
|
15
|
-
// // src/config/middlewares.ts
|
|
16
|
-
// import { sessionMiddleware } from '../middlewares/session';
|
|
17
|
-
// export const middlewares = [sessionMiddleware];
|
|
18
|
-
|
|
19
|
-
import type { MiddlewareHandler } from 'hono';
|
|
20
|
-
import { getCookie, setCookie } from 'hono/cookie';
|
|
21
|
-
import { db } from './store';
|
|
22
|
-
import { SessionStore } from './session-store';
|
|
23
|
-
import { ensureSessionAlsWired, runWithSession } from './session-als';
|
|
24
|
-
|
|
25
|
-
export interface SessionMiddlewareOptions {
|
|
26
|
-
/** Anonymous-session cookie name. Defaults to `cossack_sid`. */
|
|
27
|
-
cookieName?: string;
|
|
28
|
-
/** Session TTL in milliseconds. Defaults to 30 days. */
|
|
29
|
-
ttl?: number;
|
|
30
|
-
/**
|
|
31
|
-
* Optional: read the session ID from auth's cookie instead of the anonymous
|
|
32
|
-
* one. Return the auth session ID when the user is logged in; return
|
|
33
|
-
* undefined to fall back to the anonymous cookie. This is the "ID bridge"
|
|
34
|
-
* that lets an authenticated session reuse its existing ID.
|
|
35
|
-
*/
|
|
36
|
-
authCookieReader?: (c: any) => string | undefined | Promise<string | undefined>;
|
|
37
|
-
/**
|
|
38
|
-
* Whether to set the anonymous cookie as `httpOnly`. Defaults to true.
|
|
39
|
-
* (Auth-managed cookies set their own attributes via the auth module.)
|
|
40
|
-
*/
|
|
41
|
-
httpOnly?: boolean;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const DEFAULT_COOKIE_NAME = 'cossack_sid';
|
|
45
|
-
const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
46
|
-
|
|
47
|
-
export function createSessionMiddleware(
|
|
48
|
-
options: SessionMiddlewareOptions = {},
|
|
49
|
-
): MiddlewareHandler {
|
|
50
|
-
const cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
|
|
51
|
-
const ttl = options.ttl ?? DEFAULT_TTL_MS;
|
|
52
|
-
const httpOnly = options.httpOnly ?? true;
|
|
53
|
-
|
|
54
|
-
return async (c, next) => {
|
|
55
|
-
ensureSessionAlsWired();
|
|
56
|
-
const store = new SessionStore(db());
|
|
57
|
-
|
|
58
|
-
// 1. Resolve an existing session ID: auth cookie first, then anonymous.
|
|
59
|
-
// `authProvidedId` tracks whether auth handed us an ID so we know
|
|
60
|
-
// not to set the anonymous cookie in that case (auth manages its own).
|
|
61
|
-
let sessionId: string | undefined;
|
|
62
|
-
let authProvidedId = false;
|
|
63
|
-
if (options.authCookieReader) {
|
|
64
|
-
sessionId = await options.authCookieReader(c);
|
|
65
|
-
if (sessionId) authProvidedId = true;
|
|
66
|
-
}
|
|
67
|
-
if (!sessionId) {
|
|
68
|
-
sessionId = getCookie(c, cookieName);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// 2. If neither auth nor the anonymous cookie gave us an ID, create a
|
|
72
|
-
// fresh anonymous session. We set its cookie after `next()` so it
|
|
73
|
-
// survives redirects.
|
|
74
|
-
let issuedNewAnonymousId = false;
|
|
75
|
-
if (!sessionId) {
|
|
76
|
-
sessionId = await store.create(ttl);
|
|
77
|
-
issuedNewAnonymousId = true;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// 3. Scope the session for downstream handlers.
|
|
81
|
-
await runWithSession({ sessionId, store }, () => next());
|
|
82
|
-
|
|
83
|
-
// 4. Persist a newly-issued ANONYMOUS ID as a cookie. We must NOT skip
|
|
84
|
-
// this when `authCookieReader` is configured but returned undefined
|
|
85
|
-
// (an unauthenticated request) — otherwise the new anonymous session
|
|
86
|
-
// is orphaned and lost on the next request. Only an auth-provided ID
|
|
87
|
-
// is excluded, because the auth module sets its own cookie.
|
|
88
|
-
if (issuedNewAnonymousId && !authProvidedId) {
|
|
89
|
-
setCookie(c, cookieName, sessionId, {
|
|
90
|
-
httpOnly,
|
|
91
|
-
secure: c.req.url.startsWith('https://'),
|
|
92
|
-
sameSite: 'Lax',
|
|
93
|
-
path: '/',
|
|
94
|
-
maxAge: Math.floor(ttl / 1000),
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
}
|
package/src/session-store.ts
DELETED
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
// src/session-store.ts
|
|
2
|
-
//
|
|
3
|
-
// DB-backed key/value session storage. Promotes the inline session CRUD that
|
|
4
|
-
// `cossack add auth` generates (see `authModuleTemplate` in the cossack CLI)
|
|
5
|
-
// into a reusable, tested class. Reuses the per-request `db()` client from the
|
|
6
|
-
// database ALS scope — no separate client, no new binding.
|
|
7
|
-
//
|
|
8
|
-
// Sessions are addressed by an opaque high-entropy ID (32 random bytes,
|
|
9
|
-
// base64url). The ID is carried in a cookie (see `createSessionMiddleware`);
|
|
10
|
-
// the store is the source of truth. IDs need no signing — forging is futile
|
|
11
|
-
// against 256 bits of entropy.
|
|
12
|
-
//
|
|
13
|
-
// Anonymous sessions (`user_id` null) work for carts/wizards/A-B without auth;
|
|
14
|
-
// authenticated sessions carry the `user_id`. The `data` column holds a JSON
|
|
15
|
-
// key/value bag so `set('cart', ...)` / `get('cart')` work like a hash.
|
|
16
|
-
//
|
|
17
|
-
// Expected schema (shipped via the `cossack add database` migration template):
|
|
18
|
-
// create table sessions (
|
|
19
|
-
// id text primary key not null,
|
|
20
|
-
// user_id text, -- nullable for anonymous sessions
|
|
21
|
-
// data text, -- JSON key/value bag
|
|
22
|
-
// expires_at text not null
|
|
23
|
-
// );
|
|
24
|
-
|
|
25
|
-
import type { DbClient } from './types';
|
|
26
|
-
import { db } from './store';
|
|
27
|
-
|
|
28
|
-
/** Sessions-table row shape (snake_case to match the migration). */
|
|
29
|
-
export interface SessionRow {
|
|
30
|
-
id: string;
|
|
31
|
-
user_id: string | null;
|
|
32
|
-
data: string | null;
|
|
33
|
-
/** JSON bag for auth-session metadata (user-agent, ip, type discriminator, ...). */
|
|
34
|
-
meta: string | null;
|
|
35
|
-
/** Geo (Cloudflare request.cf country/city) captured at login; null off-CF. */
|
|
36
|
-
location: string | null;
|
|
37
|
-
/** User-Agent header captured at login. */
|
|
38
|
-
user_agent: string | null;
|
|
39
|
-
/** Client IP (cf-connecting-ip) captured at login. */
|
|
40
|
-
ip_address: string | null;
|
|
41
|
-
/** When the session row was created (the "Logged in" time). Optional on insert
|
|
42
|
-
* (the generic SessionStore doesn't set it; app auth flows do via migration). */
|
|
43
|
-
created_at?: string;
|
|
44
|
-
expires_at: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Augment the Database interface so `selectFrom('sessions')` is typed.
|
|
48
|
-
declare module './types' {
|
|
49
|
-
interface Database {
|
|
50
|
-
sessions: SessionRow;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Default session TTL: 30 days, in milliseconds. */
|
|
55
|
-
const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
56
|
-
|
|
57
|
-
function nowISO(): string {
|
|
58
|
-
return new Date().toISOString();
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function expiryISO(ttlMs: number): string {
|
|
62
|
-
return new Date(Date.now() + ttlMs).toISOString();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function isExpired(expiresAt: string): boolean {
|
|
66
|
-
return new Date(expiresAt).getTime() <= Date.now();
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* DB-backed session key/value store. Construct per request (the session
|
|
71
|
-
* middleware does this) with the scoped `db()` client, or pass an explicit
|
|
72
|
-
* client for scripts/tests.
|
|
73
|
-
*
|
|
74
|
-
* const store = new SessionStore(); // uses db()
|
|
75
|
-
* await store.set(sessionId, 'cart', { items: [] });
|
|
76
|
-
* const cart = await store.get(sessionId, 'cart');
|
|
77
|
-
*/
|
|
78
|
-
export class SessionStore {
|
|
79
|
-
constructor(private client: DbClient = db()) {}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Read + parse the JSON `data` bag for a session. Returns `{}` if the
|
|
83
|
-
* session is missing, expired, or has no data. Does NOT auto-delete expired
|
|
84
|
-
* rows here (see `purgeExpired`); callers just see an empty bag.
|
|
85
|
-
*/
|
|
86
|
-
async load(sessionId: string): Promise<Record<string, unknown>> {
|
|
87
|
-
const row = await this.client
|
|
88
|
-
.selectFrom('sessions')
|
|
89
|
-
.select(['data', 'expires_at'])
|
|
90
|
-
.where('id', '=', sessionId)
|
|
91
|
-
.executeTakeFirst();
|
|
92
|
-
if (!row) return {};
|
|
93
|
-
if (isExpired(row.expires_at as string)) return {};
|
|
94
|
-
if (!row.data) return {};
|
|
95
|
-
try {
|
|
96
|
-
return JSON.parse(row.data as string) as Record<string, unknown>;
|
|
97
|
-
} catch {
|
|
98
|
-
return {};
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Set a single key in the session's data bag (merging with existing data).
|
|
104
|
-
* Also refreshes `expires_at` to extend the session on activity (sliding
|
|
105
|
-
* expiration). Creates the row if it doesn't exist.
|
|
106
|
-
*/
|
|
107
|
-
async set(
|
|
108
|
-
sessionId: string,
|
|
109
|
-
key: string,
|
|
110
|
-
value: unknown,
|
|
111
|
-
ttlMs: number = DEFAULT_TTL_MS,
|
|
112
|
-
): Promise<void> {
|
|
113
|
-
const data = await this.load(sessionId);
|
|
114
|
-
data[key] = value;
|
|
115
|
-
await this.client
|
|
116
|
-
.insertInto('sessions')
|
|
117
|
-
.values({
|
|
118
|
-
id: sessionId,
|
|
119
|
-
user_id: null,
|
|
120
|
-
data: JSON.stringify(data),
|
|
121
|
-
expires_at: expiryISO(ttlMs),
|
|
122
|
-
})
|
|
123
|
-
.onConflict((oc) =>
|
|
124
|
-
oc.column('id').doUpdateSet({
|
|
125
|
-
data: JSON.stringify(data),
|
|
126
|
-
expires_at: expiryISO(ttlMs),
|
|
127
|
-
}),
|
|
128
|
-
)
|
|
129
|
-
.execute();
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** Read a single key from the session's data bag. */
|
|
133
|
-
async get<T = unknown>(sessionId: string, key: string): Promise<T | undefined> {
|
|
134
|
-
const data = await this.load(sessionId);
|
|
135
|
-
return data[key] as T | undefined;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/** Read the entire data bag. */
|
|
139
|
-
async getAll(sessionId: string): Promise<Record<string, unknown>> {
|
|
140
|
-
return this.load(sessionId);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** Remove a single key from the data bag. */
|
|
144
|
-
async unset(sessionId: string, key: string): Promise<void> {
|
|
145
|
-
const data = await this.load(sessionId);
|
|
146
|
-
if (!(key in data)) return;
|
|
147
|
-
delete data[key];
|
|
148
|
-
await this.client
|
|
149
|
-
.updateTable('sessions')
|
|
150
|
-
.set({ data: JSON.stringify(data) })
|
|
151
|
-
.where('id', '=', sessionId)
|
|
152
|
-
.execute();
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Delete the session row entirely. */
|
|
156
|
-
async destroy(sessionId: string): Promise<void> {
|
|
157
|
-
await this.client.deleteFrom('sessions').where('id', '=', sessionId).execute();
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Delete all expired rows. Call opportunistically (e.g. on a sample of requests). */
|
|
161
|
-
async purgeExpired(): Promise<number> {
|
|
162
|
-
const now = nowISO();
|
|
163
|
-
const result = await this.client
|
|
164
|
-
.deleteFrom('sessions')
|
|
165
|
-
.where('expires_at', '<', now)
|
|
166
|
-
.executeTakeFirst();
|
|
167
|
-
// Kysely's DeleteResult exposes numDeletedRows (bigint).
|
|
168
|
-
return Number(result?.numDeletedRows ?? 0);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Create a new session row with a fresh high-entropy ID. Returns the ID.
|
|
173
|
-
* Use when no session ID is present (anonymous first visit).
|
|
174
|
-
*/
|
|
175
|
-
async create(ttlMs: number = DEFAULT_TTL_MS): Promise<string> {
|
|
176
|
-
// 32 random bytes → ~43 base64url chars. See crypto.generateToken in
|
|
177
|
-
// @cossackframework/core; we inline here to keep this package
|
|
178
|
-
// dependency-free on core (the database package is standalone, only
|
|
179
|
-
// depending on kysely + hono peer deps).
|
|
180
|
-
const bytes = new Uint8Array(32);
|
|
181
|
-
crypto.getRandomValues(bytes);
|
|
182
|
-
let binary = '';
|
|
183
|
-
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
184
|
-
const id = btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
185
|
-
|
|
186
|
-
await this.client
|
|
187
|
-
.insertInto('sessions')
|
|
188
|
-
.values({ id, user_id: null, data: null, expires_at: expiryISO(ttlMs) })
|
|
189
|
-
.execute();
|
|
190
|
-
return id;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** Attach a user ID to a session (called on login). */
|
|
194
|
-
async bindUser(sessionId: string, userId: string): Promise<void> {
|
|
195
|
-
await this.client
|
|
196
|
-
.updateTable('sessions')
|
|
197
|
-
.set({ user_id: userId })
|
|
198
|
-
.where('id', '=', sessionId)
|
|
199
|
-
.execute();
|
|
200
|
-
}
|
|
201
|
-
}
|
package/src/session.ts
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
// src/session.ts
|
|
2
|
-
//
|
|
3
|
-
// Context-free session access: `session()` returns a handle bound to the active
|
|
4
|
-
// request's session for key/value get/set. Mirrors `db()` — throws a clear
|
|
5
|
-
// `[Cossack]` error if called outside a request scope (register the session
|
|
6
|
-
// middleware via `cossack add database`).
|
|
7
|
-
//
|
|
8
|
-
// await session().set('cart', { items: [...] });
|
|
9
|
-
// const cart = await session().get('cart');
|
|
10
|
-
// const sid = session().id();
|
|
11
|
-
//
|
|
12
|
-
// Sessions are DB-backed (the `sessions` table) and addressed by an opaque ID
|
|
13
|
-
// carried in a cookie. With auth installed, the ID is the auth session cookie;
|
|
14
|
-
// otherwise an anonymous `cossack_sid` cookie is used (see
|
|
15
|
-
// `createSessionMiddleware`).
|
|
16
|
-
|
|
17
|
-
import { getSessionScope } from './session-als';
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Returns a handle to the active request's session. The handle caches the
|
|
21
|
-
* session ID and exposes async get/set over the scoped `SessionStore`.
|
|
22
|
-
*
|
|
23
|
-
* Throws if no session scope is active.
|
|
24
|
-
*/
|
|
25
|
-
export function session() {
|
|
26
|
-
const scope = getSessionScope();
|
|
27
|
-
if (!scope) {
|
|
28
|
-
throw new Error(
|
|
29
|
-
'[Cossack] No session in scope. `session()` must be called within a request ' +
|
|
30
|
-
'handler with the session middleware registered (run `cossack add database`).',
|
|
31
|
-
);
|
|
32
|
-
}
|
|
33
|
-
return {
|
|
34
|
-
/** The active session ID for this request. */
|
|
35
|
-
id(): string {
|
|
36
|
-
return scope.sessionId;
|
|
37
|
-
},
|
|
38
|
-
/** Read a single key from the session data bag. */
|
|
39
|
-
async get<T = unknown>(key: string): Promise<T | undefined> {
|
|
40
|
-
return scope.store.get<T>(scope.sessionId, key);
|
|
41
|
-
},
|
|
42
|
-
/** Read the entire data bag. */
|
|
43
|
-
async getAll(): Promise<Record<string, unknown>> {
|
|
44
|
-
return scope.store.getAll(scope.sessionId);
|
|
45
|
-
},
|
|
46
|
-
/** Set a single key (merges into the bag; refreshes expiry). */
|
|
47
|
-
async set(key: string, value: unknown): Promise<void> {
|
|
48
|
-
return scope.store.set(scope.sessionId, key, value);
|
|
49
|
-
},
|
|
50
|
-
/** Remove a single key from the bag. */
|
|
51
|
-
async unset(key: string): Promise<void> {
|
|
52
|
-
return scope.store.unset(scope.sessionId, key);
|
|
53
|
-
},
|
|
54
|
-
/** Delete the session row entirely (e.g. on logout). */
|
|
55
|
-
async destroy(): Promise<void> {
|
|
56
|
-
return scope.store.destroy(scope.sessionId);
|
|
57
|
-
},
|
|
58
|
-
};
|
|
59
|
-
}
|