@ultimat3/testing 30.8.0 → 31.0.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/CLAUDE.md +49 -62
- package/README.md +179 -39
- package/package.json +23 -17
- package/src/ai-conformance-answer.ts +67 -0
- package/src/ai-gateway-conformance.ts +105 -0
- package/src/ai-provider-conformance.ts +69 -0
- package/src/ai-provider-transport-conformance.ts +170 -0
- package/src/audit-sink-conformance.ts +204 -0
- package/src/auth-adapter-conformance-credentials.ts +124 -0
- package/src/auth-adapter-conformance-mfa.ts +70 -0
- package/src/auth-adapter-conformance-passkeys.ts +133 -0
- package/src/auth-adapter-conformance-sessions.ts +115 -0
- package/src/auth-adapter-conformance-support.ts +71 -0
- package/src/auth-adapter-conformance-users.ts +128 -0
- package/src/auth-adapter-conformance.ts +34 -0
- package/src/auth-limiter-factory-conformance.ts +224 -0
- package/src/auth-server-store-conformance-records.ts +69 -0
- package/src/auth-server-store-conformance.ts +208 -0
- package/src/cache-tier-conformance-checks.ts +142 -0
- package/src/cache-tier-conformance.ts +24 -0
- package/src/cassette-format.ts +8 -13
- package/src/cassette-record.ts +1 -1
- package/src/cdp-browser.ts +10 -11
- package/src/cdp-e2e-page.ts +2 -2
- package/src/cdp-e2e-session.ts +2 -2
- package/src/cdp-network-probe.ts +1 -1
- package/src/cdp-offline-script.ts +2 -2
- package/src/clock-conformance.ts +126 -0
- package/src/conformance.ts +239 -0
- package/src/e2e-browser-handle.ts +1 -2
- package/src/e2e-error-codes.ts +17 -16
- package/src/e2e-run.ts +4 -3
- package/src/embedder-conformance.ts +101 -0
- package/src/entity-conformance-aggregates.ts +210 -0
- package/src/entity-conformance-batches.ts +216 -0
- package/src/entity-conformance-bulk.ts +379 -0
- package/src/entity-conformance-checks.ts +27 -0
- package/src/entity-conformance-entities.ts +52 -0
- package/src/entity-conformance-locks.ts +286 -0
- package/src/entity-conformance-matrix.ts +397 -0
- package/src/entity-conformance-reads.ts +241 -0
- package/src/entity-conformance-support.ts +56 -0
- package/src/entity-conformance-tenancy.ts +296 -0
- package/src/entity-conformance-values.ts +305 -0
- package/src/entity-conformance-versions.ts +60 -0
- package/src/entity-conformance-writes.ts +348 -0
- package/src/entity-driver-conformance.ts +103 -0
- package/src/error-groups-store-conformance.ts +198 -0
- package/src/error-reporter-conformance.ts +119 -0
- package/src/errors.ts +41 -11
- package/src/event-bus-conformance.ts +161 -0
- package/src/exercise-drift-hint.ts +4 -1
- package/src/exercise-judge.ts +5 -3
- package/src/exercise-override-input.ts +22 -9
- package/src/exercise-override-line.ts +98 -0
- package/src/exercise-report.ts +30 -51
- package/src/exercise-sweeps.ts +3 -1
- package/src/exercise.ts +38 -19
- package/src/factories.ts +192 -179
- package/src/factory-api.ts +131 -0
- package/src/factory-associations.ts +67 -0
- package/src/factory-errors.ts +38 -0
- package/src/factory-lint.ts +92 -0
- package/src/factory-persist.ts +74 -16
- package/src/factory-pipeline.ts +191 -0
- package/src/factory-registry.ts +2 -1
- package/src/factory-types.ts +131 -0
- package/src/failure-store-conformance.ts +137 -0
- package/src/fixture-jobs.ts +50 -15
- package/src/fixture-mail.ts +7 -7
- package/src/fixture-seed.ts +111 -0
- package/src/fixture-statements.ts +68 -52
- package/src/framework-fixtures.ts +1 -1
- package/src/idempotency-store-conformance.ts +186 -0
- package/src/idempotency-store-replay-conformance.ts +140 -0
- package/src/idempotency-store-tx-conformance.ts +132 -0
- package/src/idempotency-store-world-conformance.ts +82 -0
- package/src/identity-provider-conformance.ts +144 -0
- package/src/image-transform-conformance.ts +89 -0
- package/src/index.ts +68 -157
- package/src/isr-store-conformance.ts +113 -0
- package/src/job-sim-effects.ts +19 -31
- package/src/job-sim-world.ts +6 -15
- package/src/lease-store-conformance.ts +195 -0
- package/src/mail-driver-conformance.ts +108 -0
- package/src/matcher-doubles.ts +104 -0
- package/src/matcher-stub.ts +78 -0
- package/src/matcher-surface.ts +21 -0
- package/src/matchers.ts +19 -1
- package/src/mcp-confirmation-store-conformance.ts +262 -0
- package/src/meter-store-conformance.ts +135 -0
- package/src/notify-digest-conformance.ts +133 -0
- package/src/notify-inbox-conformance.ts +130 -0
- package/src/notify-ledger-conformance.ts +134 -0
- package/src/notify-preference-conformance.ts +49 -0
- package/src/notify-stores-conformance.ts +73 -0
- package/src/outbox-store-conformance-claims.ts +112 -0
- package/src/outbox-store-conformance-subject.ts +65 -0
- package/src/outbox-store-conformance.ts +71 -0
- package/src/per-test-reset.ts +55 -20
- package/src/plan-oracle.ts +10 -3
- package/src/plan-sweep.ts +37 -12
- package/src/preload.ts +4 -2
- package/src/purge-conformance.ts +79 -0
- package/src/push-device-conformance.ts +124 -0
- package/src/push-subscription-conformance.ts +123 -0
- package/src/quiet-logs.ts +4 -4
- package/src/rate-limit-store-conformance.ts +178 -0
- package/src/registry-leak-error.ts +8 -1
- package/src/scale-sweep-run.ts +3 -1
- package/src/scrape-driver-conformance-frame-checks.ts +97 -0
- package/src/scrape-driver-conformance-page-checks.ts +114 -0
- package/src/scrape-driver-conformance-site.ts +84 -0
- package/src/scrape-driver-conformance.ts +34 -0
- package/src/sealed-dns-resolver.ts +56 -0
- package/src/sealed-dns.ts +63 -64
- package/src/sealed-network.ts +13 -12
- package/src/sealed-node-sockets.ts +63 -0
- package/src/sealed-sockets.ts +13 -8
- package/src/sealed-udp.ts +118 -0
- package/src/search-index-conformance-list.ts +76 -0
- package/src/search-index-conformance-support.ts +69 -0
- package/src/search-index-conformance-versions.ts +66 -0
- package/src/search-index-conformance.ts +126 -0
- package/src/secret-source-conformance.ts +91 -0
- package/src/seed-factories.ts +57 -0
- package/src/seed-writer.ts +8 -19
- package/src/semantic-cache-factory-conformance.ts +86 -0
- package/src/sms-transport-conformance.ts +102 -0
- package/src/step-store-conformance.ts +171 -0
- package/src/storage-conformance-read-checks.ts +132 -0
- package/src/storage-conformance-shape.ts +121 -0
- package/src/storage-conformance-stream-checks.ts +226 -0
- package/src/storage-conformance.ts +34 -0
- package/src/stub-action.ts +24 -0
- package/src/stub-errors.ts +86 -0
- package/src/stub-job.ts +30 -0
- package/src/stub-query.ts +25 -0
- package/src/stub-script.ts +76 -0
- package/src/stub-stack.ts +29 -0
- package/src/stub.ts +73 -0
- package/src/swap-adapter.ts +135 -0
- package/src/test-scope.ts +96 -0
- package/src/test-types.ts +1 -1
- package/src/totp-replay-guard-conformance.ts +76 -0
- package/src/transport-conformance.ts +179 -0
- package/src/upload-scanner-conformance.ts +112 -0
- package/src/vector-store-conformance-checks.ts +174 -0
- package/src/vector-store-conformance.ts +21 -0
- package/src/cdp-connection.ts +0 -291
- package/src/cdp-errors.ts +0 -179
- package/src/cdp-launch-attempt.ts +0 -224
- package/src/cdp-launch-candidates.ts +0 -62
- package/src/cdp-launch-profile.ts +0 -106
- package/src/cdp-launch-reap.ts +0 -68
- package/src/cdp-launch-wire.ts +0 -171
- package/src/cdp-launch.ts +0 -175
- package/src/cdp-pipe.ts +0 -77
- package/src/cdp-wire-watch.ts +0 -113
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// The factory lint: every factory, bare and with each trait alone, built AND created against its own
|
|
2
|
+
// entity — `$parse` and the invariants judge the built row, a throwaway memory driver the created
|
|
3
|
+
// one. What a test would have found one failure at a time, found at once.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError, renderCauseValue, stringField } from '@ultimat3/core';
|
|
6
|
+
import type { AnyFactory } from './factory-api';
|
|
7
|
+
import { type FactoryFinding, FactoryInvalidError } from './factory-errors';
|
|
8
|
+
import { entityPersister, isEntity, swapPersister } from './factory-persist';
|
|
9
|
+
import type { EntityLike } from './factory-types';
|
|
10
|
+
|
|
11
|
+
/** The factories to judge, keyed by the name a finding reports. */
|
|
12
|
+
export type FactorySet = Readonly<Record<string, AnyFactory>>;
|
|
13
|
+
|
|
14
|
+
const findingOf = (
|
|
15
|
+
where: Pick<FactoryFinding, 'factory' | 'trait' | 'strategy'>,
|
|
16
|
+
error: unknown,
|
|
17
|
+
): FactoryFinding => ({
|
|
18
|
+
...where,
|
|
19
|
+
code: isUltimateError(error) ? error.code : 'X_TEST_FACTORY_INVALID',
|
|
20
|
+
cause: stringField(error, 'cause') ?? stringField(error, 'message') ?? renderCauseValue(error),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** A built key the entity declares no column for: `$parse` would drop it, and the test with it. */
|
|
24
|
+
const unknownColumns = (entity: EntityLike, row: object): readonly string[] =>
|
|
25
|
+
Object.keys(row).filter((key) => !Object.hasOwn(entity.$columns, key));
|
|
26
|
+
|
|
27
|
+
/** Build, judge, create; each failure a finding, never a throw. */
|
|
28
|
+
async function judge(
|
|
29
|
+
factory: AnyFactory,
|
|
30
|
+
where: Pick<FactoryFinding, 'factory' | 'trait'>,
|
|
31
|
+
): Promise<readonly FactoryFinding[]> {
|
|
32
|
+
const findings: FactoryFinding[] = [];
|
|
33
|
+
const { entity } = factory;
|
|
34
|
+
try {
|
|
35
|
+
const row = factory.build();
|
|
36
|
+
const extra = unknownColumns(entity, row);
|
|
37
|
+
if (extra.length > 0) {
|
|
38
|
+
findings.push({
|
|
39
|
+
...where,
|
|
40
|
+
strategy: 'build',
|
|
41
|
+
code: 'X_TEST_FACTORY_INVALID',
|
|
42
|
+
cause: `${entity.$table} declares no column ${extra.join(', ')}`,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (isEntity(entity)) entity.$assert(entity.$parse(row));
|
|
46
|
+
} catch (error: unknown) {
|
|
47
|
+
findings.push(findingOf({ ...where, strategy: 'build' }, error));
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
await factory.create();
|
|
51
|
+
} catch (error: unknown) {
|
|
52
|
+
findings.push(findingOf({ ...where, strategy: 'create' }, error));
|
|
53
|
+
}
|
|
54
|
+
return findings;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Every factory and every trait of it, each from a restarted sequence into its OWN fresh memory
|
|
59
|
+
* driver: one shared driver made the second factory's org repeat the first's key — a finding about
|
|
60
|
+
* the lint, not the factory. The app's rows are never touched, and the sequences are restarted
|
|
61
|
+
* after, so a lint run leaves no trace on the suite.
|
|
62
|
+
*/
|
|
63
|
+
export async function lintFactories(factories: FactorySet): Promise<readonly FactoryFinding[]> {
|
|
64
|
+
const { memoryDriver } = await import('@ultimat3/entity');
|
|
65
|
+
const previous = swapPersister(undefined);
|
|
66
|
+
const findings: FactoryFinding[] = [];
|
|
67
|
+
const isolated = async (
|
|
68
|
+
factory: AnyFactory,
|
|
69
|
+
where: Pick<FactoryFinding, 'factory' | 'trait'>,
|
|
70
|
+
): Promise<void> => {
|
|
71
|
+
factory.reset();
|
|
72
|
+
swapPersister(entityPersister({ driver: memoryDriver() }));
|
|
73
|
+
findings.push(...(await judge(factory, where)));
|
|
74
|
+
};
|
|
75
|
+
try {
|
|
76
|
+
for (const [name, factory] of Object.entries(factories)) {
|
|
77
|
+
await isolated(factory, { factory: name, trait: null });
|
|
78
|
+
for (const trait of factory.traits)
|
|
79
|
+
await isolated(factory.with(trait), { factory: name, trait });
|
|
80
|
+
factory.reset();
|
|
81
|
+
}
|
|
82
|
+
} finally {
|
|
83
|
+
swapPersister(previous);
|
|
84
|
+
}
|
|
85
|
+
return findings;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** `lintFactories`, as one coded failure listing every finding: `X_TEST_FACTORY_INVALID`. */
|
|
89
|
+
export async function assertFactoriesValid(factories: FactorySet): Promise<void> {
|
|
90
|
+
const [first, ...rest] = await lintFactories(factories);
|
|
91
|
+
if (first !== undefined) throw new FactoryInvalidError([first, ...rest]);
|
|
92
|
+
}
|
package/src/factory-persist.ts
CHANGED
|
@@ -1,41 +1,99 @@
|
|
|
1
|
-
// The one seam a factory's `create()` writes through
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The one seam a factory's `create()` writes through, and its default: the entity's own repository
|
|
2
|
+
// on the process driver, the one `database()` reads through. Structural over `EntityLike` so the
|
|
3
|
+
// barrel stays entity-free — `@ultimat3/entity` loads on the first write, never on import.
|
|
4
4
|
|
|
5
|
+
import type { DbClient } from '@ultimat3/db';
|
|
6
|
+
import type { Driver, EntityCore, Repo } from '@ultimat3/entity';
|
|
5
7
|
import { FactoryNotPersistedError } from './errors';
|
|
8
|
+
import type { EntityLike } from './factory-types';
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
|
-
* Writes
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
* persister owns only whether the row exists.
|
|
11
|
+
* Writes one built row and answers the row AS STORED — declared defaults, generated columns and
|
|
12
|
+
* timestamps included. `create()` returns exactly this, so a test asserts on what the table holds,
|
|
13
|
+
* never on what the factory meant to write.
|
|
12
14
|
*/
|
|
13
15
|
export interface Persister {
|
|
14
|
-
insert
|
|
16
|
+
insert(entity: EntityLike, row: object): Promise<object>;
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
let current: Persister | undefined;
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
+
* Replace the default writer, once, in the test preload: `usePersister(entityPersister({ driver }))`
|
|
23
|
+
* for an app that names its own driver. Process-global for the reason the fixture registry is: a
|
|
24
|
+
* factory is imported by the file under test, not handed to it.
|
|
22
25
|
*/
|
|
23
26
|
export function usePersister(persister: Persister): void {
|
|
24
27
|
current = persister;
|
|
25
28
|
}
|
|
26
29
|
|
|
27
|
-
/** Hand the process back. An `afterAll` in any file that installed one of its own. */
|
|
30
|
+
/** Hand the process back to the default. An `afterAll` in any file that installed one of its own. */
|
|
28
31
|
export function clearPersister(): void {
|
|
29
32
|
current = undefined;
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
export const persisterInstalled = (): boolean => current !== undefined;
|
|
33
36
|
|
|
37
|
+
/** Install for one run and hand back what was there: the factory lint's own throwaway writer. */
|
|
38
|
+
export function swapPersister(next: Persister | undefined): Persister | undefined {
|
|
39
|
+
const previous = current;
|
|
40
|
+
current = next;
|
|
41
|
+
return previous;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Where `entityPersister` writes. One or the other: two answers to one question is a compile error. */
|
|
45
|
+
export type PersisterTarget =
|
|
46
|
+
/** Postgres (or PGlite) through this client: `postgresRepo(entity, { client })`. */
|
|
47
|
+
| { readonly client: DbClient; readonly driver?: never }
|
|
48
|
+
/** This driver's repositories. Left out: `defaultDriver()`, the one `database()` names by default. */
|
|
49
|
+
| { readonly driver?: Driver; readonly client?: never };
|
|
50
|
+
|
|
51
|
+
/** A real `entity()` value: the only kind a repository can be built over. */
|
|
52
|
+
export const isEntity = (entity: EntityLike): entity is EntityLike & EntityCore =>
|
|
53
|
+
typeof entity.$parse === 'function' &&
|
|
54
|
+
'$describe' in entity &&
|
|
55
|
+
typeof entity.$describe === 'function' &&
|
|
56
|
+
'$name' in entity;
|
|
57
|
+
|
|
58
|
+
/** The tenant a write runs under: the row's own tenant column, as a script has no actor. */
|
|
59
|
+
export const tenantScope = (entity: EntityLike, row: object): { orgId?: string } => {
|
|
60
|
+
const column = entity.$tenantColumn ?? null;
|
|
61
|
+
const value = column === null ? undefined : (row as Readonly<Record<string, unknown>>)[column];
|
|
62
|
+
return typeof value === 'string' ? { orgId: value } : {};
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Through the entity's own repository: `$parse` fills declared defaults and validates every
|
|
67
|
+
* column, the repository runs the invariants and answers the stored row (`returning *` on Postgres).
|
|
68
|
+
*/
|
|
69
|
+
export function entityPersister(target: PersisterTarget = {}): Persister {
|
|
70
|
+
let make: Promise<(entity: EntityCore) => Repo<unknown>> | undefined;
|
|
71
|
+
const resolve = async (): Promise<(entity: EntityCore) => Repo<unknown>> => {
|
|
72
|
+
const { defaultDriver, postgresRepo } = await import('@ultimat3/entity');
|
|
73
|
+
const { client } = target;
|
|
74
|
+
if (client !== undefined) return (entity) => postgresRepo(entity, { client });
|
|
75
|
+
const driver = target.driver ?? defaultDriver();
|
|
76
|
+
return (entity) => driver.repo(entity);
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
async insert(entity, row) {
|
|
80
|
+
if (!isEntity(entity)) throw new FactoryNotPersistedError({ table: entity.$table });
|
|
81
|
+
make ??= resolve();
|
|
82
|
+
const repo = (await make)(entity);
|
|
83
|
+
// `$parse` answers the entity's row type, which a `Repo<unknown>` spells as `RowWrite<unknown>`.
|
|
84
|
+
const parsed = entity.$parse(row) as Parameters<Repo<unknown>['insert']>[0];
|
|
85
|
+
const stored = await repo.insert(parsed, tenantScope(entity, row));
|
|
86
|
+
return stored as object;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const fallback = entityPersister();
|
|
92
|
+
|
|
34
93
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
94
|
+
* The installed persister, else the entity repository on the process driver. A lookalike with no
|
|
95
|
+
* `$parse` has no repository, so with nothing installed it is `X_TEST_FACTORY_NOT_PERSISTED`.
|
|
37
96
|
*/
|
|
38
|
-
export async function persistRow
|
|
39
|
-
|
|
40
|
-
await current.insert(table, row);
|
|
97
|
+
export async function persistRow(entity: EntityLike, row: object): Promise<object> {
|
|
98
|
+
return (current ?? fallback).insert(entity, row);
|
|
41
99
|
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// One row's pipeline, written ONCE for both strategies: a generator that yields what it needs — a
|
|
2
|
+
// parent, a child, a write, a callback — and lets the caller decide how. `build()` answers each
|
|
3
|
+
// yield synchronously in memory, `create()` awaits the database; the order of every step, and so
|
|
4
|
+
// every seeded draw, is the same in both.
|
|
5
|
+
|
|
6
|
+
import { referencedBy } from './factory-associations';
|
|
7
|
+
import type {
|
|
8
|
+
BelongsTo,
|
|
9
|
+
EntityLike,
|
|
10
|
+
FactoryContext,
|
|
11
|
+
FactoryIds,
|
|
12
|
+
FactoryLike,
|
|
13
|
+
HasMany,
|
|
14
|
+
Trait,
|
|
15
|
+
} from './factory-types';
|
|
16
|
+
|
|
17
|
+
type Bag = Record<string, unknown>;
|
|
18
|
+
|
|
19
|
+
/** A factory's declaration with its types erased: what the pipeline runs. */
|
|
20
|
+
export interface FactorySpec {
|
|
21
|
+
readonly entity: EntityLike;
|
|
22
|
+
readonly defaults: (index: number, ids: FactoryIds, transient: Bag) => object;
|
|
23
|
+
readonly traits: Readonly<Record<string, Trait<object, Bag>>>;
|
|
24
|
+
readonly transient: Readonly<Bag>;
|
|
25
|
+
readonly belongsTo: readonly (readonly [string, BelongsTo<object, object, string>])[];
|
|
26
|
+
readonly hasMany: readonly (readonly [string, HasMany<object, object, string>])[];
|
|
27
|
+
readonly afterBuild: readonly ((row: object, context: FactoryContext<Bag>) => void)[];
|
|
28
|
+
readonly afterCreate: readonly ((row: object, context: FactoryContext<Bag>) => unknown)[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type Step =
|
|
32
|
+
| { readonly kind: 'parent' | 'child'; readonly factory: FactoryLike; readonly over: object }
|
|
33
|
+
| { readonly kind: 'persist'; readonly row: object }
|
|
34
|
+
| { readonly kind: 'callback'; readonly run: () => unknown };
|
|
35
|
+
|
|
36
|
+
interface Split {
|
|
37
|
+
readonly columns: Bag;
|
|
38
|
+
readonly transient: Bag;
|
|
39
|
+
readonly parents: ReadonlyMap<string, Bag>;
|
|
40
|
+
readonly many: ReadonlyMap<string, number | readonly object[]>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** An override key is a transient, a `belongsTo` name, a `hasMany` name — or a column. */
|
|
44
|
+
function split(spec: FactorySpec, over: object): Split {
|
|
45
|
+
const columns: Bag = {};
|
|
46
|
+
const transient: Bag = { ...spec.transient };
|
|
47
|
+
const parents = new Map<string, Bag>();
|
|
48
|
+
const many = new Map<string, number | readonly object[]>();
|
|
49
|
+
const parentNames = new Set(spec.belongsTo.map(([name]) => name));
|
|
50
|
+
const manyNames = new Set(spec.hasMany.map(([name]) => name));
|
|
51
|
+
for (const [key, value] of Object.entries(over)) {
|
|
52
|
+
if (Object.hasOwn(spec.transient, key)) transient[key] = value;
|
|
53
|
+
else if (parentNames.has(key)) parents.set(key, value as Bag);
|
|
54
|
+
else if (manyNames.has(key)) many.set(key, value as number | readonly object[]);
|
|
55
|
+
else columns[key] = value;
|
|
56
|
+
}
|
|
57
|
+
return { columns, transient, parents, many };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Traits left to right, then the call's columns: the patch every association must respect. */
|
|
61
|
+
function patchOf(
|
|
62
|
+
spec: FactorySpec,
|
|
63
|
+
applied: readonly string[],
|
|
64
|
+
parts: Split,
|
|
65
|
+
index: number,
|
|
66
|
+
ids: FactoryIds,
|
|
67
|
+
): Bag {
|
|
68
|
+
let patch: Bag = {};
|
|
69
|
+
for (const name of applied) {
|
|
70
|
+
const trait = spec.traits[name];
|
|
71
|
+
patch = {
|
|
72
|
+
...patch,
|
|
73
|
+
...(typeof trait === 'function' ? trait(index, ids, parts.transient) : trait),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return { ...patch, ...parts.columns };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A row's tenant as its own entity stores it: the tenant column's value, when it has one. */
|
|
80
|
+
const tenantOf = (entity: EntityLike, row: Bag): unknown => {
|
|
81
|
+
const column = entity.$tenantColumn ?? null;
|
|
82
|
+
return column === null ? undefined : row[column];
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The association on the tenant column first: its parent fixes the tenant, and every other parent
|
|
87
|
+
* is then made IN that tenant — a comment's post and its org, never two orgs.
|
|
88
|
+
*/
|
|
89
|
+
const tenantFirst = (spec: FactorySpec): FactorySpec['belongsTo'] => {
|
|
90
|
+
const column = spec.entity.$tenantColumn ?? null;
|
|
91
|
+
return [...spec.belongsTo].sort(
|
|
92
|
+
([, a], [, b]) => Number(b.foreignKey === column) - Number(a.foreignKey === column),
|
|
93
|
+
);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
export function* rowSteps(
|
|
97
|
+
spec: FactorySpec,
|
|
98
|
+
applied: readonly string[],
|
|
99
|
+
over: object,
|
|
100
|
+
strategy: 'build' | 'create',
|
|
101
|
+
context: { readonly index: number; readonly ids: FactoryIds },
|
|
102
|
+
): Generator<Step, object, unknown> {
|
|
103
|
+
const parts = split(spec, over);
|
|
104
|
+
const { index, ids } = context;
|
|
105
|
+
const ctx: FactoryContext<Bag> = { index, ids, transient: parts.transient };
|
|
106
|
+
const patch = patchOf(spec, applied, parts, index, ids);
|
|
107
|
+
const row: Bag = { ...spec.defaults(index, ids, parts.transient), ...patch };
|
|
108
|
+
const tenantColumn = spec.entity.$tenantColumn ?? null;
|
|
109
|
+
let tenant =
|
|
110
|
+
tenantColumn !== null && Object.hasOwn(patch, tenantColumn) ? patch[tenantColumn] : undefined;
|
|
111
|
+
// A parent the CALLER handed over decides the tenant before anything is made: resolved first, the
|
|
112
|
+
// tenant column's own association made a new org and keyed the row to a post in another one.
|
|
113
|
+
for (const [name, link] of spec.belongsTo) {
|
|
114
|
+
const given = parts.parents.get(name);
|
|
115
|
+
if (tenant !== undefined || given === undefined || link.foreignKey === tenantColumn) continue;
|
|
116
|
+
tenant = tenantOf(link.parent.entity, given);
|
|
117
|
+
}
|
|
118
|
+
for (const [name, link] of tenantFirst(spec)) {
|
|
119
|
+
const key = link.foreignKey;
|
|
120
|
+
let parent = parts.parents.get(name);
|
|
121
|
+
if (parent === undefined) {
|
|
122
|
+
// A key the caller (or a trait) supplied makes no parent nobody asked for.
|
|
123
|
+
if (Object.hasOwn(patch, key)) continue;
|
|
124
|
+
// The tenant is already known — the tenant column takes it, and no second tenant is made.
|
|
125
|
+
if (key === tenantColumn && tenant !== undefined) {
|
|
126
|
+
row[key] = tenant;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const parentTenant = link.parent.entity.$tenantColumn ?? null;
|
|
130
|
+
const parentOver =
|
|
131
|
+
tenant !== undefined && parentTenant !== null ? { [parentTenant]: tenant } : {};
|
|
132
|
+
parent = (yield { kind: 'parent', factory: link.parent, over: parentOver }) as Bag;
|
|
133
|
+
}
|
|
134
|
+
row[key] = parent[referencedBy(spec.entity, key, link.references)];
|
|
135
|
+
if (key === tenantColumn) tenant = row[key];
|
|
136
|
+
else tenant ??= tenantOf(link.parent.entity, parent);
|
|
137
|
+
}
|
|
138
|
+
if (tenantColumn !== null && tenant !== undefined && !Object.hasOwn(patch, tenantColumn)) {
|
|
139
|
+
row[tenantColumn] = tenant;
|
|
140
|
+
}
|
|
141
|
+
for (const callback of spec.afterBuild) callback(row, ctx);
|
|
142
|
+
const stored = strategy === 'create' ? ((yield { kind: 'persist', row }) as Bag) : row;
|
|
143
|
+
const children: Record<string, readonly object[]> = {};
|
|
144
|
+
for (const [name, link] of spec.hasMany) {
|
|
145
|
+
const asked = parts.many.get(name) ?? link.count;
|
|
146
|
+
const list = typeof asked === 'number' ? Array.from({ length: asked }, () => ({})) : asked;
|
|
147
|
+
const value = stored[referencedBy(link.child.entity, link.foreignKey, link.references)];
|
|
148
|
+
const childTenant = link.child.entity.$tenantColumn ?? null;
|
|
149
|
+
const ownTenant = tenantOf(spec.entity, stored);
|
|
150
|
+
const follows =
|
|
151
|
+
childTenant !== null && childTenant !== link.foreignKey && ownTenant !== undefined
|
|
152
|
+
? { [childTenant]: ownTenant }
|
|
153
|
+
: {};
|
|
154
|
+
const made: object[] = [];
|
|
155
|
+
for (const one of list) {
|
|
156
|
+
const childOver = { [link.foreignKey]: value, ...follows, ...one };
|
|
157
|
+
made.push((yield { kind: 'child', factory: link.child, over: childOver }) as object);
|
|
158
|
+
}
|
|
159
|
+
children[name] = made;
|
|
160
|
+
}
|
|
161
|
+
// The children ride NON-enumerable: the answer is still the row as stored — `toEqual` against a
|
|
162
|
+
// read of the table holds, a spread or an insert of it carries no `comments` column — and
|
|
163
|
+
// `post.comments` is there for the test that asked for them.
|
|
164
|
+
const result: object = { ...stored };
|
|
165
|
+
for (const [name, made] of Object.entries(children)) {
|
|
166
|
+
Object.defineProperty(result, name, { value: made, enumerable: false });
|
|
167
|
+
}
|
|
168
|
+
if (strategy === 'create') {
|
|
169
|
+
for (const callback of spec.afterCreate) {
|
|
170
|
+
yield { kind: 'callback', run: () => callback(result, ctx) };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `attributesFor`: the input shape — no key of its own, no parent key, no transient. */
|
|
177
|
+
export function attributesOf(
|
|
178
|
+
spec: FactorySpec,
|
|
179
|
+
applied: readonly string[],
|
|
180
|
+
over: object,
|
|
181
|
+
context: { readonly index: number; readonly ids: FactoryIds },
|
|
182
|
+
): object {
|
|
183
|
+
const parts = split(spec, over);
|
|
184
|
+
const row: Bag = {
|
|
185
|
+
...spec.defaults(context.index, context.ids, parts.transient),
|
|
186
|
+
...patchOf(spec, applied, parts, context.index, context.ids),
|
|
187
|
+
};
|
|
188
|
+
for (const key of spec.entity.$primaryKey ?? ['id']) delete row[key];
|
|
189
|
+
for (const [, link] of spec.belongsTo) delete row[link.foreignKey];
|
|
190
|
+
return row;
|
|
191
|
+
}
|
package/src/factory-registry.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// nullability, enumerated values, money parts, default — through the seed graph's one value
|
|
3
3
|
// source. Enough for the rows a test does not care about; `defineFactory` is for the ones it does.
|
|
4
4
|
|
|
5
|
-
import type { EntityLike, Factory, FactoryIds } from './factories';
|
|
6
5
|
import { defineFactory } from './factories';
|
|
6
|
+
import type { Factory } from './factory-api';
|
|
7
|
+
import type { EntityLike, FactoryIds } from './factory-types';
|
|
7
8
|
import { seedGraphUnsatisfied } from './seed-graph-error';
|
|
8
9
|
import { declaredPatterns } from './seed-graph-patterns';
|
|
9
10
|
import { SEED_SOFT_DELETE_PROPERTY, type SeedEntity } from './seed-graph-shape';
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The factory vocabulary as types: what a factory is declared with, what each strategy hands back,
|
|
2
|
+
// and what an override may name. Kept apart from the runtime so `factories.ts` holds one job — the
|
|
3
|
+
// row pipeline — and a caller reading the contract reads it here.
|
|
4
|
+
|
|
5
|
+
import type { ColumnMap, Insertable } from '@ultimat3/entity';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The members of `entity()`'s value a factory reads, structurally: `@ultimat3/entity` is a
|
|
9
|
+
* dynamic-only dependency of this barrel. `$table` is the PHYSICAL table. The optional members are
|
|
10
|
+
* what a real entity adds — the default persister, tenancy and `references()` need them, a
|
|
11
|
+
* hand-built lookalike in a unit test may leave them out.
|
|
12
|
+
*/
|
|
13
|
+
export interface EntityLike {
|
|
14
|
+
readonly $table: string;
|
|
15
|
+
readonly $columns: Readonly<Record<string, unknown>>;
|
|
16
|
+
readonly $primaryKey?: readonly string[];
|
|
17
|
+
readonly $tenantColumn?: string | null;
|
|
18
|
+
$references?(): readonly { readonly property: string; readonly targetProperty: string }[];
|
|
19
|
+
$parse?(value: unknown): unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The seeded generators a `defaults` or trait body draws from. Never `Math.random` directly. */
|
|
23
|
+
export interface FactoryIds {
|
|
24
|
+
uuid(): string;
|
|
25
|
+
number(): number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** No members: the default for every optional map a factory declares. */
|
|
29
|
+
export type None = Record<never, never>;
|
|
30
|
+
|
|
31
|
+
/** What every body and callback of one row sees. `index` IS the sequence: 1, 2, 3 … per factory. */
|
|
32
|
+
export interface FactoryContext<TTransient extends object = None> {
|
|
33
|
+
readonly index: number;
|
|
34
|
+
readonly ids: FactoryIds;
|
|
35
|
+
/** The declared transient defaults, overridden by the call. Never written to the row. */
|
|
36
|
+
readonly transient: TTransient;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A named partial. A function form gets the row's index, the seeded generators and the transients. */
|
|
40
|
+
export type Trait<TRow, TTransient extends object = None> =
|
|
41
|
+
| Partial<TRow>
|
|
42
|
+
| ((index: number, ids: FactoryIds, transient: TTransient) => Partial<TRow>);
|
|
43
|
+
|
|
44
|
+
export type TraitMap<TRow, TTransient extends object = None> = Readonly<
|
|
45
|
+
Record<string, Trait<TRow, TTransient>>
|
|
46
|
+
>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The structural face of any factory, as an association holds it. Method syntax on purpose: a
|
|
50
|
+
* factory's `build(over?: Overrides<…>)` is assignable here only through method bivariance.
|
|
51
|
+
*/
|
|
52
|
+
export interface FactoryLike<TBuilt extends object = object, TRow extends object = object> {
|
|
53
|
+
readonly entity: EntityLike;
|
|
54
|
+
build(over?: object): TBuilt;
|
|
55
|
+
create(over?: object): Promise<TRow>;
|
|
56
|
+
reset(): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** `belongsTo(orgs, 'orgId')`: the parent built with the strategy the child is built with. */
|
|
60
|
+
export interface BelongsTo<TBuilt extends object, TRow extends object, TKey extends string> {
|
|
61
|
+
readonly kind: 'belongsTo';
|
|
62
|
+
readonly parent: FactoryLike<TBuilt, TRow>;
|
|
63
|
+
readonly foreignKey: TKey;
|
|
64
|
+
/** The parent's column the key holds. Unset: the child entity's `references()`, else `id`. */
|
|
65
|
+
readonly references: string | undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `hasMany(comments, 'postId')`: children written AFTER the parent, the key set from it. */
|
|
69
|
+
export interface HasMany<TBuilt extends object, TRow extends object, TKey extends string> {
|
|
70
|
+
readonly kind: 'hasMany';
|
|
71
|
+
readonly child: FactoryLike<TBuilt, TRow>;
|
|
72
|
+
readonly foreignKey: TKey;
|
|
73
|
+
readonly references: string | undefined;
|
|
74
|
+
/** Children made when the call names none. Default 0. */
|
|
75
|
+
readonly count: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// `object`, not `unknown`: a `FactoryLike<TBuilt>` is invariant in nothing that matters here, and
|
|
79
|
+
// the map's job is only to say "every value is an association"; each one's own type is kept.
|
|
80
|
+
export type BelongsToMap<TKey extends string = string> = Readonly<
|
|
81
|
+
Record<string, BelongsTo<object, object, TKey>>
|
|
82
|
+
>;
|
|
83
|
+
export type HasManyMap = Readonly<Record<string, HasMany<object, object, string>>>;
|
|
84
|
+
|
|
85
|
+
type ParentValue<B> = B extends BelongsTo<infer TBuilt, infer TRow, string> ? TBuilt | TRow : never;
|
|
86
|
+
type ManyValue<H> =
|
|
87
|
+
H extends HasMany<infer TBuilt, object, string> ? number | readonly Partial<TBuilt>[] : never;
|
|
88
|
+
type ManyBuilt<H> = H extends HasMany<infer TBuilt, object, string> ? TBuilt : never;
|
|
89
|
+
type ManyStored<H> = H extends HasMany<object, infer TRow, string> ? TRow : never;
|
|
90
|
+
export type ForeignKeysOf<TBelongs> = {
|
|
91
|
+
[K in keyof TBelongs]: TBelongs[K] extends BelongsTo<object, object, infer F> ? F : never;
|
|
92
|
+
}[keyof TBelongs];
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One call's overrides: columns, transients, a parent row per `belongsTo` name (`{ org: row }`,
|
|
96
|
+
* reused rather than made), and per `hasMany` name a count or one override per child.
|
|
97
|
+
*/
|
|
98
|
+
export type FactoryOverrides<TAttrs, TTransient, TBelongs, TMany> = Partial<TAttrs> &
|
|
99
|
+
Partial<TTransient> & { readonly [K in keyof TBelongs]?: ParentValue<TBelongs[K]> } & {
|
|
100
|
+
readonly [K in keyof TMany]?: ManyValue<TMany[K]>;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `build()`'s answer: the attributes, each `hasMany` name holding the children built with them —
|
|
105
|
+
* as a NON-enumerable property, so the row itself is only its columns.
|
|
106
|
+
*/
|
|
107
|
+
export type Built<TAttrs, TMany> = TAttrs & {
|
|
108
|
+
readonly [K in keyof TMany]: readonly ManyBuilt<TMany[K]>[];
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** `create()`'s answer: the row AS STORED, each `hasMany` name (non-enumerable) its stored children. */
|
|
112
|
+
export type Created<TRow, TMany> = TRow & {
|
|
113
|
+
readonly [K in keyof TMany]: readonly ManyStored<TMany[K]>[];
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* `attributesFor()`'s answer — an input, not a row: no parent key. The primary key is dropped at
|
|
118
|
+
* runtime (`$primaryKey`); the type omits `id`, the one key name `entity()` gives a type to see.
|
|
119
|
+
*/
|
|
120
|
+
export type AttributesFor<TAttrs, TBelongs> = Omit<TAttrs, ForeignKeysOf<TBelongs> | 'id'>;
|
|
121
|
+
|
|
122
|
+
/** The stored row of a real `entity()` (`$row`); a lookalike's is what its factory builds. */
|
|
123
|
+
export type StoredOf<E, TAttrs> = E extends { readonly $row: infer R extends object } ? R : TAttrs;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* What `defaults` may name for an `entity()`: its columns, each as its write shape. A column the
|
|
127
|
+
* entity does not declare, or a value of the wrong kind, is a compile error at the factory.
|
|
128
|
+
*/
|
|
129
|
+
export type WriteBound<E> = E extends { readonly $columns: infer C extends ColumnMap }
|
|
130
|
+
? Partial<Insertable<C>>
|
|
131
|
+
: object;
|