@classytic/supplier-performance 0.1.0 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,68 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ Stack upgrade + tenant-isolation fix + PACKAGE_RULES compliance + real test
6
+ coverage. No new features.
7
+
8
+ ### Fixed (security)
9
+
10
+ - **Cross-tenant leak — `multiTenantPlugin` was never wired.** Both
11
+ repositories were constructed with only `methodRegistryPlugin()`, so reads
12
+ and writes were NOT tenant-scoped despite the schema carrying an
13
+ `organizationId` field. The engine now derives one resolved tenant config
14
+ (via repo-core's `resolveTenantConfig`) and wires `multiTenantPlugin` on
15
+ every repo — scoping is enforced at POLICY priority and missing
16
+ `organizationId` throws (fail-closed). A `tenant-plugin-probe` integration
17
+ test plus an end-to-end isolation test guard this.
18
+
19
+ ### Changed (breaking)
20
+
21
+ - **Peers:** `@classytic/mongokit` `>=3.13.0` → `>=3.16.0`; **added**
22
+ `@classytic/repo-core >=0.6.0` (rule 11 — the code imports
23
+ `@classytic/repo-core/tenant` and `/errors`); **added** `zod >=4.0.0`
24
+ (event catalog). `@classytic/primitives` stays `>=0.5.0` (devDep bumped to
25
+ `^0.7.2`).
26
+ - **Tenant config clean break.** Dropped the legacy
27
+ `{ tenantFieldType, multiTenant }` shape and the `'string'` default. Tenant
28
+ config is now a repo-core `TenantConfig` (or boolean), defaulting to
29
+ repo-core's standard `fieldType: 'objectId'`, `required: true`. Hosts with
30
+ string/UUID org ids pass `{ fieldType: 'string' }`. Mongokit-runtime knobs
31
+ (`skipWhen`, `resolveContext`, `allowDataInjection`, `onMismatch`,
32
+ `skipOperations`) forward through the `tenant` object.
33
+ - **Errors.** Removed `RecordEventValidationError extends Error`. Validation now
34
+ throws `SupplierPerformanceValidationError implements HttpError` (status 400,
35
+ code `supplier_performance.validation.invalid_input`) so arc serializes it
36
+ correctly.
37
+
38
+ ### Added
39
+
40
+ - **Zod event catalog (rule 18):** `supplierPerformanceEventDefinitions`
41
+ exported from the package root AND the new `./events` subpath; per-event Zod
42
+ schemas (`z.iso.datetime()` timestamps), a no-drift invariant test, and
43
+ safeParse happy/rejection tests.
44
+ - **Cancellation / retry threading:** `SupplierPerformanceContext` now carries
45
+ `signal` / `retryPolicy`, forwarded to repo calls via `repoOptionsFromCtx`.
46
+ - **Test coverage** raised from one unit file to five files / 21 tests:
47
+ event-catalog no-drift, tenant probe + isolation, computeScore aggregation +
48
+ idempotency (re-run does not double-aggregate, exactly one snapshot row),
49
+ model-collision policy.
50
+
51
+ ### Build hygiene
52
+
53
+ - `tsconfig.json`: enabled `exactOptionalPropertyTypes`; disabled
54
+ `declarationMap` and `sourceMap` (no source leaks). `InProcessSupplierPerformanceBus`
55
+ gained `close()`. `CHANGELOG.md` added to published `files`.
56
+
57
+ ### Notes (verified, intentionally NOT changed)
58
+
59
+ - **No outbox / P8 dispatch machinery.** Durable delivery is host-composed
60
+ (§5.5 / §16); only a transport is wired, so publish failures are swallowed
61
+ (rule 14). Not a gap.
62
+ - **No capabilities boot gate.** The package uses no transactions — every verb
63
+ is a single-doc read/write/upsert — so the gate (transactions-only) does not
64
+ apply.
65
+ - **No rating-state CAS.** Scorecards are recomputable snapshots, not a state
66
+ machine; `computeScore` idempotency rests on the unique index + upsert.
67
+ - **`recordEvent` dedup stays host-owned** by design (hosts key differently:
68
+ PO-line vs PO+SKU). The kernel does not enforce a metric-dedup unique index.
package/README.md CHANGED
@@ -27,9 +27,11 @@ Peer deps:
27
27
 
28
28
  | | |
29
29
  |---|---|
30
- | `@classytic/mongokit` | `>=3.11.0` |
31
- | `@classytic/primitives` | `>=0.1.0` |
30
+ | `@classytic/mongokit` | `>=3.16.0` |
31
+ | `@classytic/repo-core` | `>=0.6.0` |
32
+ | `@classytic/primitives` | `>=0.5.0` |
32
33
  | `mongoose` | `>=9.4.1` |
34
+ | `zod` | `>=4.0.0` |
33
35
 
34
36
  ## Quick start
35
37
 
@@ -140,17 +142,43 @@ supplier_performance:score.computed
140
142
 
141
143
  Use any `EventTransport`-shaped bus (Arc's MemoryEventTransport, Redis, Kafka, …). The bundled `InProcessSupplierPerformanceBus` is a zero-dep default.
142
144
 
145
+ A Zod event catalog ships at the `@classytic/supplier-performance/events`
146
+ subpath (`supplierPerformanceEventDefinitions`) — hosts register it with arc's
147
+ `EventRegistry` for publish-time validation and OpenAPI introspection:
148
+
149
+ ```ts
150
+ import { supplierPerformanceEventDefinitions } from '@classytic/supplier-performance/events';
151
+ for (const def of supplierPerformanceEventDefinitions) registry.register(def);
152
+ ```
153
+
154
+ There is no package-owned outbox — durable delivery is host-composed
155
+ (`PACKAGE_RULES §5.5 / §16`). A transport publish failure is logged and
156
+ swallowed; hosts wanting at-least-once wire their own transport + relay.
157
+
143
158
  ### Multi-tenant
144
159
 
145
- Drives off `@classytic/primitives/tenant`. Default field type is `'string'` (matches the legacy convention shared by sibling packages):
160
+ Every repository is wired with `multiTenantPlugin` — reads and writes are
161
+ tenant-scoped at POLICY priority, so cross-tenant access is impossible (the
162
+ plugin throws when `organizationId` is missing from the call context).
163
+ Resolution drives off `@classytic/repo-core/tenant`; defaults follow repo-core:
164
+ `tenantField: 'organizationId'`, `fieldType: 'objectId'`, required.
146
165
 
147
166
  ```ts
167
+ // ObjectId org ids (Better Auth) — the default:
168
+ const engine = await createSupplierPerformance({ connection });
169
+
170
+ // String / UUID org ids:
148
171
  const engine = await createSupplierPerformance({
149
172
  connection,
150
- tenant: { fieldType: 'objectId' }, // when org IDs are stored as ObjectId
173
+ tenant: { fieldType: 'string' },
151
174
  });
152
175
  ```
153
176
 
177
+ Mongokit 3.16 plugin defaults are fail-closed (`onMismatch: 'throw'`,
178
+ `allowDataInjection: false`); a host can forward `skipWhen` / `resolveContext` /
179
+ `allowDataInjection` / `onMismatch` through the `tenant` object when its trust
180
+ model justifies it.
181
+
154
182
  ### Indexes
155
183
 
156
184
  | Collection | Index | Purpose |
@@ -164,7 +192,11 @@ The tenant field is prepended to compound indexes via `injectTenantField` when s
164
192
 
165
193
  ### Soft delete
166
194
 
167
- Every collection wires `softDeletePlugin` with a default 7-year retention. Hosts override via `retentionDays` on the engine config.
195
+ Not wired by default — soft delete is host policy, not package policy
196
+ (`PACKAGE_RULES §10`). The event log is append-only and scorecards are
197
+ recomputable, so neither collection needs reversible delete out of the box.
198
+ Hosts that want it pass a `softDeletePlugin()` instance through
199
+ `repositoryPlugins.performanceEvent` / `repositoryPlugins.supplierScore`.
168
200
 
169
201
  ## Why a service (and not just repos)?
170
202
 
@@ -0,0 +1,170 @@
1
+ import { createEvent, matchEventPattern } from "@classytic/primitives/events";
2
+ import { z } from "zod";
3
+ //#region src/domain/enums/event-type.enum.ts
4
+ /**
5
+ * Performance event types — what happened on a single supplier interaction.
6
+ *
7
+ * The catalog is intentionally small. Each type contributes to one or more
8
+ * scorecard metrics:
9
+ *
10
+ * - `delivery_received` → on-time rate, average delay
11
+ * - `delivery_late` → on-time rate, average delay
12
+ * - `defect_reported` → defect rate
13
+ * - `price_variance` → price variance %
14
+ *
15
+ * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
16
+ * extend by adding a constant + payload. Pure data; no FSM.
17
+ */
18
+ const PerformanceEventType = {
19
+ delivery_received: "delivery_received",
20
+ delivery_late: "delivery_late",
21
+ defect_reported: "defect_reported",
22
+ price_variance: "price_variance"
23
+ };
24
+ const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(PerformanceEventType);
25
+ //#endregion
26
+ //#region src/events/event-constants.ts
27
+ /**
28
+ * Canonical event names emitted by `@classytic/supplier-performance`.
29
+ *
30
+ * Prefix `supplier_performance:` matches the sibling-package convention
31
+ * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
32
+ * pattern-match on `supplier_performance:*`.
33
+ */
34
+ const SupplierPerformanceEvents = {
35
+ EVENT_RECORDED: "supplier_performance:event.recorded",
36
+ SCORE_COMPUTED: "supplier_performance:score.computed"
37
+ };
38
+ //#endregion
39
+ //#region src/events/helpers.ts
40
+ /**
41
+ * Thin typed wrapper around `@classytic/primitives/events.createEvent`
42
+ * (PACKAGE_RULES rule 14 shape: `createEvent(type, payload, ctx?, meta?)`).
43
+ *
44
+ * Value-add over primitives:
45
+ * - narrows `type` to `SupplierPerformanceEventName`
46
+ * - fills `meta.userId` / `meta.organizationId` / `meta.correlationId`
47
+ * from the supplier-performance context so every event stays scoped to
48
+ * the originating actor and tenant.
49
+ *
50
+ * Shape, id generation, timestamp — all owned by primitives / arc.
51
+ */
52
+ function createEvent$1(type, payload, ctx, meta) {
53
+ return createEvent(type, payload, {
54
+ ...ctx !== void 0 && ctx.actorKind === "user" ? { userId: String(ctx.actorRef) } : {},
55
+ ...ctx?.organizationId !== void 0 ? { organizationId: String(ctx.organizationId) } : {},
56
+ ...ctx?.correlationId !== void 0 ? { correlationId: ctx.correlationId } : {},
57
+ ...meta
58
+ });
59
+ }
60
+ //#endregion
61
+ //#region src/events/in-process-bus.ts
62
+ /**
63
+ * Zero-dep in-process event bus. Subscribers can use glob patterns
64
+ * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
65
+ * caught and logged — they never break the emitter or sibling
66
+ * subscribers.
67
+ *
68
+ * Drop-in compatible with any `EventTransport` — hosts replace it by
69
+ * passing their own at `createSupplierPerformance({ eventTransport })`.
70
+ */
71
+ var InProcessSupplierPerformanceBus = class {
72
+ name = "in-process-supplier-performance";
73
+ patterns = /* @__PURE__ */ new Map();
74
+ logger;
75
+ constructor(options = {}) {
76
+ this.logger = options.logger ?? console;
77
+ }
78
+ async publish(event) {
79
+ for (const [pattern, handlers] of this.patterns) {
80
+ if (!matchEventPattern(pattern, event.type)) continue;
81
+ for (const fn of handlers) try {
82
+ await fn(event);
83
+ } catch (err) {
84
+ this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
85
+ }
86
+ }
87
+ }
88
+ async subscribe(pattern, handler) {
89
+ let set = this.patterns.get(pattern);
90
+ if (!set) {
91
+ set = /* @__PURE__ */ new Set();
92
+ this.patterns.set(pattern, set);
93
+ }
94
+ set.add(handler);
95
+ return () => {
96
+ const s = this.patterns.get(pattern);
97
+ s?.delete(handler);
98
+ if (s && s.size === 0) this.patterns.delete(pattern);
99
+ };
100
+ }
101
+ async close() {
102
+ this.patterns.clear();
103
+ }
104
+ };
105
+ //#endregion
106
+ //#region src/events/event-catalog.ts
107
+ /**
108
+ * Zod-source event catalog (PACKAGE_RULES rule 18).
109
+ *
110
+ * One Zod schema per event is the source of truth — runtime validation,
111
+ * static types, and Arc introspection all derive from it. Hosts wire the
112
+ * definitions into arc's `EventRegistry`:
113
+ *
114
+ * ```ts
115
+ * for (const def of supplierPerformanceEventDefinitions) registry.register(def);
116
+ * ```
117
+ *
118
+ * which lights up publish-time validation (`eventPlugin({ registry,
119
+ * validateMode: 'reject' })`), OpenAPI event introspection, and
120
+ * `arc describe` output — with zero arc imports here (the definition shape
121
+ * is structurally identical to arc's `EventDefinitionOutput`).
122
+ *
123
+ * Timestamps are `z.iso.datetime()` (rule 25): `z.toJSONSchema()` throws on
124
+ * `z.coerce.date()`, and events serialize to JSON over the wire anyway.
125
+ */
126
+ function defineSupplierPerformanceEvent(input) {
127
+ const { name, description, version = 1, zodSchema } = input;
128
+ return {
129
+ name,
130
+ version,
131
+ description,
132
+ zodSchema,
133
+ schema: z.toJSONSchema(zodSchema),
134
+ create(payload, meta) {
135
+ return createEvent(name, payload, {
136
+ resource: "supplier-performance",
137
+ source: "supplier-performance",
138
+ ...meta
139
+ });
140
+ }
141
+ };
142
+ }
143
+ const eventRecordedSchema = z.object({
144
+ supplierId: z.string(),
145
+ type: z.enum(PERFORMANCE_EVENT_TYPE_VALUES),
146
+ occurredAt: z.iso.datetime(),
147
+ sourceRef: z.string().optional()
148
+ });
149
+ const EventRecorded = defineSupplierPerformanceEvent({
150
+ name: SupplierPerformanceEvents.EVENT_RECORDED,
151
+ description: "recordEvent() appended one supplier signal to the event log.",
152
+ zodSchema: eventRecordedSchema
153
+ });
154
+ const scoreComputedSchema = z.object({
155
+ supplierId: z.string(),
156
+ period: z.object({
157
+ start: z.iso.datetime(),
158
+ end: z.iso.datetime()
159
+ }),
160
+ compositeScore: z.number(),
161
+ eventCount: z.number().int().min(0)
162
+ });
163
+ const ScoreComputed = defineSupplierPerformanceEvent({
164
+ name: SupplierPerformanceEvents.SCORE_COMPUTED,
165
+ description: "computeScore() aggregated the window and upserted a scorecard snapshot.",
166
+ zodSchema: scoreComputedSchema
167
+ });
168
+ const supplierPerformanceEventDefinitions = [EventRecorded, ScoreComputed];
169
+ //#endregion
170
+ export { createEvent$1 as a, PerformanceEventType as c, InProcessSupplierPerformanceBus as i, ScoreComputed as n, SupplierPerformanceEvents as o, supplierPerformanceEventDefinitions as r, PERFORMANCE_EVENT_TYPE_VALUES as s, EventRecorded as t };
@@ -0,0 +1,2 @@
1
+ import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus } from "./in-process-bus.js";
2
+ export { EventRecorded, InProcessSupplierPerformanceBus, ScoreComputed, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, createEvent, supplierPerformanceEventDefinitions };
package/dist/events.js ADDED
@@ -0,0 +1,2 @@
1
+ import { a as createEvent, i as InProcessSupplierPerformanceBus, n as ScoreComputed, o as SupplierPerformanceEvents, r as supplierPerformanceEventDefinitions, t as EventRecorded } from "./event-catalog.js";
2
+ export { EventRecorded, InProcessSupplierPerformanceBus, ScoreComputed, SupplierPerformanceEvents, createEvent, supplierPerformanceEventDefinitions };
@@ -0,0 +1,163 @@
1
+ import { DomainEvent, EventHandler, EventMeta, EventTransport } from "@classytic/primitives/events";
2
+ import { z } from "zod";
3
+
4
+ //#region src/events/event-constants.d.ts
5
+
6
+ /**
7
+ * Canonical event names emitted by `@classytic/supplier-performance`.
8
+ *
9
+ * Prefix `supplier_performance:` matches the sibling-package convention
10
+ * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
11
+ * pattern-match on `supplier_performance:*`.
12
+ */
13
+ declare const SupplierPerformanceEvents: {
14
+ readonly EVENT_RECORDED: "supplier_performance:event.recorded";
15
+ readonly SCORE_COMPUTED: "supplier_performance:score.computed";
16
+ };
17
+ type SupplierPerformanceEventName = (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];
18
+ //#endregion
19
+ //#region src/domain/enums/event-type.enum.d.ts
20
+ /**
21
+ * Performance event types — what happened on a single supplier interaction.
22
+ *
23
+ * The catalog is intentionally small. Each type contributes to one or more
24
+ * scorecard metrics:
25
+ *
26
+ * - `delivery_received` → on-time rate, average delay
27
+ * - `delivery_late` → on-time rate, average delay
28
+ * - `defect_reported` → defect rate
29
+ * - `price_variance` → price variance %
30
+ *
31
+ * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
32
+ * extend by adding a constant + payload. Pure data; no FSM.
33
+ */
34
+ declare const PerformanceEventType: {
35
+ readonly delivery_received: "delivery_received";
36
+ readonly delivery_late: "delivery_late";
37
+ readonly defect_reported: "defect_reported";
38
+ readonly price_variance: "price_variance";
39
+ };
40
+ type PerformanceEventTypeValue = (typeof PerformanceEventType)[keyof typeof PerformanceEventType];
41
+ declare const PERFORMANCE_EVENT_TYPE_VALUES: readonly PerformanceEventTypeValue[];
42
+ //#endregion
43
+ //#region src/events/event-payloads.d.ts
44
+ /**
45
+ * Payload shapes for every `supplier_performance:*` event. Subscribers
46
+ * type-narrow on `eventType` and read `payload` as the matching entry.
47
+ *
48
+ * Timestamps are ISO-8601 strings on the wire (rule 25). Subscribers
49
+ * wanting a `Date` call `new Date(payload.occurredAt)`.
50
+ */
51
+ interface SupplierPerformanceEventPayloads {
52
+ 'supplier_performance:event.recorded': {
53
+ supplierId: string;
54
+ type: PerformanceEventTypeValue;
55
+ /** ISO-8601 — when the signal happened in the real world. */
56
+ occurredAt: string;
57
+ sourceRef?: string;
58
+ };
59
+ 'supplier_performance:score.computed': {
60
+ supplierId: string;
61
+ period: {
62
+ /** ISO-8601 inclusive start. */
63
+ start: string;
64
+ /** ISO-8601 exclusive end. */
65
+ end: string;
66
+ };
67
+ compositeScore: number;
68
+ eventCount: number;
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region src/events/event-catalog.d.ts
73
+ /** JSON-Schema object produced by `z.toJSONSchema` — what arc's registry consumes. */
74
+ type SupplierPerformanceEventSchema = Record<string, unknown>;
75
+ /** Structurally identical to arc's `EventDefinitionOutput` — do NOT import arc. */
76
+ interface SupplierPerformanceEventDefinition<TSchema extends z.ZodType = z.ZodType> {
77
+ name: SupplierPerformanceEventName;
78
+ version: number;
79
+ description: string;
80
+ zodSchema: TSchema;
81
+ schema: SupplierPerformanceEventSchema;
82
+ create(payload: z.infer<TSchema>, meta?: Partial<EventMeta>): DomainEvent<z.infer<TSchema>>;
83
+ }
84
+ declare const EventRecorded: SupplierPerformanceEventDefinition<z.ZodObject<{
85
+ supplierId: z.ZodString;
86
+ type: z.ZodEnum<{
87
+ [x: string]: string;
88
+ }>;
89
+ occurredAt: z.ZodISODateTime;
90
+ sourceRef: z.ZodOptional<z.ZodString>;
91
+ }, z.core.$strip>>;
92
+ declare const ScoreComputed: SupplierPerformanceEventDefinition<z.ZodObject<{
93
+ supplierId: z.ZodString;
94
+ period: z.ZodObject<{
95
+ start: z.ZodISODateTime;
96
+ end: z.ZodISODateTime;
97
+ }, z.core.$strip>;
98
+ compositeScore: z.ZodNumber;
99
+ eventCount: z.ZodNumber;
100
+ }, z.core.$strip>>;
101
+ declare const supplierPerformanceEventDefinitions: ReadonlyArray<SupplierPerformanceEventDefinition>;
102
+ //#endregion
103
+ //#region src/domain/ports/common.d.ts
104
+ /**
105
+ * Per-call context. Carries tenant, actor, and tracing signals. Opaque
106
+ * `session` slot avoids importing mongoose here so this port file stays
107
+ * framework-agnostic.
108
+ */
109
+ interface SupplierPerformanceContext {
110
+ /** Tenant scope. */
111
+ organizationId: string;
112
+ /** Actor reference (user id, system id, cron id). */
113
+ actorRef: string;
114
+ /** Actor kind. */
115
+ actorKind: 'user' | 'system' | 'integration';
116
+ /** Correlation id propagated through events. */
117
+ correlationId: string;
118
+ /** Optional mongoose ClientSession — narrowed at the repo boundary. */
119
+ session?: unknown;
120
+ /** Optional idempotency key for the operation. */
121
+ idempotencyKey?: string;
122
+ /**
123
+ * Optional cancellation signal. Threaded to repo calls via
124
+ * `repoOptionsFromCtx`; mongokit checks it at every op boundary and
125
+ * stops before the next round-trip.
126
+ */
127
+ signal?: AbortSignal;
128
+ /**
129
+ * Optional retry policy forwarded to repo calls. Mongokit wraps driver
130
+ * round-trips in `withRetry` when present.
131
+ */
132
+ retryPolicy?: unknown;
133
+ }
134
+ //#endregion
135
+ //#region src/events/helpers.d.ts
136
+ declare function createEvent$1<T>(type: SupplierPerformanceEventName, payload: T, ctx?: SupplierPerformanceContext, meta?: Partial<EventMeta>): DomainEvent<T>;
137
+ //#endregion
138
+ //#region src/events/in-process-bus.d.ts
139
+ interface InProcessBusOptions {
140
+ logger?: {
141
+ error(message: string, ...args: unknown[]): void;
142
+ };
143
+ }
144
+ /**
145
+ * Zero-dep in-process event bus. Subscribers can use glob patterns
146
+ * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
147
+ * caught and logged — they never break the emitter or sibling
148
+ * subscribers.
149
+ *
150
+ * Drop-in compatible with any `EventTransport` — hosts replace it by
151
+ * passing their own at `createSupplierPerformance({ eventTransport })`.
152
+ */
153
+ declare class InProcessSupplierPerformanceBus implements EventTransport {
154
+ readonly name = "in-process-supplier-performance";
155
+ private patterns;
156
+ private logger;
157
+ constructor(options?: InProcessBusOptions);
158
+ publish(event: DomainEvent): Promise<void>;
159
+ subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
160
+ close(): Promise<void>;
161
+ }
162
+ //#endregion
163
+ export { ScoreComputed as a, supplierPerformanceEventDefinitions as c, PerformanceEventType as d, PerformanceEventTypeValue as f, EventRecorded as i, SupplierPerformanceEventPayloads as l, SupplierPerformanceEvents as m, createEvent$1 as n, SupplierPerformanceEventDefinition as o, SupplierPerformanceEventName as p, SupplierPerformanceContext as r, SupplierPerformanceEventSchema as s, InProcessSupplierPerformanceBus as t, PERFORMANCE_EVENT_TYPE_VALUES as u };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
+ import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, d as PerformanceEventType, f as PerformanceEventTypeValue, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, r as SupplierPerformanceContext, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus, u as PERFORMANCE_EVENT_TYPE_VALUES } from "./in-process-bus.js";
2
+ import { PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
3
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
1
4
  import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
2
- import { ResolvedTenantConfig, TenantConfig } from "@classytic/primitives/tenant";
3
- import { PluginType, Repository } from "@classytic/mongokit";
4
- import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
5
+ import { EventTransport } from "@classytic/primitives/events";
6
+ import { HttpError } from "@classytic/repo-core/errors";
5
7
 
6
8
  //#region src/models/performance-event.model.d.ts
7
9
  interface PerformanceEventDocument extends Document {
@@ -49,51 +51,19 @@ declare class SupplierScoreModelCollisionError extends Error {
49
51
  }
50
52
  declare function createSupplierScoreModel(connection: Connection, tenant: ResolvedTenantConfig, config?: SupplierScoreModelConfig): Model<SupplierScoreDocument>;
51
53
  //#endregion
52
- //#region src/models/inject-tenant.d.ts
53
- type SupplierPerformanceTenantInput = TenantConfig | boolean | {
54
- tenantFieldType?: 'objectId' | 'string';
55
- multiTenant?: boolean;
56
- };
57
- declare function resolveSupplierPerformanceTenant(input?: SupplierPerformanceTenantInput): ResolvedTenantConfig;
58
- /**
59
- * Inject the tenant field into a Mongoose schema and prepend it to every
60
- * existing compound index (so queries are index-efficient under
61
- * multi-tenant scoping). Identical algorithm to commission's helper.
62
- */
63
- //#endregion
64
54
  //#region src/models/create-models.d.ts
65
55
  interface SupplierPerformanceModelBundle {
66
56
  PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;
67
57
  SupplierScore: ReturnType<typeof createSupplierScoreModel>;
68
58
  }
69
59
  interface CreateSupplierPerformanceModelsOptions {
70
- tenant?: ResolvedTenantConfig | TenantConfig | boolean | SupplierPerformanceTenantInput;
60
+ /** Resolved tenant config, or a `TenantConfig` / boolean to resolve. */
61
+ tenant?: ResolvedTenantConfig | TenantConfig | boolean;
71
62
  collectionPrefix?: string | undefined;
72
63
  forceRecreate?: boolean | undefined;
73
64
  }
74
65
  declare function createSupplierPerformanceModels(connection: Connection, options?: CreateSupplierPerformanceModelsOptions): SupplierPerformanceModelBundle;
75
66
  //#endregion
76
- //#region src/domain/ports/common.d.ts
77
- /**
78
- * Per-call context. Carries tenant, actor, and tracing signals. Opaque
79
- * `session` slot avoids importing mongoose here so this port file stays
80
- * framework-agnostic.
81
- */
82
- interface SupplierPerformanceContext {
83
- /** Tenant scope. */
84
- organizationId: string;
85
- /** Actor reference (user id, system id, cron id). */
86
- actorRef: string;
87
- /** Actor kind. */
88
- actorKind: 'user' | 'system' | 'integration';
89
- /** Correlation id propagated through events. */
90
- correlationId: string;
91
- /** Optional mongoose ClientSession — narrowed at the repo boundary. */
92
- session?: unknown;
93
- /** Optional idempotency key for the operation. */
94
- idempotencyKey?: string;
95
- }
96
- //#endregion
97
67
  //#region src/repositories/performance-event.repository.d.ts
98
68
  interface PerformanceEventRepositoryConfig {
99
69
  model: Model<PerformanceEventDocument>;
@@ -182,6 +152,11 @@ declare class SupplierScoreRepository extends Repository<SupplierScoreDocument>
182
152
  * snapshot in place — `computeScore` is idempotent. The unique index
183
153
  * on `(supplierId, period.start, period.end)` enforces that only one
184
154
  * row per (tenant, supplier, window) ever exists.
155
+ *
156
+ * INTENTIONAL BYPASS: This is an idempotent data-refresh upsert, not
157
+ * a state-machine transition. Per migration rules, upserts that refresh
158
+ * computed data (not CAS transitions) are excluded from claim() migration.
159
+ * Stays as `findOneAndUpdate` with explicit upsert: true.
185
160
  */
186
161
  upsertForPeriod(input: UpsertScoreInput, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument>;
187
162
  /**
@@ -192,30 +167,6 @@ declare class SupplierScoreRepository extends Repository<SupplierScoreDocument>
192
167
  findLatest(supplierId: string, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument | null>;
193
168
  }
194
169
  //#endregion
195
- //#region src/domain/enums/event-type.enum.d.ts
196
- /**
197
- * Performance event types — what happened on a single supplier interaction.
198
- *
199
- * The catalog is intentionally small. Each type contributes to one or more
200
- * scorecard metrics:
201
- *
202
- * - `delivery_received` → on-time rate, average delay
203
- * - `delivery_late` → on-time rate, average delay
204
- * - `defect_reported` → defect rate
205
- * - `price_variance` → price variance %
206
- *
207
- * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
208
- * extend by adding a constant + payload. Pure data; no FSM.
209
- */
210
- declare const PerformanceEventType: {
211
- readonly delivery_received: "delivery_received";
212
- readonly delivery_late: "delivery_late";
213
- readonly defect_reported: "defect_reported";
214
- readonly price_variance: "price_variance";
215
- };
216
- type PerformanceEventTypeValue = (typeof PerformanceEventType)[keyof typeof PerformanceEventType];
217
- declare const PERFORMANCE_EVENT_TYPE_VALUES: readonly PerformanceEventTypeValue[];
218
- //#endregion
219
170
  //#region src/domain/entities/performance-event.entity.d.ts
220
171
  interface PerformanceEvent {
221
172
  _id: Types.ObjectId;
@@ -292,12 +243,12 @@ interface ScoreServiceConfig {
292
243
  eventTransport?: EventTransport | undefined;
293
244
  logger?: {
294
245
  error(message: string, ...args: unknown[]): void;
295
- };
246
+ } | undefined;
296
247
  }
297
248
  declare class ScoreService {
298
249
  private events;
299
250
  private scores;
300
- private eventTransport?;
251
+ private eventTransport;
301
252
  private logger;
302
253
  constructor(config: ScoreServiceConfig);
303
254
  /**
@@ -321,18 +272,33 @@ declare class ScoreService {
321
272
  * implicitly (callers know when their data has changed).
322
273
  */
323
274
  getScorecard(supplierId: string, ctx: SupplierPerformanceContext, period?: ScorePeriod): Promise<SupplierScoreDocument | null>;
275
+ /**
276
+ * Publish a domain event via the injected transport (rule 14). There is
277
+ * no outbox in this package (host-composed per §5.5 / §16), so a publish
278
+ * failure is logged and swallowed — there is no durable row to roll back
279
+ * and no transaction in flight. Hosts wanting at-least-once delivery wire
280
+ * their own transport (Redis/Kafka) + relay.
281
+ */
324
282
  private publish;
325
283
  }
326
- declare class RecordEventValidationError extends Error {
327
- readonly name = "RecordEventValidationError";
328
- readonly code: "SUPPLIER_PERFORMANCE_VALIDATION";
329
- constructor(message: string);
330
- }
331
284
  //#endregion
332
285
  //#region src/engine/engine-types.d.ts
333
286
  interface SupplierPerformanceLogger {
334
287
  error(message: string, ...args: unknown[]): void;
335
288
  }
289
+ /**
290
+ * Tenant scoping config. Extends repo-core's `TenantConfig` with the
291
+ * mongokit-runtime knobs `multiTenantPlugin` accepts beyond the static
292
+ * vocabulary (forwarded only when the host sets them — the fail-closed
293
+ * 3.16 defaults stay in charge otherwise, rule 9.3 / 9.5).
294
+ */
295
+ interface SupplierPerformanceTenantOptions extends TenantConfig {
296
+ skipOperations?: string[] | undefined;
297
+ skipWhen?: ((context: RepositoryContext, operation: string) => boolean) | undefined;
298
+ resolveContext?: (() => string | undefined) | undefined;
299
+ allowDataInjection?: boolean | undefined;
300
+ onMismatch?: 'throw' | 'overwrite' | undefined;
301
+ }
336
302
  interface SupplierPerformanceConfig {
337
303
  /** Shared mongoose connection. */
338
304
  connection: Connection;
@@ -344,9 +310,15 @@ interface SupplierPerformanceConfig {
344
310
  */
345
311
  eventTransport?: EventTransport | undefined;
346
312
  /**
347
- * Tenant scoping config. Defaults to `{ fieldType: 'string' }`.
313
+ * Tenant scoping config — `TenantConfig` from `@classytic/repo-core/tenant`
314
+ * (plus mongokit-runtime knobs) or a boolean shorthand. One resolved value
315
+ * drives BOTH the model factory (schema field type + index prefixing) and
316
+ * `multiTenantPlugin` (query casting + fail-closed scoping), so they can't
317
+ * drift (rule 9.2). Defaults follow repo-core: `tenantField: 'organizationId'`,
318
+ * `fieldType: 'objectId'`, required. Hosts with string/UUID org ids pass
319
+ * `{ fieldType: 'string' }`.
348
320
  */
349
- tenant?: TenantConfig | boolean | undefined;
321
+ tenant?: SupplierPerformanceTenantOptions | boolean | undefined;
350
322
  /** Optional collection name prefix (PACKAGE_RULES §20.1). */
351
323
  collectionPrefix?: string | undefined;
352
324
  /** Hot-reload / test fixtures only. Default `false`. */
@@ -368,7 +340,7 @@ interface SupplierPerformanceEngine {
368
340
  services: {
369
341
  score: ScoreService;
370
342
  };
371
- events?: EventTransport;
343
+ events: EventTransport;
372
344
  syncIndexes(): Promise<void>;
373
345
  destroy(): Promise<void>;
374
346
  }
@@ -376,6 +348,17 @@ interface SupplierPerformanceEngine {
376
348
  //#region src/engine/create-supplier-performance.d.ts
377
349
  declare function createSupplierPerformance(config: SupplierPerformanceConfig): Promise<SupplierPerformanceEngine>;
378
350
  //#endregion
351
+ //#region src/domain/errors/supplier-performance.errors.d.ts
352
+ declare class SupplierPerformanceError extends Error implements HttpError {
353
+ readonly code: string;
354
+ readonly status: number;
355
+ constructor(message: string, code: string, status: number);
356
+ }
357
+ /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
358
+ declare class SupplierPerformanceValidationError extends SupplierPerformanceError {
359
+ constructor(message: string);
360
+ }
361
+ //#endregion
379
362
  //#region src/calc/score-calculator.d.ts
380
363
  /**
381
364
  * Aggregate raw performance events into a scorecard. Events outside the
@@ -384,6 +367,19 @@ declare function createSupplierPerformance(config: SupplierPerformanceConfig): P
384
367
  */
385
368
  declare function scoreFromEvents(events: ReadonlyArray<PerformanceEvent>, period: ScorePeriod): ScoreMetrics;
386
369
  //#endregion
370
+ //#region src/models/inject-tenant.d.ts
371
+ /**
372
+ * Resolve the package's tenant config. Accepts a repo-core `TenantConfig`
373
+ * or boolean shorthand — no package-local shapes. Pure passthrough to
374
+ * `resolveTenantConfig` so defaults can't drift from the org standard.
375
+ */
376
+ declare function resolveSupplierPerformanceTenant(input?: TenantConfig | boolean): ResolvedTenantConfig;
377
+ /**
378
+ * Inject the tenant field into a Mongoose schema and prepend it to every
379
+ * existing compound index (so queries are index-efficient under
380
+ * multi-tenant scoping, rule 36).
381
+ */
382
+ //#endregion
387
383
  //#region src/repositories/repo-options.d.ts
388
384
  interface RepoOptions {
389
385
  organizationId: string;
@@ -392,47 +388,10 @@ interface RepoOptions {
392
388
  correlationId: string;
393
389
  session?: ClientSession;
394
390
  idempotencyKey?: string;
391
+ signal?: AbortSignal;
392
+ retryPolicy?: unknown;
395
393
  [key: string]: unknown;
396
394
  }
397
395
  declare function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions;
398
396
  //#endregion
399
- //#region src/events/event-constants.d.ts
400
- /**
401
- * Canonical event names emitted by `@classytic/supplier-performance`.
402
- *
403
- * Prefix `supplier_performance:` matches the sibling-package convention
404
- * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
405
- * pattern-match on `supplier_performance:*`.
406
- */
407
- declare const SupplierPerformanceEvents: {
408
- readonly EVENT_RECORDED: "supplier_performance:event.recorded";
409
- readonly SCORE_COMPUTED: "supplier_performance:score.computed";
410
- };
411
- type SupplierPerformanceEventName = (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];
412
- //#endregion
413
- //#region src/events/in-process-bus.d.ts
414
- interface InProcessBusOptions {
415
- logger?: {
416
- error(message: string, ...args: unknown[]): void;
417
- };
418
- }
419
- /**
420
- * Zero-dep in-process event bus. Subscribers can use glob patterns
421
- * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
422
- * caught and logged — they never break the emitter or sibling
423
- * subscribers.
424
- *
425
- * Drop-in compatible with any `EventTransport` — hosts replace it by
426
- * passing their own at `createSupplierPerformance({ eventTransport })`.
427
- */
428
- declare class InProcessSupplierPerformanceBus implements EventTransport {
429
- readonly name = "in-process-supplier-performance";
430
- private patterns;
431
- private logger;
432
- constructor(options?: InProcessBusOptions);
433
- publish(event: DomainEvent): Promise<void>;
434
- subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
435
- }
436
- //#endregion
437
- export { type ComputeScoreInput, type CreateSupplierPerformanceModelsOptions, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventModelCollisionError, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, RecordEventValidationError, type RepoOptions, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceConfig, type SupplierPerformanceContext, type SupplierPerformanceEngine, type SupplierPerformanceEventName, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModelBundle, type SupplierPerformanceRepositories, type SupplierPerformanceTenantInput, type SupplierScore, type SupplierScoreDocument, SupplierScoreModelCollisionError, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents };
438
- //# sourceMappingURL=index.d.ts.map
397
+ export { type ComputeScoreInput, type CreateSupplierPerformanceModelsOptions, EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventModelCollisionError, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, type RepoOptions, ScoreComputed, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceConfig, type SupplierPerformanceContext, type SupplierPerformanceEngine, SupplierPerformanceError, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModelBundle, type SupplierPerformanceRepositories, type SupplierPerformanceTenantOptions, SupplierPerformanceValidationError, type SupplierScore, type SupplierScoreDocument, SupplierScoreModelCollisionError, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
package/dist/index.js CHANGED
@@ -1,65 +1,30 @@
1
+ import { a as createEvent, c as PerformanceEventType, i as InProcessSupplierPerformanceBus, n as ScoreComputed, o as SupplierPerformanceEvents, r as supplierPerformanceEventDefinitions, s as PERFORMANCE_EVENT_TYPE_VALUES, t as EventRecorded } from "./event-catalog.js";
2
+ import { Repository, createOptionsExtractor, methodRegistryPlugin, multiTenantPlugin } from "@classytic/mongokit";
3
+ import { resolveTenantConfig } from "@classytic/repo-core/tenant";
1
4
  import mongoose, { Schema } from "mongoose";
2
- import { resolveTenantConfig } from "@classytic/primitives/tenant";
3
- import { Repository, methodRegistryPlugin } from "@classytic/mongokit";
4
- import { createEvent, matchEventPattern } from "@classytic/primitives/events";
5
- //#region src/domain/enums/event-type.enum.ts
5
+ //#region src/models/inject-tenant.ts
6
6
  /**
7
- * Performance event types — what happened on a single supplier interaction.
8
- *
9
- * The catalog is intentionally small. Each type contributes to one or more
10
- * scorecard metrics:
11
- *
12
- * - `delivery_received` → on-time rate, average delay
13
- * - `delivery_late` → on-time rate, average delay
14
- * - `defect_reported` → defect rate
15
- * - `price_variance` → price variance %
7
+ * Mongoose-specific tenant adapter — thin layer over repo-core's
8
+ * `resolveTenantConfig()` (P11). All tenant-config defaulting and
9
+ * validation belongs to repo-core; only the Mongoose schema mutation
10
+ * (field add + compound-index prefix) lives here.
16
11
  *
17
- * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
18
- * extend by adding a constant + payload. Pure data; no FSM.
12
+ * Defaults follow repo-core: `tenantField: 'organizationId'`,
13
+ * `fieldType: 'objectId'`, `required: true`, `enabled: true`. Hosts whose
14
+ * org ids are strings/UUIDs pass `tenant: { fieldType: 'string' }`.
19
15
  */
20
- const PerformanceEventType = {
21
- delivery_received: "delivery_received",
22
- delivery_late: "delivery_late",
23
- defect_reported: "defect_reported",
24
- price_variance: "price_variance"
25
- };
26
- const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(PerformanceEventType);
27
- //#endregion
28
- //#region src/models/inject-tenant.ts
29
16
  /**
30
- * Mongoose-specific tenant adapter — mirrors the commission package's
31
- * pattern so hosts that already configured commission can reuse the same
32
- * config shape here.
33
- *
34
- * Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass
35
- * `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.
17
+ * Resolve the package's tenant config. Accepts a repo-core `TenantConfig`
18
+ * or boolean shorthand — no package-local shapes. Pure passthrough to
19
+ * `resolveTenantConfig` so defaults can't drift from the org standard.
36
20
  */
37
- function resolveSupplierPerformanceTenant(input = {}) {
38
- if (typeof input === "boolean") return applyDefaultFieldType(resolveTenantConfig(input));
39
- if ("tenantFieldType" in input || "multiTenant" in input) {
40
- const legacy = input;
41
- return resolveTenantConfig({
42
- enabled: legacy.multiTenant !== false,
43
- fieldType: legacy.tenantFieldType ?? "string"
44
- });
45
- }
46
- const cfg = input;
47
- if (cfg.fieldType === void 0) return resolveTenantConfig({
48
- ...cfg,
49
- fieldType: "string"
50
- });
51
- return resolveTenantConfig(cfg);
52
- }
53
- function applyDefaultFieldType(resolved) {
54
- return {
55
- ...resolved,
56
- fieldType: "string"
57
- };
21
+ function resolveSupplierPerformanceTenant(input) {
22
+ return resolveTenantConfig(input);
58
23
  }
59
24
  /**
60
25
  * Inject the tenant field into a Mongoose schema and prepend it to every
61
26
  * existing compound index (so queries are index-efficient under
62
- * multi-tenant scoping). Identical algorithm to commission's helper.
27
+ * multi-tenant scoping, rule 36).
63
28
  */
64
29
  function injectTenantField(schema, tenant) {
65
30
  const isFieldStrategy = tenant.strategy === "field";
@@ -274,12 +239,13 @@ function createSupplierScoreModel(connection, tenant, config = {}) {
274
239
  }
275
240
  //#endregion
276
241
  //#region src/models/create-models.ts
242
+ function toResolved(tenant) {
243
+ if (typeof tenant === "object" && tenant !== null && "strategy" in tenant && "enabled" in tenant && "tenantField" in tenant) return tenant;
244
+ if (tenant !== void 0) return resolveSupplierPerformanceTenant(tenant);
245
+ return resolveSupplierPerformanceTenant();
246
+ }
277
247
  function createSupplierPerformanceModels(connection, options = {}) {
278
- const tenant = (() => {
279
- if (typeof options.tenant === "object" && options.tenant !== null && "strategy" in options.tenant && "tenantField" in options.tenant) return options.tenant;
280
- if (options.tenant !== void 0) return resolveSupplierPerformanceTenant(options.tenant);
281
- return resolveSupplierPerformanceTenant();
282
- })();
248
+ const tenant = toResolved(options.tenant);
283
249
  const modelConfig = {
284
250
  ...options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {},
285
251
  ...options.forceRecreate !== void 0 ? { forceRecreate: options.forceRecreate } : {}
@@ -291,16 +257,18 @@ function createSupplierPerformanceModels(connection, options = {}) {
291
257
  }
292
258
  //#endregion
293
259
  //#region src/repositories/repo-options.ts
260
+ const extract = createOptionsExtractor([
261
+ "organizationId",
262
+ "actorRef",
263
+ "actorKind",
264
+ "correlationId",
265
+ "session",
266
+ "idempotencyKey",
267
+ "signal",
268
+ "retryPolicy"
269
+ ]);
294
270
  function repoOptionsFromCtx(ctx) {
295
- const opts = {
296
- organizationId: ctx.organizationId,
297
- actorRef: ctx.actorRef,
298
- actorKind: ctx.actorKind,
299
- correlationId: ctx.correlationId
300
- };
301
- if (ctx.session !== void 0) opts.session = ctx.session;
302
- if (ctx.idempotencyKey !== void 0) opts.idempotencyKey = ctx.idempotencyKey;
303
- return opts;
271
+ return extract(ctx);
304
272
  }
305
273
  //#endregion
306
274
  //#region src/repositories/performance-event.repository.ts
@@ -351,6 +319,11 @@ var SupplierScoreRepository = class extends Repository {
351
319
  * snapshot in place — `computeScore` is idempotent. The unique index
352
320
  * on `(supplierId, period.start, period.end)` enforces that only one
353
321
  * row per (tenant, supplier, window) ever exists.
322
+ *
323
+ * INTENTIONAL BYPASS: This is an idempotent data-refresh upsert, not
324
+ * a state-machine transition. Per migration rules, upserts that refresh
325
+ * computed data (not CAS transitions) are excluded from claim() migration.
326
+ * Stays as `findOneAndUpdate` with explicit upsert: true.
354
327
  */
355
328
  async upsertForPeriod(input, ctx) {
356
329
  const computedAt = input.computedAt ?? /* @__PURE__ */ new Date();
@@ -457,17 +430,22 @@ function round(value, digits) {
457
430
  return Math.round(value * factor) / factor;
458
431
  }
459
432
  //#endregion
460
- //#region src/events/event-constants.ts
461
- /**
462
- * Canonical event names emitted by `@classytic/supplier-performance`.
463
- *
464
- * Prefix `supplier_performance:` matches the sibling-package convention
465
- * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
466
- * pattern-match on `supplier_performance:*`.
467
- */
468
- const SupplierPerformanceEvents = {
469
- EVENT_RECORDED: "supplier_performance:event.recorded",
470
- SCORE_COMPUTED: "supplier_performance:score.computed"
433
+ //#region src/domain/errors/supplier-performance.errors.ts
434
+ var SupplierPerformanceError = class extends Error {
435
+ code;
436
+ status;
437
+ constructor(message, code, status) {
438
+ super(message);
439
+ this.code = code;
440
+ this.status = status;
441
+ this.name = this.constructor.name;
442
+ }
443
+ };
444
+ /** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
445
+ var SupplierPerformanceValidationError = class extends SupplierPerformanceError {
446
+ constructor(message) {
447
+ super(message, "supplier_performance.validation.invalid_input", 400);
448
+ }
471
449
  };
472
450
  //#endregion
473
451
  //#region src/services/score.service.ts
@@ -489,7 +467,7 @@ var ScoreService = class {
489
467
  * different keying preferences: PO-line, PO+SKU, etc.).
490
468
  */
491
469
  async recordEvent(input, ctx) {
492
- if (!input.supplierId) throw new RecordEventValidationError("supplierId is required");
470
+ if (!input.supplierId) throw new SupplierPerformanceValidationError("supplierId is required");
493
471
  const occurredAt = input.occurredAt ?? /* @__PURE__ */ new Date();
494
472
  const doc = await this.events.create({
495
473
  organizationId: ctx.organizationId,
@@ -549,13 +527,16 @@ var ScoreService = class {
549
527
  }, ctx);
550
528
  return this.scores.findLatest(supplierId, ctx);
551
529
  }
530
+ /**
531
+ * Publish a domain event via the injected transport (rule 14). There is
532
+ * no outbox in this package (host-composed per §5.5 / §16), so a publish
533
+ * failure is logged and swallowed — there is no durable row to roll back
534
+ * and no transaction in flight. Hosts wanting at-least-once delivery wire
535
+ * their own transport (Redis/Kafka) + relay.
536
+ */
552
537
  publish(type, ctx, data) {
553
538
  if (!this.eventTransport) return;
554
- const event = createEvent(type, data, {
555
- organizationId: ctx.organizationId,
556
- userId: ctx.actorRef,
557
- correlationId: ctx.correlationId
558
- });
539
+ const event = createEvent(type, data, ctx);
559
540
  this.eventTransport.publish(event).catch((err) => {
560
541
  this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);
561
542
  });
@@ -577,77 +558,44 @@ function toCalcEvent(doc) {
577
558
  };
578
559
  }
579
560
  function normalizePeriod(period) {
580
- if (period.end.getTime() <= period.start.getTime()) throw new RecordEventValidationError(`period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`);
561
+ if (period.end.getTime() <= period.start.getTime()) throw new SupplierPerformanceValidationError(`period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`);
581
562
  return period;
582
563
  }
583
- var RecordEventValidationError = class extends Error {
584
- name = "RecordEventValidationError";
585
- code = "SUPPLIER_PERFORMANCE_VALIDATION";
586
- constructor(message) {
587
- super(message);
588
- }
589
- };
590
- //#endregion
591
- //#region src/events/in-process-bus.ts
592
- /**
593
- * Zero-dep in-process event bus. Subscribers can use glob patterns
594
- * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
595
- * caught and logged — they never break the emitter or sibling
596
- * subscribers.
597
- *
598
- * Drop-in compatible with any `EventTransport` — hosts replace it by
599
- * passing their own at `createSupplierPerformance({ eventTransport })`.
600
- */
601
- var InProcessSupplierPerformanceBus = class {
602
- name = "in-process-supplier-performance";
603
- patterns = /* @__PURE__ */ new Map();
604
- logger;
605
- constructor(options = {}) {
606
- this.logger = options.logger ?? console;
607
- }
608
- async publish(event) {
609
- for (const [pattern, handlers] of this.patterns) {
610
- if (!matchEventPattern(pattern, event.type)) continue;
611
- for (const fn of handlers) try {
612
- await fn(event);
613
- } catch (err) {
614
- this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
615
- }
616
- }
617
- }
618
- async subscribe(pattern, handler) {
619
- let set = this.patterns.get(pattern);
620
- if (!set) {
621
- set = /* @__PURE__ */ new Set();
622
- this.patterns.set(pattern, set);
623
- }
624
- set.add(handler);
625
- return () => {
626
- const s = this.patterns.get(pattern);
627
- s?.delete(handler);
628
- if (s && s.size === 0) this.patterns.delete(pattern);
629
- };
630
- }
631
- };
632
564
  //#endregion
633
565
  //#region src/engine/create-supplier-performance.ts
634
566
  async function createSupplierPerformance(config) {
635
567
  if (!config.connection) throw new Error("createSupplierPerformance: config.connection is required");
636
568
  const logger = config.logger ?? console;
637
569
  const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
638
- const tenant = resolveSupplierPerformanceTenant(config.tenant);
570
+ const tenant = resolveTenantConfig(config.tenant);
639
571
  const models = createSupplierPerformanceModels(config.connection, {
640
572
  tenant,
641
573
  ...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
642
574
  ...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
643
575
  });
576
+ const tenantPlugins = (() => {
577
+ if (!tenant.enabled || tenant.strategy !== "field") return [];
578
+ const extras = typeof config.tenant === "object" ? config.tenant : void 0;
579
+ return [multiTenantPlugin({
580
+ tenantField: tenant.tenantField,
581
+ fieldType: tenant.fieldType,
582
+ contextKey: tenant.contextKey,
583
+ required: tenant.required,
584
+ ...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
585
+ ...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
586
+ ...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
587
+ ...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
588
+ ...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
589
+ })];
590
+ })();
591
+ const repoPlugins = config.repositoryPlugins ?? {};
644
592
  const performanceEvent = new PerformanceEventRepository({
645
593
  model: models.PerformanceEvent,
646
- ...config.repositoryPlugins?.performanceEvent !== void 0 ? { plugins: config.repositoryPlugins.performanceEvent } : {}
594
+ plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
647
595
  });
648
596
  const supplierScore = new SupplierScoreRepository({
649
597
  model: models.SupplierScore,
650
- ...config.repositoryPlugins?.supplierScore !== void 0 ? { plugins: config.repositoryPlugins.supplierScore } : {}
598
+ plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
651
599
  });
652
600
  const score = new ScoreService({
653
601
  events: performanceEvent,
@@ -666,10 +614,10 @@ async function createSupplierPerformance(config) {
666
614
  async syncIndexes() {
667
615
  await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
668
616
  },
669
- async destroy() {}
617
+ async destroy() {
618
+ await events.close?.();
619
+ }
670
620
  };
671
621
  }
672
622
  //#endregion
673
- export { InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType, RecordEventValidationError, ScoreService, SupplierPerformanceEvents, SupplierScoreModelCollisionError, SupplierScoreRepository, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents };
674
-
675
- //# sourceMappingURL=index.js.map
623
+ export { EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType, ScoreComputed, ScoreService, SupplierPerformanceError, SupplierPerformanceEvents, SupplierPerformanceValidationError, SupplierScoreModelCollisionError, SupplierScoreRepository, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/supplier-performance",
3
- "version": "0.1.0",
4
- "description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
3
+ "version": "0.2.0",
4
+ "description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
6
  "license": "MIT",
7
7
  "homepage": "https://www.npmjs.com/package/@classytic/supplier-performance",
@@ -36,6 +36,10 @@
36
36
  ".": {
37
37
  "types": "./dist/index.d.ts",
38
38
  "default": "./dist/index.js"
39
+ },
40
+ "./events": {
41
+ "types": "./dist/events.d.ts",
42
+ "default": "./dist/events.js"
39
43
  }
40
44
  },
41
45
  "main": "./dist/index.js",
@@ -43,6 +47,7 @@
43
47
  "files": [
44
48
  "dist",
45
49
  "README.md",
50
+ "CHANGELOG.md",
46
51
  "LICENSE"
47
52
  ],
48
53
  "scripts": {
@@ -55,19 +60,23 @@
55
60
  "release": "npm run push -- main && npm run release:tag && npm publish"
56
61
  },
57
62
  "peerDependencies": {
58
- "@classytic/mongokit": ">=3.11.0",
59
- "@classytic/primitives": ">=0.1.0",
60
- "mongoose": ">=9.4.1"
63
+ "@classytic/mongokit": ">=3.16.0",
64
+ "@classytic/repo-core": ">=0.6.0",
65
+ "@classytic/primitives": ">=0.5.0",
66
+ "mongoose": ">=9.4.1",
67
+ "zod": ">=4.0.0"
61
68
  },
62
69
  "devDependencies": {
63
70
  "@classytic/dev-tools": "^0.2.0",
64
- "@classytic/mongokit": "^3.11.0",
65
- "@classytic/primitives": "^0.1.1",
71
+ "@classytic/mongokit": ">=3.16.0",
72
+ "@classytic/repo-core": ">=0.6.0",
73
+ "@classytic/primitives": "^0.7.2",
66
74
  "@types/node": "^25.5.0",
67
75
  "mongodb-memory-server": "^10.2.3",
68
76
  "mongoose": "^9.4.1",
69
77
  "tsdown": "^0.14.2",
70
78
  "typescript": "^5.8.2",
71
- "vitest": "^3.2.4"
79
+ "vitest": "^3.2.4",
80
+ "zod": "^4.0.0"
72
81
  }
73
82
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/models/performance-event.model.ts","../src/models/supplier-score.model.ts","../src/models/inject-tenant.ts","../src/models/create-models.ts","../src/domain/ports/common.ts","../src/repositories/performance-event.repository.ts","../src/domain/entities/supplier-score.entity.ts","../src/repositories/supplier-score.repository.ts","../src/domain/enums/event-type.enum.ts","../src/domain/entities/performance-event.entity.ts","../src/services/score.service.ts","../src/engine/engine-types.ts","../src/engine/create-supplier-performance.ts","../src/calc/score-calculator.ts","../src/repositories/repo-options.ts","../src/events/event-constants.ts","../src/events/in-process-bus.ts"],"mappings":";;;;;;UAKiB,wBAAA,SAAiC;;;;EAAjC,UAAA,EAIH,IAJG;EAAyB,OAAA,EAK/B,MAL+B,CAAA,MAAA,EAAA,OAAA,CAAA;WAI5B,CAAA,EAAA,MAAA;YACH,CAAA,EAAA,MAAA;UAGE,CAAA,EAAA,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,EU5BE,+BV4BF;UACJ,EAAA;IACA,KAAA,EU7BW,YV6BX;;QACP,CAAA,EU7BQ,cV6BR;EAAK,WAAA,EAAA,EU5BS,OV4BT,CAAA,IAAA,CAAA;aU3BK;;;;iBC7CS,yBAAA,SACZ,4BACP,QAAQ;;;;;;;;AZR+C,iBasB1C,eAAA,CbtB0C,MAAA,EauBhD,abvBgD,CauBlC,gBbvBkC,CAAA,EAAA,MAAA,EawBhD,WbxBgD,CAAA,EayBvD,YbzBuD;;;UcFzC,WAAA;;;aAGJ;EdDI,aAAA,EAAA,MAAA;EAAyB,OAAA,CAAA,EcG9B,adH8B;gBAI5B,CAAA,EAAA,MAAA;MACH,EAAA,MAAA,CAAA,EAAA,OAAA;;AAIE,iBcDG,kBAAA,CdCH,GAAA,EcD2B,0BdC3B,CAAA,EcDwD,WdCxD;;;;;;;;;AATb;AAA0C,ceE7B,yBfF6B,EAAA;WAI5B,cAAA,EAAA,qCAAA;WACH,cAAA,EAAA,qCAAA;;AAIE,KeFD,4BAAA,GfEC,CAAA,OeDH,yBfCG,CAAA,CAAA,MAAA,OeDqC,yBfCrC,CAAA;;;UgBPI,mBAAA;;;;;AhBFjB;;;;;;;;;AA0BiB,cgBXJ,+BAAA,YAA2C,chBWZ,CAAA;EAiC/B,SAAA,IAAA,GAAA,iCAA4C;EAUzC,QAAA,QAAA;EAA2B,QAAA,MAAA;aAC7B,CAAA,OAAA,CAAA,EgBlDS,mBhBkDT;SACJ,CAAA,KAAA,EgB/Ca,WhB+Cb,CAAA,EgB/C2B,OhB+C3B,CAAA,IAAA,CAAA;WACA,CAAA,OAAA,EAAA,MAAA,EAAA,OAAA,EgBhCkC,YhBgClC,CAAA,EgBhCiD,OhBgCjD,CAAA,GAAA,GAAA,IAAA,CAAA"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["metricsSchema"],"sources":["../src/domain/enums/event-type.enum.ts","../src/models/inject-tenant.ts","../src/models/performance-event.model.ts","../src/models/supplier-score.model.ts","../src/models/create-models.ts","../src/repositories/repo-options.ts","../src/repositories/performance-event.repository.ts","../src/repositories/supplier-score.repository.ts","../src/calc/score-calculator.ts","../src/events/event-constants.ts","../src/services/score.service.ts","../src/events/in-process-bus.ts","../src/engine/create-supplier-performance.ts"],"sourcesContent":["/**\n * Performance event types — what happened on a single supplier interaction.\n *\n * The catalog is intentionally small. Each type contributes to one or more\n * scorecard metrics:\n *\n * - `delivery_received` → on-time rate, average delay\n * - `delivery_late` → on-time rate, average delay\n * - `defect_reported` → defect rate\n * - `price_variance` → price variance %\n *\n * Hosts that need a domain-specific signal (e.g. `quality_audit`) can\n * extend by adding a constant + payload. Pure data; no FSM.\n */\nexport const PerformanceEventType = {\n delivery_received: 'delivery_received',\n delivery_late: 'delivery_late',\n defect_reported: 'defect_reported',\n price_variance: 'price_variance',\n} as const;\n\nexport type PerformanceEventTypeValue =\n (typeof PerformanceEventType)[keyof typeof PerformanceEventType];\n\nexport const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(\n PerformanceEventType,\n) as readonly PerformanceEventTypeValue[];\n","/**\n * Mongoose-specific tenant adapter — mirrors the commission package's\n * pattern so hosts that already configured commission can reuse the same\n * config shape here.\n *\n * Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass\n * `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.\n */\nimport mongoose, { type Schema } from 'mongoose';\nimport {\n resolveTenantConfig,\n type ResolvedTenantConfig,\n type TenantConfig,\n} from '@classytic/primitives/tenant';\n\nexport type SupplierPerformanceTenantInput =\n | TenantConfig\n | boolean\n | {\n tenantFieldType?: 'objectId' | 'string';\n multiTenant?: boolean;\n };\n\nexport function resolveSupplierPerformanceTenant(\n input: SupplierPerformanceTenantInput = {},\n): ResolvedTenantConfig {\n if (typeof input === 'boolean') {\n return applyDefaultFieldType(resolveTenantConfig(input));\n }\n if ('tenantFieldType' in input || 'multiTenant' in input) {\n const legacy = input as { tenantFieldType?: 'objectId' | 'string'; multiTenant?: boolean };\n return resolveTenantConfig({\n enabled: legacy.multiTenant !== false,\n fieldType: legacy.tenantFieldType ?? 'string',\n });\n }\n const cfg = input as TenantConfig;\n if (cfg.fieldType === undefined) {\n return resolveTenantConfig({ ...cfg, fieldType: 'string' });\n }\n return resolveTenantConfig(cfg);\n}\n\nfunction applyDefaultFieldType(resolved: ResolvedTenantConfig): ResolvedTenantConfig {\n return { ...resolved, fieldType: 'string' };\n}\n\n/**\n * Inject the tenant field into a Mongoose schema and prepend it to every\n * existing compound index (so queries are index-efficient under\n * multi-tenant scoping). Identical algorithm to commission's helper.\n */\nexport function injectTenantField(schema: Schema, tenant: ResolvedTenantConfig): void {\n const isFieldStrategy = tenant.strategy === 'field';\n const isObjectId = tenant.fieldType === 'objectId';\n\n schema.add({\n [tenant.tenantField]: {\n type: isObjectId ? mongoose.Schema.Types.ObjectId : String,\n ...(tenant.enabled && tenant.required ? { required: true } : {}),\n index: true,\n ...(isObjectId && tenant.ref ? { ref: tenant.ref } : {}),\n },\n });\n\n if (!tenant.enabled || !isFieldStrategy) return;\n\n const existingIndexes = (\n schema as unknown as {\n _indexes: Array<[Record<string, unknown>, Record<string, unknown>]>;\n }\n )._indexes;\n if (existingIndexes && existingIndexes.length > 0) {\n for (const indexEntry of existingIndexes) {\n const fields = indexEntry[0];\n if (fields[tenant.tenantField] !== undefined) continue;\n const newFields: Record<string, unknown> = { [tenant.tenantField]: 1 };\n for (const [key, val] of Object.entries(fields)) {\n newFields[key] = val;\n }\n indexEntry[0] = newFields;\n }\n }\n}\n","import { Schema, type Connection, type Document, type Model } from 'mongoose';\nimport type { ResolvedTenantConfig } from '@classytic/primitives/tenant';\nimport { PERFORMANCE_EVENT_TYPE_VALUES } from '../domain/enums/event-type.enum.js';\nimport { injectTenantField } from './inject-tenant.js';\n\nexport interface PerformanceEventDocument extends Document {\n organizationId: unknown;\n supplierId: string;\n type: string;\n occurredAt: Date;\n metrics: Record<string, unknown>;\n sourceRef?: string;\n sourceType?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nconst metricsSchema = new Schema(\n {\n quantity: { type: Number, min: 0 },\n expectedAt: Date,\n actualAt: Date,\n delayDays: Number,\n expectedUnitCost: { type: Number, min: 0 },\n actualUnitCost: { type: Number, min: 0 },\n variancePct: Number,\n },\n { _id: false, strict: false },\n);\n\nexport interface PerformanceEventModelConfig {\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean;\n}\n\nfunction buildPerformanceEventSchema(tenant: ResolvedTenantConfig): Schema {\n const schema = new Schema<PerformanceEventDocument>(\n {\n supplierId: { type: String, required: true },\n type: { type: String, required: true, enum: PERFORMANCE_EVENT_TYPE_VALUES },\n occurredAt: { type: Date, required: true },\n metrics: { type: metricsSchema, required: true, default: {} },\n sourceRef: String,\n sourceType: String,\n metadata: { type: Schema.Types.Mixed },\n },\n { timestamps: true, collection: 'supplier_performance_events' },\n );\n\n // Primary scorecard query — events for a supplier in a time window.\n // Tenant prefix added by `injectTenantField` per PACKAGE_RULES §P11.\n schema.index({ supplierId: 1, occurredAt: 1 });\n\n // Source drill-down — \"why did this PO show up in the late bucket?\"\n schema.index(\n { sourceRef: 1, type: 1 },\n { partialFilterExpression: { sourceRef: { $exists: true } } },\n );\n\n injectTenantField(schema, tenant);\n return schema;\n}\n\nexport class PerformanceEventModelCollisionError extends Error {\n constructor(name: string) {\n super(\n `[supplier-performance] Mongoose model \"${name}\" already exists on this connection. ` +\n `Pass \\`forceRecreate: true\\` for hot-reload, or use two Mongoose connections.`,\n );\n this.name = 'PerformanceEventModelCollisionError';\n }\n}\n\nexport function createPerformanceEventModel(\n connection: Connection,\n tenant: ResolvedTenantConfig,\n config: PerformanceEventModelConfig = {},\n): Model<PerformanceEventDocument> {\n if (connection.models.PerformanceEvent) {\n if (config.forceRecreate) {\n connection.deleteModel('PerformanceEvent');\n } else {\n throw new PerformanceEventModelCollisionError('PerformanceEvent');\n }\n }\n const collection = (config.collectionPrefix ?? '') + 'supplier_performance_events';\n return connection.model<PerformanceEventDocument>(\n 'PerformanceEvent',\n buildPerformanceEventSchema(tenant),\n collection,\n );\n}\n","import { Schema, type Connection, type Document, type Model } from 'mongoose';\nimport type { ResolvedTenantConfig } from '@classytic/primitives/tenant';\nimport { injectTenantField } from './inject-tenant.js';\n\nexport interface SupplierScoreDocument extends Document {\n organizationId: unknown;\n supplierId: string;\n period: { start: Date; end: Date; label?: string };\n metrics: Record<string, unknown>;\n computedAt: Date;\n eventCount: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nconst periodSchema = new Schema(\n {\n start: { type: Date, required: true },\n end: { type: Date, required: true },\n label: String,\n },\n { _id: false },\n);\n\nconst metricsSchema = new Schema(\n {\n deliveryCount: { type: Number, default: 0, min: 0 },\n onTimeCount: { type: Number, default: 0, min: 0 },\n onTimeRate: { type: Number, default: 0, min: 0, max: 1 },\n avgDelayDays: { type: Number, default: 0 },\n unitsReceived: { type: Number, default: 0, min: 0 },\n defectiveUnits: { type: Number, default: 0, min: 0 },\n defectRate: { type: Number, default: 0, min: 0, max: 1 },\n priceVarianceCount: { type: Number, default: 0, min: 0 },\n avgPriceVariance: { type: Number, default: 0 },\n compositeScore: { type: Number, default: 0, min: 0, max: 100 },\n },\n { _id: false },\n);\n\nexport interface SupplierScoreModelConfig {\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean;\n}\n\nfunction buildSupplierScoreSchema(tenant: ResolvedTenantConfig): Schema {\n const schema = new Schema<SupplierScoreDocument>(\n {\n supplierId: { type: String, required: true },\n period: { type: periodSchema, required: true },\n metrics: { type: metricsSchema, required: true, default: {} },\n computedAt: { type: Date, required: true },\n eventCount: { type: Number, required: true, default: 0, min: 0 },\n },\n { timestamps: true, collection: 'supplier_scores' },\n );\n\n // One score per (supplier, period.start, period.end). Re-computing the\n // same window upserts in place — tenant scoping prepended by\n // `injectTenantField`.\n schema.index({ supplierId: 1, 'period.start': 1, 'period.end': 1 }, { unique: true });\n\n // Dashboard query — \"list all suppliers' scores for the latest period\".\n schema.index({ 'period.end': -1, 'metrics.compositeScore': -1 });\n\n injectTenantField(schema, tenant);\n return schema;\n}\n\nexport class SupplierScoreModelCollisionError extends Error {\n constructor(name: string) {\n super(\n `[supplier-performance] Mongoose model \"${name}\" already exists on this connection. ` +\n `Pass \\`forceRecreate: true\\` for hot-reload, or use two Mongoose connections.`,\n );\n this.name = 'SupplierScoreModelCollisionError';\n }\n}\n\nexport function createSupplierScoreModel(\n connection: Connection,\n tenant: ResolvedTenantConfig,\n config: SupplierScoreModelConfig = {},\n): Model<SupplierScoreDocument> {\n if (connection.models.SupplierScore) {\n if (config.forceRecreate) {\n connection.deleteModel('SupplierScore');\n } else {\n throw new SupplierScoreModelCollisionError('SupplierScore');\n }\n }\n const collection = (config.collectionPrefix ?? '') + 'supplier_scores';\n return connection.model<SupplierScoreDocument>(\n 'SupplierScore',\n buildSupplierScoreSchema(tenant),\n collection,\n );\n}\n","import type { Connection } from 'mongoose';\nimport type { ResolvedTenantConfig, TenantConfig } from '@classytic/primitives/tenant';\nimport {\n createPerformanceEventModel,\n type PerformanceEventDocument,\n} from './performance-event.model.js';\nimport {\n createSupplierScoreModel,\n type SupplierScoreDocument,\n} from './supplier-score.model.js';\nimport {\n resolveSupplierPerformanceTenant,\n type SupplierPerformanceTenantInput,\n} from './inject-tenant.js';\n\nexport interface SupplierPerformanceModelBundle {\n PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;\n SupplierScore: ReturnType<typeof createSupplierScoreModel>;\n}\n\nexport type { PerformanceEventDocument, SupplierScoreDocument };\n\nexport interface CreateSupplierPerformanceModelsOptions {\n tenant?: ResolvedTenantConfig | TenantConfig | boolean | SupplierPerformanceTenantInput;\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean | undefined;\n}\n\nexport function createSupplierPerformanceModels(\n connection: Connection,\n options: CreateSupplierPerformanceModelsOptions = {},\n): SupplierPerformanceModelBundle {\n const tenant: ResolvedTenantConfig = (() => {\n if (\n typeof options.tenant === 'object' &&\n options.tenant !== null &&\n 'strategy' in options.tenant &&\n 'tenantField' in options.tenant\n ) {\n return options.tenant as ResolvedTenantConfig;\n }\n if (options.tenant !== undefined) {\n return resolveSupplierPerformanceTenant(options.tenant as SupplierPerformanceTenantInput);\n }\n return resolveSupplierPerformanceTenant();\n })();\n\n const modelConfig = {\n ...(options.collectionPrefix !== undefined ? { collectionPrefix: options.collectionPrefix } : {}),\n ...(options.forceRecreate !== undefined ? { forceRecreate: options.forceRecreate } : {}),\n };\n\n return {\n PerformanceEvent: createPerformanceEventModel(connection, tenant, modelConfig),\n SupplierScore: createSupplierScoreModel(connection, tenant, modelConfig),\n };\n}\n","import type { ClientSession } from 'mongoose';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\n\nexport interface RepoOptions {\n organizationId: string;\n actorRef: string;\n actorKind: SupplierPerformanceContext['actorKind'];\n correlationId: string;\n session?: ClientSession;\n idempotencyKey?: string;\n [key: string]: unknown;\n}\n\nexport function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions {\n const opts: RepoOptions = {\n organizationId: ctx.organizationId,\n actorRef: ctx.actorRef,\n actorKind: ctx.actorKind,\n correlationId: ctx.correlationId,\n };\n if (ctx.session !== undefined) opts.session = ctx.session as ClientSession;\n if (ctx.idempotencyKey !== undefined) opts.idempotencyKey = ctx.idempotencyKey;\n return opts;\n}\n","/**\n * PerformanceEventRepository — append-only event log.\n *\n * No mutation verbs beyond mongokit's inherited `create` / `findAll` /\n * `getByQuery`. Aggregation lives in `ScoreService` — this repo's only\n * job is \"store one row per supplier signal\".\n */\nimport { Repository, type PluginType, methodRegistryPlugin } from '@classytic/mongokit';\nimport type { Model } from 'mongoose';\nimport type { PerformanceEventDocument } from '../models/performance-event.model.js';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport { repoOptionsFromCtx } from './repo-options.js';\n\nexport interface PerformanceEventRepositoryConfig {\n model: Model<PerformanceEventDocument>;\n plugins?: PluginType[];\n}\n\nexport class PerformanceEventRepository extends Repository<PerformanceEventDocument> {\n constructor(config: PerformanceEventRepositoryConfig) {\n super(config.model, [methodRegistryPlugin(), ...(config.plugins ?? [])]);\n }\n\n /**\n * Range query for one supplier — `[start, end)`. The (supplierId,\n * occurredAt) compound index serves this directly. Returned lean for\n * cheap aggregation in the service layer.\n */\n async findInWindow(\n supplierId: string,\n start: Date,\n end: Date,\n ctx: SupplierPerformanceContext,\n ): Promise<PerformanceEventDocument[]> {\n return this.findAll(\n {\n supplierId,\n occurredAt: { $gte: start, $lt: end },\n },\n { ...repoOptionsFromCtx(ctx), lean: true },\n ) as unknown as Promise<PerformanceEventDocument[]>;\n }\n}\n","/**\n * SupplierScoreRepository — cached scorecard upserts.\n *\n * `upsertForPeriod` is the only domain verb — it replaces any prior\n * computation for the same (supplierId, period.start, period.end) tuple\n * (enforced by the unique index on the model). Pure CRUD beyond that.\n */\nimport { Repository, type PluginType, methodRegistryPlugin } from '@classytic/mongokit';\nimport type { Model } from 'mongoose';\nimport type { SupplierScoreDocument } from '../models/supplier-score.model.js';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport type { ScoreMetrics, ScorePeriod } from '../domain/entities/supplier-score.entity.js';\nimport { repoOptionsFromCtx } from './repo-options.js';\n\nexport interface SupplierScoreRepositoryConfig {\n model: Model<SupplierScoreDocument>;\n plugins?: PluginType[];\n}\n\nexport interface UpsertScoreInput {\n supplierId: string;\n period: ScorePeriod;\n metrics: ScoreMetrics;\n eventCount: number;\n computedAt?: Date;\n}\n\nexport class SupplierScoreRepository extends Repository<SupplierScoreDocument> {\n constructor(config: SupplierScoreRepositoryConfig) {\n super(config.model, [methodRegistryPlugin(), ...(config.plugins ?? [])]);\n }\n\n /**\n * Atomic upsert keyed on (supplierId, period). Replaces an existing\n * snapshot in place — `computeScore` is idempotent. The unique index\n * on `(supplierId, period.start, period.end)` enforces that only one\n * row per (tenant, supplier, window) ever exists.\n */\n async upsertForPeriod(\n input: UpsertScoreInput,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument> {\n const computedAt = input.computedAt ?? new Date();\n const updated = await this.findOneAndUpdate<SupplierScoreDocument>(\n {\n supplierId: input.supplierId,\n 'period.start': input.period.start,\n 'period.end': input.period.end,\n },\n {\n $set: {\n period: input.period,\n metrics: input.metrics,\n eventCount: input.eventCount,\n computedAt,\n },\n },\n {\n ...repoOptionsFromCtx(ctx),\n upsert: true,\n returnDocument: 'after',\n lean: false,\n },\n );\n if (!updated) {\n throw new Error(\n `[supplier-performance] upsertForPeriod returned null for ${input.supplierId} ${input.period.start.toISOString()}`,\n );\n }\n return updated;\n }\n\n /**\n * Latest snapshot whose period contains `asOf` (or covers it via\n * `period.end`). Useful for dashboard reads — pick the most recent\n * computed scorecard for this supplier.\n */\n async findLatest(\n supplierId: string,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument | null> {\n const docs = await this.findAll(\n { supplierId },\n {\n ...repoOptionsFromCtx(ctx),\n lean: true,\n sort: { 'period.end': -1 },\n limit: 1,\n },\n );\n return (docs[0] as SupplierScoreDocument | undefined) ?? null;\n }\n}\n","/**\n * Pure scorecard aggregation. No I/O, no side effects, no `Date.now()`.\n *\n * Hosts that need different weights / scoring formulas write their own\n * roll-up over the same `PerformanceEvent` array — this module ships\n * one sane default.\n */\nimport type {\n PerformanceEvent,\n PerformanceMetrics,\n} from '../domain/entities/performance-event.entity.js';\nimport type {\n ScoreMetrics,\n ScorePeriod,\n} from '../domain/entities/supplier-score.entity.js';\n\nconst COMPOSITE_WEIGHTS = {\n onTime: 0.5,\n defectFree: 0.4,\n pricedToPlan: 0.1,\n} as const;\n\n/**\n * Aggregate raw performance events into a scorecard. Events outside the\n * `period` window are filtered out (defensive — callers should already\n * have queried within the window).\n */\nexport function scoreFromEvents(\n events: ReadonlyArray<PerformanceEvent>,\n period: ScorePeriod,\n): ScoreMetrics {\n const inWindow = events.filter(\n (e) => e.occurredAt >= period.start && e.occurredAt < period.end,\n );\n\n let deliveryCount = 0;\n let onTimeCount = 0;\n let totalDelayDays = 0;\n let lateCount = 0;\n\n let unitsReceived = 0;\n let defectiveUnits = 0;\n\n let priceVarianceCount = 0;\n let totalVariancePct = 0;\n\n for (const event of inWindow) {\n const metrics = (event.metrics ?? {}) as PerformanceMetrics;\n const qty = Number(metrics.quantity ?? 1);\n\n switch (event.type) {\n case 'delivery_received': {\n deliveryCount++;\n onTimeCount++;\n unitsReceived += qty;\n break;\n }\n case 'delivery_late': {\n deliveryCount++;\n lateCount++;\n unitsReceived += qty;\n const delay = Number(metrics.delayDays ?? 0);\n if (delay > 0) totalDelayDays += delay;\n break;\n }\n case 'defect_reported': {\n defectiveUnits += qty;\n break;\n }\n case 'price_variance': {\n priceVarianceCount++;\n totalVariancePct += Number(metrics.variancePct ?? 0);\n break;\n }\n }\n }\n\n const onTimeRate = deliveryCount > 0 ? onTimeCount / deliveryCount : 0;\n const avgDelayDays = lateCount > 0 ? totalDelayDays / lateCount : 0;\n const defectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;\n const avgPriceVariance =\n priceVarianceCount > 0 ? totalVariancePct / priceVarianceCount : 0;\n\n // Composite: higher = better. Bounds at 0..100. Variance flips sign so\n // both over- and under-billing reduce the score.\n const composite =\n onTimeRate * COMPOSITE_WEIGHTS.onTime +\n (1 - defectRate) * COMPOSITE_WEIGHTS.defectFree +\n (1 - Math.min(Math.abs(avgPriceVariance), 1)) * COMPOSITE_WEIGHTS.pricedToPlan;\n\n return {\n deliveryCount,\n onTimeCount,\n onTimeRate: round(onTimeRate, 4),\n avgDelayDays: round(avgDelayDays, 2),\n unitsReceived,\n defectiveUnits,\n defectRate: round(defectRate, 4),\n priceVarianceCount,\n avgPriceVariance: round(avgPriceVariance, 4),\n compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2),\n };\n}\n\nfunction round(value: number, digits: number): number {\n const factor = 10 ** digits;\n return Math.round(value * factor) / factor;\n}\n","/**\n * Canonical event names emitted by `@classytic/supplier-performance`.\n *\n * Prefix `supplier_performance:` matches the sibling-package convention\n * (`order:...`, `commission:...`). Hosts wiring an Arc transport can\n * pattern-match on `supplier_performance:*`.\n */\nexport const SupplierPerformanceEvents = {\n EVENT_RECORDED: 'supplier_performance:event.recorded',\n SCORE_COMPUTED: 'supplier_performance:score.computed',\n} as const;\n\nexport type SupplierPerformanceEventName =\n (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];\n","/**\n * ScoreService — orchestration on top of the two repositories.\n *\n * Service-justified per PACKAGE_RULES §2 (multi-repo orchestration + event\n * emission + pure aggregation algorithm). Pure scoring math lives in\n * `calc/score-calculator.ts`; the service handles persistence + events.\n *\n * Verbs:\n * recordEvent(input, ctx) — append to event log + emit `event.recorded`\n * computeScore(input, ctx) — aggregate + upsert + emit `score.computed`\n * getScorecard(supplierId, period?, ctx) — read-or-compute (lazy refresh)\n */\nimport type { EventTransport } from '@classytic/primitives/events';\nimport { createEvent } from '@classytic/primitives/events';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport type {\n PerformanceEvent,\n RecordEventInput,\n} from '../domain/entities/performance-event.entity.js';\nimport type {\n ComputeScoreInput,\n ScorePeriod,\n SupplierScore,\n} from '../domain/entities/supplier-score.entity.js';\nimport type { PerformanceEventDocument } from '../models/performance-event.model.js';\nimport type { SupplierScoreDocument } from '../models/supplier-score.model.js';\nimport type { PerformanceEventRepository } from '../repositories/performance-event.repository.js';\nimport type { SupplierScoreRepository } from '../repositories/supplier-score.repository.js';\nimport { repoOptionsFromCtx } from '../repositories/repo-options.js';\nimport { scoreFromEvents } from '../calc/score-calculator.js';\nimport { SupplierPerformanceEvents } from '../events/event-constants.js';\n\nexport interface ScoreServiceConfig {\n events: PerformanceEventRepository;\n scores: SupplierScoreRepository;\n eventTransport?: EventTransport | undefined;\n logger?: { error(message: string, ...args: unknown[]): void };\n}\n\nexport class ScoreService {\n private events: PerformanceEventRepository;\n private scores: SupplierScoreRepository;\n private eventTransport?: EventTransport;\n private logger: NonNullable<ScoreServiceConfig['logger']>;\n\n constructor(config: ScoreServiceConfig) {\n this.events = config.events;\n this.scores = config.scores;\n this.eventTransport = config.eventTransport;\n this.logger = config.logger ?? console;\n }\n\n /**\n * Append a single performance event to the log. Idempotent on the\n * caller's side via `metadata.idempotencyKey` if hosts wire their own\n * dedup index — this kernel doesn't enforce it (different hosts have\n * different keying preferences: PO-line, PO+SKU, etc.).\n */\n async recordEvent(\n input: RecordEventInput,\n ctx: SupplierPerformanceContext,\n ): Promise<PerformanceEventDocument> {\n if (!input.supplierId) throw new RecordEventValidationError('supplierId is required');\n\n const occurredAt = input.occurredAt ?? new Date();\n const doc = (await this.events.create(\n {\n organizationId: ctx.organizationId,\n supplierId: input.supplierId,\n type: input.type,\n occurredAt,\n metrics: input.metrics ?? {},\n ...(input.sourceRef !== undefined ? { sourceRef: input.sourceRef } : {}),\n ...(input.sourceType !== undefined ? { sourceType: input.sourceType } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n },\n repoOptionsFromCtx(ctx),\n )) as PerformanceEventDocument;\n\n this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {\n supplierId: input.supplierId,\n type: input.type,\n occurredAt: occurredAt.toISOString(),\n sourceRef: input.sourceRef,\n });\n\n return doc;\n }\n\n /**\n * Compute (or recompute) a scorecard for one (supplier, period) pair.\n * Pulls all events in window, runs the pure calculator, persists the\n * snapshot. Idempotent — calling twice with the same period upserts in\n * place.\n */\n async computeScore(\n input: ComputeScoreInput,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument> {\n const period = normalizePeriod(input.period);\n const rawEvents = await this.events.findInWindow(\n input.supplierId,\n period.start,\n period.end,\n ctx,\n );\n const eventsForCalc = rawEvents.map(toCalcEvent);\n const metrics = scoreFromEvents(eventsForCalc, period);\n\n const doc = await this.scores.upsertForPeriod(\n {\n supplierId: input.supplierId,\n period,\n metrics,\n eventCount: eventsForCalc.length,\n },\n ctx,\n );\n\n this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {\n supplierId: input.supplierId,\n period: { start: period.start.toISOString(), end: period.end.toISOString() },\n compositeScore: metrics.compositeScore,\n eventCount: eventsForCalc.length,\n });\n\n return doc;\n }\n\n /**\n * Read-or-compute. Returns the latest cached scorecard for the supplier;\n * if `period` is supplied, recomputes for that exact window before\n * returning. Pure read otherwise — won't refresh stale snapshots\n * implicitly (callers know when their data has changed).\n */\n async getScorecard(\n supplierId: string,\n ctx: SupplierPerformanceContext,\n period?: ScorePeriod,\n ): Promise<SupplierScoreDocument | null> {\n if (period) {\n return this.computeScore({ supplierId, period }, ctx);\n }\n return this.scores.findLatest(supplierId, ctx);\n }\n\n // ── Internals ────────────────────────────────────────────────────\n\n private publish(\n type: string,\n ctx: SupplierPerformanceContext,\n data: Record<string, unknown>,\n ): void {\n if (!this.eventTransport) return;\n const event = createEvent(type, data, {\n organizationId: ctx.organizationId,\n userId: ctx.actorRef,\n correlationId: ctx.correlationId,\n });\n this.eventTransport.publish(event).catch((err) => {\n this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);\n });\n }\n}\n\n// ── Adapters ───────────────────────────────────────────────────────────\n\nfunction toCalcEvent(doc: PerformanceEventDocument): PerformanceEvent {\n return {\n _id: doc._id as PerformanceEvent['_id'],\n organizationId: String(doc.organizationId),\n supplierId: doc.supplierId,\n type: doc.type as PerformanceEvent['type'],\n occurredAt: doc.occurredAt,\n metrics: (doc.metrics ?? {}) as PerformanceEvent['metrics'],\n ...(doc.sourceRef !== undefined ? { sourceRef: doc.sourceRef } : {}),\n ...(doc.sourceType !== undefined ? { sourceType: doc.sourceType } : {}),\n ...(doc.metadata !== undefined ? { metadata: doc.metadata } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n };\n}\n\nfunction normalizePeriod(period: ScorePeriod): ScorePeriod {\n if (period.end.getTime() <= period.start.getTime()) {\n throw new RecordEventValidationError(\n `period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`,\n );\n }\n return period;\n}\n\n// ── Errors ─────────────────────────────────────────────────────────────\n\nexport class RecordEventValidationError extends Error {\n override readonly name = 'RecordEventValidationError';\n readonly code = 'SUPPLIER_PERFORMANCE_VALIDATION' as const;\n constructor(message: string) {\n super(message);\n }\n}\n","import type {\n DomainEvent,\n EventHandler,\n EventTransport,\n} from '@classytic/primitives/events';\nimport { matchEventPattern } from '@classytic/primitives/events';\n\nexport interface InProcessBusOptions {\n logger?: { error(message: string, ...args: unknown[]): void };\n}\n\n/**\n * Zero-dep in-process event bus. Subscribers can use glob patterns\n * (`supplier_performance:*`, `*`, exact type). Subscriber errors are\n * caught and logged — they never break the emitter or sibling\n * subscribers.\n *\n * Drop-in compatible with any `EventTransport` — hosts replace it by\n * passing their own at `createSupplierPerformance({ eventTransport })`.\n */\nexport class InProcessSupplierPerformanceBus implements EventTransport {\n readonly name = 'in-process-supplier-performance';\n private patterns = new Map<string, Set<EventHandler>>();\n private logger: NonNullable<InProcessBusOptions['logger']>;\n\n constructor(options: InProcessBusOptions = {}) {\n this.logger = options.logger ?? console;\n }\n\n async publish(event: DomainEvent): Promise<void> {\n for (const [pattern, handlers] of this.patterns) {\n if (!matchEventPattern(pattern, event.type)) continue;\n for (const fn of handlers) {\n try {\n await fn(event);\n } catch (err) {\n this.logger.error(\n `[supplier-performance] subscriber threw on ${event.type}: ${(err as Error).message}`,\n err,\n );\n }\n }\n }\n }\n\n async subscribe(pattern: string, handler: EventHandler): Promise<() => void> {\n let set = this.patterns.get(pattern);\n if (!set) {\n set = new Set();\n this.patterns.set(pattern, set);\n }\n set.add(handler);\n return () => {\n const s = this.patterns.get(pattern);\n s?.delete(handler);\n if (s && s.size === 0) this.patterns.delete(pattern);\n };\n }\n}\n","import { createSupplierPerformanceModels } from '../models/create-models.js';\nimport { resolveSupplierPerformanceTenant } from '../models/inject-tenant.js';\nimport { PerformanceEventRepository } from '../repositories/performance-event.repository.js';\nimport { SupplierScoreRepository } from '../repositories/supplier-score.repository.js';\nimport { ScoreService } from '../services/score.service.js';\nimport { InProcessSupplierPerformanceBus } from '../events/in-process-bus.js';\nimport type {\n SupplierPerformanceConfig,\n SupplierPerformanceEngine,\n} from './engine-types.js';\n\nexport async function createSupplierPerformance(\n config: SupplierPerformanceConfig,\n): Promise<SupplierPerformanceEngine> {\n if (!config.connection) {\n throw new Error('createSupplierPerformance: config.connection is required');\n }\n\n const logger = config.logger ?? console;\n const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });\n\n const tenant = resolveSupplierPerformanceTenant(config.tenant);\n const models = createSupplierPerformanceModels(config.connection, {\n tenant,\n ...(config.collectionPrefix !== undefined ? { collectionPrefix: config.collectionPrefix } : {}),\n ...(config.forceRecreate !== undefined ? { forceRecreate: config.forceRecreate } : {}),\n });\n\n const performanceEvent = new PerformanceEventRepository({\n model: models.PerformanceEvent,\n ...(config.repositoryPlugins?.performanceEvent !== undefined\n ? { plugins: config.repositoryPlugins.performanceEvent }\n : {}),\n });\n const supplierScore = new SupplierScoreRepository({\n model: models.SupplierScore,\n ...(config.repositoryPlugins?.supplierScore !== undefined\n ? { plugins: config.repositoryPlugins.supplierScore }\n : {}),\n });\n\n const score = new ScoreService({\n events: performanceEvent,\n scores: supplierScore,\n eventTransport: events,\n logger,\n });\n\n return {\n models,\n repositories: { performanceEvent, supplierScore },\n services: { score },\n events,\n async syncIndexes() {\n await Promise.all([\n models.PerformanceEvent.syncIndexes(),\n models.SupplierScore.syncIndexes(),\n ]);\n },\n async destroy() {\n // No-op — host owns the connection lifecycle.\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,MAAa,uBAAuB;CAClC,mBAAmB;CACnB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CACjB;AAKD,MAAa,gCAAgC,OAAO,OAClD,qBACD;;;;;;;;;;;ACHD,SAAgB,iCACd,QAAwC,EAAE,EACpB;AACtB,KAAI,OAAO,UAAU,UACnB,QAAO,sBAAsB,oB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