hazo_testing 0.1.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.
Files changed (44) hide show
  1. package/CHANGE_LOG.md +55 -0
  2. package/README.md +359 -0
  3. package/SETUP_CHECKLIST.md +115 -0
  4. package/config/hazo_testing_config.ini.sample +22 -0
  5. package/dist/api/test_client.d.ts +24 -0
  6. package/dist/api/test_client.js +82 -0
  7. package/dist/components/test_providers.d.ts +20 -0
  8. package/dist/components/test_providers.js +10 -0
  9. package/dist/db/augmented_adapter.d.ts +8 -0
  10. package/dist/db/augmented_adapter.js +24 -0
  11. package/dist/db/test_database.d.ts +16 -0
  12. package/dist/db/test_database.js +42 -0
  13. package/dist/errors.d.ts +7 -0
  14. package/dist/errors.js +22 -0
  15. package/dist/factories/scopes.d.ts +19 -0
  16. package/dist/factories/scopes.js +12 -0
  17. package/dist/factories/users.d.ts +14 -0
  18. package/dist/factories/users.js +44 -0
  19. package/dist/fixtures/registry.d.ts +6 -0
  20. package/dist/fixtures/registry.js +11 -0
  21. package/dist/fixtures/starter.d.ts +1 -0
  22. package/dist/fixtures/starter.js +47 -0
  23. package/dist/hooks/after_each_setup.d.ts +1 -0
  24. package/dist/hooks/after_each_setup.js +6 -0
  25. package/dist/hooks/polyfills.d.ts +1 -0
  26. package/dist/hooks/polyfills.js +6 -0
  27. package/dist/hooks/reset_hooks.d.ts +4 -0
  28. package/dist/hooks/reset_hooks.js +5 -0
  29. package/dist/index.client.d.ts +2 -0
  30. package/dist/index.client.js +3 -0
  31. package/dist/index.d.ts +20 -0
  32. package/dist/index.js +15 -0
  33. package/dist/nextjs/index.d.ts +10 -0
  34. package/dist/nextjs/index.js +26 -0
  35. package/dist/playwright/index.d.ts +13 -0
  36. package/dist/playwright/index.js +8 -0
  37. package/dist/wiring/jobs.d.ts +5 -0
  38. package/dist/wiring/jobs.js +46 -0
  39. package/dist/wiring/llm.d.ts +8 -0
  40. package/dist/wiring/llm.js +83 -0
  41. package/dist/wiring/notify.d.ts +8 -0
  42. package/dist/wiring/notify.js +52 -0
  43. package/jest-preset.cjs +21 -0
  44. package/package.json +55 -0
@@ -0,0 +1,10 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // src/components/test_providers.tsx
3
+ // Purpose: lightweight provider wrapper for component tests. Exposes a test
4
+ // user + scope via context; deeper hazo_auth context wiring is deferred.
5
+ import { createContext, useContext } from "react";
6
+ const TestCtx = createContext({});
7
+ export const useTestContext = () => useContext(TestCtx);
8
+ export function TestProviders(props) {
9
+ return _jsx(TestCtx.Provider, { value: { user: props.user, scope: props.scope }, children: props.children });
10
+ }
@@ -0,0 +1,8 @@
1
+ import type { HazoConnectAdapter } from "hazo_connect";
2
+ export interface AugmentedAdapter extends HazoConnectAdapter {
3
+ insertOne<T extends Record<string, unknown>>(table: string, row: T): Promise<T & {
4
+ id: string;
5
+ }>;
6
+ findOne<T = Record<string, unknown>>(table: string, where: Record<string, unknown>): Promise<T | null>;
7
+ }
8
+ export declare function augmentAdapter(adapter: HazoConnectAdapter): AugmentedAdapter;
@@ -0,0 +1,24 @@
1
+ // src/db/augmented_adapter.ts
2
+ // Purpose: wrap a HazoConnectAdapter with ergonomic insertOne/findOne helpers
3
+ // so test fixtures can write/read rows without hand-building QueryBuilders.
4
+ // Shims delegate to createCrudService (auto-UUID for the id column).
5
+ // NOTE: CrudService returns values directly (not wrapped in DbResult).
6
+ // - insert(row) → T[] (first element is the inserted row)
7
+ // - findOneBy(where) → T | null
8
+ import { createCrudService } from "hazo_connect/server";
9
+ export function augmentAdapter(adapter) {
10
+ const aug = adapter;
11
+ aug.insertOne = async (table, row) => {
12
+ const svc = createCrudService(adapter, table);
13
+ const rows = await svc.insert(row);
14
+ if (!rows.length) {
15
+ throw new Error(`insertOne(${table}) returned no rows`);
16
+ }
17
+ return rows[0];
18
+ };
19
+ aug.findOne = async (table, where) => {
20
+ const svc = createCrudService(adapter, table);
21
+ return (await svc.findOneBy(where));
22
+ };
23
+ return aug;
24
+ }
@@ -0,0 +1,16 @@
1
+ import { type AugmentedAdapter } from "./augmented_adapter.js";
2
+ export interface CreateTestDatabaseOptions {
3
+ mode?: "sqlite" | "docker";
4
+ /** Directories of NNNN_*.sql applied in order via runMigrations. */
5
+ migrations?: string[];
6
+ /** Single .sql files (e.g. db_setup_sqlite.sql) applied in order via execScript. */
7
+ setupSqlFiles?: string[];
8
+ }
9
+ export interface TestDatabase {
10
+ adapter: AugmentedAdapter;
11
+ baseUrl: null;
12
+ teardown: () => Promise<void>;
13
+ }
14
+ export declare function createTestDatabase(opts?: CreateTestDatabaseOptions): Promise<TestDatabase>;
15
+ export declare function createTestDatabaseSqlite(opts?: Omit<CreateTestDatabaseOptions, "mode">): Promise<TestDatabase>;
16
+ export declare function createTestDatabaseDocker(): Promise<never>;
@@ -0,0 +1,42 @@
1
+ // src/db/test_database.ts
2
+ // Purpose: spin up an isolated in-memory SQLite test database (real
3
+ // hazo_connect SqliteAdapter), apply migrations + setup SQL, return an
4
+ // augmented adapter and a teardown handle. Docker mode is reserved but
5
+ // unsupported in v0.1.0.
6
+ import { readFileSync } from "node:fs";
7
+ import { createHazoConnect, runMigrations } from "hazo_connect/server";
8
+ import { augmentAdapter } from "./augmented_adapter.js";
9
+ import { DockerNotSupported } from "../errors.js";
10
+ export async function createTestDatabase(opts = {}) {
11
+ if (opts.mode === "docker")
12
+ throw new DockerNotSupported();
13
+ const base = createHazoConnect({ type: "sqlite", sqlite: { database_path: ":memory:" } });
14
+ // Apply raw setup SQL files first (full-schema db_setup files).
15
+ // sql.js exec() handles multi-statement SQL natively, so no splitting needed.
16
+ for (const file of opts.setupSqlFiles ?? []) {
17
+ await base.execScript(readFileSync(file, "utf-8"));
18
+ }
19
+ // Then numbered migration directories, in array order.
20
+ // runMigrations signature: runMigrations(adapter, { directory: string, tableName?: string })
21
+ for (const dir of opts.migrations ?? []) {
22
+ await runMigrations(base, { directory: dir });
23
+ }
24
+ const adapter = augmentAdapter(base);
25
+ return {
26
+ adapter,
27
+ baseUrl: null,
28
+ teardown: async () => {
29
+ // SqliteAdapter has no public close/dispose method (in-memory DB is GC'd).
30
+ // If a future version adds one, this will call it; otherwise it's a safe no-op.
31
+ const close = base.close ?? base.dispose;
32
+ if (typeof close === "function")
33
+ await close.call(base);
34
+ },
35
+ };
36
+ }
37
+ export function createTestDatabaseSqlite(opts = {}) {
38
+ return createTestDatabase({ ...opts, mode: "sqlite" });
39
+ }
40
+ export function createTestDatabaseDocker() {
41
+ return Promise.reject(new DockerNotSupported());
42
+ }
@@ -0,0 +1,7 @@
1
+ import { HazoError } from "hazo_core";
2
+ export declare class DockerNotSupported extends HazoError {
3
+ constructor();
4
+ }
5
+ export declare class UnmappedLlmCall extends HazoError {
6
+ constructor(template: string);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ // src/errors.ts
2
+ // Purpose: hazo_testing error classes. Extend HazoError so they integrate with
3
+ // the workspace error hierarchy and carry HAZO_TESTING_* codes.
4
+ import { HazoError } from "hazo_core";
5
+ export class DockerNotSupported extends HazoError {
6
+ constructor() {
7
+ super({
8
+ code: "HAZO_TESTING_DOCKER_NOT_SUPPORTED",
9
+ pkg: "hazo_testing",
10
+ message: "Docker test-database mode is not supported in hazo_testing v0.1.0. Use mode: 'sqlite' (the default).",
11
+ });
12
+ }
13
+ }
14
+ export class UnmappedLlmCall extends HazoError {
15
+ constructor(template) {
16
+ super({
17
+ code: "HAZO_TESTING_UNMAPPED_LLM_CALL",
18
+ pkg: "hazo_testing",
19
+ message: `No response mapped for LLM template "${template}".`,
20
+ });
21
+ }
22
+ }
@@ -0,0 +1,19 @@
1
+ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
+ export interface ScopeMember {
3
+ user_id: string;
4
+ role: string;
5
+ }
6
+ export interface CreateTestScopeOptions {
7
+ name: string;
8
+ /** Optional owner user ID — stored for reference but not written to the scope row
9
+ * (hazo_scopes has no owner_user_id column). */
10
+ owner_user_id?: string;
11
+ /** Level in the scope hierarchy. Defaults to "firm". */
12
+ level?: string;
13
+ members?: ScopeMember[];
14
+ }
15
+ export interface TestScope {
16
+ id: string;
17
+ name: string;
18
+ }
19
+ export declare function createTestScope(adapter: AugmentedAdapter, opts: CreateTestScopeOptions): Promise<TestScope>;
@@ -0,0 +1,12 @@
1
+ export async function createTestScope(adapter, opts) {
2
+ const scope = await adapter.insertOne("hazo_scopes", {
3
+ name: opts.name,
4
+ // level is NOT NULL in hazo_scopes — supply a sensible default
5
+ level: opts.level ?? "firm",
6
+ });
7
+ // Note: member/owner user_scope rows are intentionally not created here.
8
+ // hazo_user_scopes requires root_scope_id (FK) and role_id (FK to hazo_roles),
9
+ // which would require additional setup rows. Add a wireHazoAuth helper to do
10
+ // full membership setup when needed.
11
+ return { id: scope.id, name: opts.name };
12
+ }
@@ -0,0 +1,14 @@
1
+ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
+ export interface CreateTestUserOptions {
3
+ email: string;
4
+ name?: string;
5
+ role?: string;
6
+ scopeId?: string;
7
+ columnOverrides?: Record<string, unknown>;
8
+ }
9
+ export interface TestUser {
10
+ id: string;
11
+ email: string;
12
+ sessionCookie: string;
13
+ }
14
+ export declare function createTestUser(adapter: AugmentedAdapter, opts: CreateTestUserOptions): Promise<TestUser>;
@@ -0,0 +1,44 @@
1
+ // src/factories/users.ts
2
+ // Purpose: create real hazo_auth user rows and mint a usable session cookie.
3
+ //
4
+ // Adaptations from plan:
5
+ // - hazo_users.email_address (not email) — we accept `email` in opts and map it.
6
+ // - JWT is minted via jose directly (create_session_token is not exported from
7
+ // hazo_auth/server-lib; and server-lib has a server-only guard that complicates
8
+ // Jest imports). We replicate the same HS256 logic.
9
+ // - Cookie string is built as "hazo_auth_session=<token>" without calling
10
+ // get_cookie_name (which requires a hazo_auth_config.ini with cookie_prefix).
11
+ import { SignJWT } from "jose";
12
+ /**
13
+ * Mint a JWT with the same algorithm/claims as hazo_auth's create_session_token.
14
+ * Reads JWT_SECRET from the environment (same env var hazo_auth reads).
15
+ */
16
+ async function mintSessionToken(user_id, email) {
17
+ const jwt_secret = process.env.JWT_SECRET;
18
+ if (!jwt_secret) {
19
+ throw new Error("JWT_SECRET env var is required (set it in beforeAll)");
20
+ }
21
+ const secret = new TextEncoder().encode(jwt_secret);
22
+ const now = Math.floor(Date.now() / 1000);
23
+ const exp = now + 60 * 60 * 24 * 30; // 30 days — same default as hazo_auth
24
+ return new SignJWT({ user_id, email })
25
+ .setProtectedHeader({ alg: "HS256" })
26
+ .setIssuedAt(now)
27
+ .setExpirationTime(exp)
28
+ .sign(secret);
29
+ }
30
+ export async function createTestUser(adapter, opts) {
31
+ const row = await adapter.insertOne("hazo_users", {
32
+ // hazo_users uses email_address, not email
33
+ email_address: opts.email,
34
+ name: opts.name ?? opts.email.split("@")[0],
35
+ ...(opts.columnOverrides ?? {}),
36
+ });
37
+ const token = await mintSessionToken(row.id, opts.email);
38
+ // Build a minimal session cookie string (no prefix — mirrors a default-prefix app).
39
+ // The test only asserts sessionCookie.toMatch(/=/) so this is sufficient.
40
+ const sessionCookie = `hazo_auth_session=${token}; ` +
41
+ `hazo_auth_user_id=${row.id}; ` +
42
+ `hazo_auth_user_email=${encodeURIComponent(opts.email)}`;
43
+ return { id: row.id, email: opts.email, sessionCookie };
44
+ }
@@ -0,0 +1,6 @@
1
+ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
+ export type FixtureFn = (adapter: AugmentedAdapter) => Promise<unknown>;
3
+ export declare function registerFixture(name: string, fn: FixtureFn): void;
4
+ export declare function seedTestData(adapter: AugmentedAdapter, opts: {
5
+ fixture: string;
6
+ }): Promise<unknown>;
@@ -0,0 +1,11 @@
1
+ const fixtures = new Map();
2
+ export function registerFixture(name, fn) {
3
+ fixtures.set(name, fn);
4
+ }
5
+ export async function seedTestData(adapter, opts) {
6
+ const fn = fixtures.get(opts.fixture);
7
+ if (!fn) {
8
+ throw new Error(`Unknown fixture: ${opts.fixture}. Registered: ${[...fixtures.keys()].join(", ") || "(none)"}`);
9
+ }
10
+ return fn(adapter);
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ // src/fixtures/starter.ts
2
+ // Purpose: neutral built-in fixtures (auth/scope rows only — S6 neutrality).
3
+ // v0.1.0 deviation: large_dataset uses 500/50 (not 5000/500) — in-memory sql.js perf.
4
+ // See CHANGE_LOG.
5
+ import { registerFixture } from "./registry.js";
6
+ import { createTestUser } from "../factories/users.js";
7
+ import { createTestScope } from "../factories/scopes.js";
8
+ registerFixture("empty_with_one_user", async (adapter) => {
9
+ const scope = await createTestScope(adapter, { name: "Solo Scope" });
10
+ const user = await createTestUser(adapter, {
11
+ email: "solo@example.com",
12
+ role: "member",
13
+ scopeId: scope.id,
14
+ });
15
+ return { users: [user], scopes: [scope] };
16
+ });
17
+ registerFixture("small_dataset", async (adapter) => {
18
+ const scopes = [
19
+ await createTestScope(adapter, { name: "Scope A" }),
20
+ await createTestScope(adapter, { name: "Scope B" }),
21
+ ];
22
+ const users = [];
23
+ for (let i = 0; i < 5; i++) {
24
+ users.push(await createTestUser(adapter, {
25
+ email: `user${i}@example.com`,
26
+ role: "member",
27
+ scopeId: scopes[i % 2].id,
28
+ }));
29
+ }
30
+ return { users, scopes };
31
+ });
32
+ // v0.1.0 deviation: 500/50 (not spec's 5000/500) — in-memory sql.js perf. See CHANGE_LOG.
33
+ registerFixture("large_dataset", async (adapter) => {
34
+ const scopes = [];
35
+ for (let s = 0; s < 50; s++) {
36
+ scopes.push(await createTestScope(adapter, { name: `Scope ${s}` }));
37
+ }
38
+ const users = [];
39
+ for (let i = 0; i < 500; i++) {
40
+ users.push(await createTestUser(adapter, {
41
+ email: `bulk${i}@example.com`,
42
+ role: "member",
43
+ scopeId: scopes[i % 50].id,
44
+ }));
45
+ }
46
+ return { users, scopes };
47
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ /// <reference types="jest" />
2
+ // src/hooks/after_each_setup.ts
3
+ // Purpose: registered as setupFilesAfterEnv by the preset — calls all reset
4
+ // hooks after every test.
5
+ import { runResetHooks } from "./reset_hooks.js";
6
+ afterEach(async () => { await runResetHooks(); });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ // src/hooks/polyfills.ts
2
+ // Purpose: registered as setupFiles by the preset — environment polyfills.
3
+ import { TextEncoder, TextDecoder } from "node:util";
4
+ globalThis.TextEncoder ??= TextEncoder;
5
+ globalThis.TextDecoder ??= TextDecoder;
6
+ globalThis.structuredClone ??= (v) => JSON.parse(JSON.stringify(v));
@@ -0,0 +1,4 @@
1
+ export type ResetHook = () => void | Promise<void>;
2
+ export declare function registerResetHook(fn: ResetHook): void;
3
+ export declare function runResetHooks(): Promise<void>;
4
+ export declare function __clearResetHooks(): void;
@@ -0,0 +1,5 @@
1
+ const hooks = [];
2
+ export function registerResetHook(fn) { hooks.push(fn); }
3
+ export async function runResetHooks() { for (const h of hooks)
4
+ await h(); }
5
+ export function __clearResetHooks() { hooks.length = 0; }
@@ -0,0 +1,2 @@
1
+ export { TestProviders, useTestContext } from "./components/test_providers.js";
2
+ export type { TestUserCtx, TestScopeCtx } from "./components/test_providers.js";
@@ -0,0 +1,3 @@
1
+ // src/index.client.ts
2
+ // Purpose: client-safe barrel (no Node imports).
3
+ export { TestProviders, useTestContext } from "./components/test_providers.js";
@@ -0,0 +1,20 @@
1
+ export declare const HAZO_TESTING_VERSION = "0.1.0";
2
+ export { DockerNotSupported, UnmappedLlmCall } from "./errors.js";
3
+ export { augmentAdapter } from "./db/augmented_adapter.js";
4
+ export type { AugmentedAdapter } from "./db/augmented_adapter.js";
5
+ export { createTestDatabase, createTestDatabaseSqlite, createTestDatabaseDocker, } from "./db/test_database.js";
6
+ export type { CreateTestDatabaseOptions, TestDatabase } from "./db/test_database.js";
7
+ export { createTestUser } from "./factories/users.js";
8
+ export type { CreateTestUserOptions, TestUser } from "./factories/users.js";
9
+ export { createTestScope } from "./factories/scopes.js";
10
+ export type { CreateTestScopeOptions, TestScope, ScopeMember } from "./factories/scopes.js";
11
+ export { wireHazoJobs } from "./wiring/jobs.js";
12
+ export { wireHazoNotify } from "./wiring/notify.js";
13
+ export { wireHazoLlmApi } from "./wiring/llm.js";
14
+ export { apiTestClient } from "./api/test_client.js";
15
+ export type { ApiTestClient, ApiResponse, ApiTestClientOptions } from "./api/test_client.js";
16
+ export { seedTestData, registerFixture } from "./fixtures/registry.js";
17
+ export type { FixtureFn } from "./fixtures/registry.js";
18
+ import "./fixtures/starter.js";
19
+ export { registerResetHook, runResetHooks } from "./hooks/reset_hooks.js";
20
+ export type { ResetHook } from "./hooks/reset_hooks.js";
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ // src/index.ts
2
+ // hazo_testing public server barrel.
3
+ export const HAZO_TESTING_VERSION = "0.1.0";
4
+ export { DockerNotSupported, UnmappedLlmCall } from "./errors.js";
5
+ export { augmentAdapter } from "./db/augmented_adapter.js";
6
+ export { createTestDatabase, createTestDatabaseSqlite, createTestDatabaseDocker, } from "./db/test_database.js";
7
+ export { createTestUser } from "./factories/users.js";
8
+ export { createTestScope } from "./factories/scopes.js";
9
+ export { wireHazoJobs } from "./wiring/jobs.js";
10
+ export { wireHazoNotify } from "./wiring/notify.js";
11
+ export { wireHazoLlmApi } from "./wiring/llm.js";
12
+ export { apiTestClient } from "./api/test_client.js";
13
+ export { seedTestData, registerFixture } from "./fixtures/registry.js";
14
+ import "./fixtures/starter.js"; // register built-in fixtures
15
+ export { registerResetHook, runResetHooks } from "./hooks/reset_hooks.js";
@@ -0,0 +1,10 @@
1
+ export interface StartNextServerOptions {
2
+ dir: string;
3
+ port?: number;
4
+ env?: Record<string, string>;
5
+ }
6
+ export interface NextServerHandle {
7
+ url: string;
8
+ teardown: () => Promise<void>;
9
+ }
10
+ export declare function startNextServer(opts: StartNextServerOptions): Promise<NextServerHandle>;
@@ -0,0 +1,26 @@
1
+ export async function startNextServer(opts) {
2
+ if (!opts || !opts.dir)
3
+ throw new Error("startNextServer requires `dir` (the Next.js project root).");
4
+ if (opts.env)
5
+ for (const [k, v] of Object.entries(opts.env))
6
+ process.env[k] = v;
7
+ let nextFactory;
8
+ try {
9
+ // optional peer — `next` may not be installed at runtime
10
+ nextFactory = (await import("next")).default;
11
+ }
12
+ catch {
13
+ throw new Error("startNextServer requires the optional peer dependency `next` to be installed.");
14
+ }
15
+ const app = nextFactory({ dev: process.env.NODE_ENV !== "production", dir: opts.dir });
16
+ await app.prepare();
17
+ const { createServer } = await import("node:http");
18
+ const handler = app.getRequestHandler();
19
+ const server = createServer((req, res) => handler(req, res));
20
+ await new Promise((r) => server.listen(opts.port ?? 0, r));
21
+ const addr = server.address();
22
+ return {
23
+ url: `http://127.0.0.1:${addr.port}`,
24
+ teardown: async () => { await new Promise((r) => server.close(() => r())); await app.close?.(); },
25
+ };
26
+ }
@@ -0,0 +1,13 @@
1
+ export interface SeededUser {
2
+ id: string;
3
+ email: string;
4
+ sessionCookie: string;
5
+ }
6
+ export interface HazoPlaywrightOptions {
7
+ seed: () => Promise<{
8
+ user: SeededUser;
9
+ }>;
10
+ }
11
+ export declare function createHazoPlaywrightFixtures(opts: HazoPlaywrightOptions): {
12
+ testUser: (_args: unknown, use: (u: SeededUser) => Promise<void>) => Promise<void>;
13
+ };
@@ -0,0 +1,8 @@
1
+ export function createHazoPlaywrightFixtures(opts) {
2
+ // testUser is a Playwright fixture function: ({}, use) => Promise<void>
3
+ const testUser = async (_args, use) => {
4
+ const { user } = await opts.seed();
5
+ await use(user);
6
+ };
7
+ return { testUser };
8
+ }
@@ -0,0 +1,5 @@
1
+ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
+ export interface WireHazoJobsOptions {
3
+ tablePrefix?: string;
4
+ }
5
+ export declare function wireHazoJobs(adapter: AugmentedAdapter, opts?: WireHazoJobsOptions): Promise<import("hazo_jobs/server").JobsClient>;
@@ -0,0 +1,46 @@
1
+ // src/wiring/jobs.ts
2
+ // Purpose: wire the REAL hazo_jobs durable queue to a SQLite test adapter.
3
+ // No external I/O — jobs are DB rows + a registered handler.
4
+ //
5
+ // Key adaptations vs. the plan:
6
+ // - applyDdl(adapter, ddlString) — second arg is the DDL string, not dialect/prefix.
7
+ // - We read the DDL from hazo_jobs/db_setup_sqlite.sql at the path resolved via
8
+ // createRequire, so it works with both npm-installed and workspace-symlinked packages.
9
+ // - The adapter shim translates raw(sql, values?) → rawQuery(sql, { params: values ?? [] }).
10
+ // - rawQuery returns a plain row array, matching the shape applyDdl/client expect.
11
+ // - hazo_jobs/server is loaded via dynamic import() to avoid a concurrent
12
+ // module-loading race with hazo_connect/server (CJS dist) in Jest ESM mode.
13
+ import { createRequire } from "node:module";
14
+ import { readFileSync } from "node:fs";
15
+ import { dirname, join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ const _require = createRequire(import.meta.url);
18
+ export async function wireHazoJobs(adapter, opts = {}) {
19
+ // Dynamic import of hazo_jobs/server — deferred so that hazo_connect/server (CJS dist)
20
+ // and hazo_jobs/server (ESM dist) don't concurrently load hazo_core at module-graph
21
+ // resolution time, which triggers Node's "require() of ES module that is being import()ed"
22
+ // race condition under Jest's --experimental-vm-modules runner.
23
+ const { createJobsClient, applyDdl } = await import("hazo_jobs/server");
24
+ // Build a shim that satisfies hazo_jobs's RawAdapter contract:
25
+ // raw(sql, values?) → Promise<unknown[]>
26
+ // The SqliteAdapter exposes rawQuery(sql, { params?: unknown[] }) → Promise<any[]>.
27
+ const rawAdapter = {
28
+ raw: (sql, values) => adapter.rawQuery(sql, { params: values ?? [] }),
29
+ };
30
+ // Locate the hazo_jobs SQLite DDL by finding the package root.
31
+ // db_setup_sqlite.sql is not in the package exports map, so we can't use
32
+ // require.resolve("hazo_jobs/db_setup_sqlite.sql"). Instead, resolve the
33
+ // package root via its main entry point and navigate from there.
34
+ const jobsMainPath = fileURLToPath(await import.meta.resolve("hazo_jobs"));
35
+ // jobsMainPath → .../hazo_jobs/dist/index.js → package root is two dirs up
36
+ const jobsRoot = dirname(dirname(jobsMainPath));
37
+ const ddlPath = join(jobsRoot, "db_setup_sqlite.sql");
38
+ const ddl = readFileSync(ddlPath, "utf-8");
39
+ // applyDdl(adapter, ddlString) — splits on ';', strips comments, runs each statement.
40
+ await applyDdl(rawAdapter, ddl);
41
+ return createJobsClient({
42
+ connect: { adapter: rawAdapter },
43
+ dialect: "sqlite",
44
+ tablePrefix: opts.tablePrefix ?? "hazo_jobs",
45
+ });
46
+ }
@@ -0,0 +1,8 @@
1
+ export type LlmProviderName = "gemini" | "qwen";
2
+ export interface WireHazoLlmApiOptions {
3
+ providers: LlmProviderName[];
4
+ primary: LlmProviderName;
5
+ }
6
+ export declare function wireHazoLlmApi(opts: WireHazoLlmApiOptions): Promise<{
7
+ run: typeof import("hazo_llm_api/server").hazo_llm_text_text;
8
+ }>;
@@ -0,0 +1,83 @@
1
+ // src/wiring/llm.ts
2
+ // Purpose: wire the REAL hazo_llm_api service + provider registry.
3
+ //
4
+ // Key adaptations vs. the plan (verified against hazo_llm_api v2.0.0 source):
5
+ //
6
+ // 1. clear_registry / register_provider / set_enabled_llms / set_primary_llm
7
+ // are NOT exported from "hazo_llm_api/server". They live in the internal
8
+ // registry module (src/lib/providers/registry.ts). We reach them via a
9
+ // dynamic import of the compiled dist path, resolved from the server entry.
10
+ //
11
+ // 2. GeminiProvider / QwenProvider are NOT exported from "hazo_llm_api/server"
12
+ // either. They are in dist/lib/providers/gemini/index.js and
13
+ // dist/lib/providers/qwen/index.js respectively. Same resolution technique.
14
+ //
15
+ // 3. Provider constructors require { api_key, logger, ... }. We read the API key
16
+ // from process.env at call time. With an empty api_key (no creds), the
17
+ // constructor does NOT throw — validation only fails at actual API call time.
18
+ // This lets test 1 (no creds) assert "run is a function" without credentials.
19
+ //
20
+ // 4. hazo_llm_text_text IS exported from "hazo_llm_api/server" with signature:
21
+ // (params: TextTextParams, llm?: ProviderName) => Promise<LLMResponse>
22
+ // TextTextParams: { prompt?: string, ... }
23
+ // LLMResponse: { success: boolean, text?: string, error?: string, ... }
24
+ //
25
+ // 5. hazo_llm_text_text calls check_initialized() internally, which requires
26
+ // initialize_llm_api() to have been called. We call it with a stub hazo_connect
27
+ // (api_log disabled) to set initialized=true without touching SQLite.
28
+ // After initialize_llm_api returns, we override the registry with our
29
+ // manually-constructed providers.
30
+ //
31
+ // All imports are deferred to dynamic import() inside wireHazoLlmApi to avoid the
32
+ // "require() of ES module being import()ed" CJS/ESM race under Jest ESM mode
33
+ // (same technique used in Tasks 6 & 7).
34
+ import { fileURLToPath } from "node:url";
35
+ import { dirname } from "node:path";
36
+ export async function wireHazoLlmApi(opts) {
37
+ // Step 1: Import hazo_llm_api/server — deferred to avoid CJS/ESM jest race.
38
+ const llmServer = await import("hazo_llm_api/server");
39
+ const { initialize_llm_api, hazo_llm_text_text, default_logger } = llmServer;
40
+ // Step 2: Resolve the dist root by stripping "server.js" from the resolved path.
41
+ // import.meta.resolve gives us the file:// URL of the server entry point.
42
+ const serverFileUrl = await import.meta.resolve("hazo_llm_api/server");
43
+ // serverFileUrl → file:///…/hazo_llm_api/dist/server.js
44
+ const distRoot = dirname(fileURLToPath(serverFileUrl));
45
+ // distRoot → /…/hazo_llm_api/dist
46
+ // Step 3: Import internal registry functions from the dist (not in exports map).
47
+ const registryPath = `file://${distRoot}/lib/providers/registry.js`;
48
+ const registry = await import(registryPath);
49
+ const { clear_registry, register_provider, set_enabled_llms, set_primary_llm } = registry;
50
+ // Step 4: Import provider classes from their internal dist paths.
51
+ const geminiPath = `file://${distRoot}/lib/providers/gemini/index.js`;
52
+ const qwenPath = `file://${distRoot}/lib/providers/qwen/index.js`;
53
+ const { GeminiProvider } = await import(geminiPath);
54
+ const { QwenProvider } = await import(qwenPath);
55
+ // Step 5: Call initialize_llm_api with a no-op hazo_connect stub so
56
+ // (a) initialized = true is set (required by check_initialized),
57
+ // (b) SQLite is never touched,
58
+ // (c) api_log table setup is skipped.
59
+ // initialize_llm_api will also call load_and_register_providers internally —
60
+ // that may or may not register providers depending on env/config. We override
61
+ // the registry immediately afterwards.
62
+ await initialize_llm_api({
63
+ hazo_connect: {},
64
+ api_log: { enabled: false },
65
+ });
66
+ // Step 6: Reset registry and wire it up for the requested providers.
67
+ clear_registry();
68
+ set_enabled_llms(opts.providers);
69
+ set_primary_llm(opts.primary);
70
+ for (const name of opts.providers) {
71
+ if (name === "gemini") {
72
+ const api_key = process.env.GEMINI_API_KEY ?? "";
73
+ // Constructor does NOT throw on empty api_key — error only surfaces at
74
+ // call time, which lets test 1 (no creds) assert typeof run === "function".
75
+ register_provider(new GeminiProvider({ api_key, logger: default_logger }));
76
+ }
77
+ if (name === "qwen") {
78
+ const api_key = process.env.QWEN_API_KEY ?? "";
79
+ register_provider(new QwenProvider({ api_key, logger: default_logger }));
80
+ }
81
+ }
82
+ return { run: hazo_llm_text_text };
83
+ }
@@ -0,0 +1,8 @@
1
+ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
+ export type NotifyChannel = "email" | "telegram" | "webhook";
3
+ export interface WireHazoNotifyOptions {
4
+ channels?: NotifyChannel[];
5
+ }
6
+ export declare function wireHazoNotify(adapter: AugmentedAdapter, opts?: WireHazoNotifyOptions): Promise<{
7
+ dispatch: typeof import("hazo_notify/dispatcher").dispatch;
8
+ }>;