@ontrails/core 1.0.0-beta.10 → 1.0.0-beta.12
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/.turbo/turbo-lint.log +1 -1
- package/CHANGELOG.md +33 -0
- package/README.md +1 -0
- package/dist/context.d.ts +2 -2
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +12 -7
- package/dist/context.js.map +1 -1
- package/dist/execute.d.ts +8 -3
- package/dist/execute.d.ts.map +1 -1
- package/dist/execute.js +25 -6
- package/dist/execute.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/service-config.d.ts +22 -0
- package/dist/service-config.d.ts.map +1 -0
- package/dist/service-config.js +208 -0
- package/dist/service-config.js.map +1 -0
- package/dist/service.d.ts +75 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +56 -0
- package/dist/service.js.map +1 -0
- package/dist/topo.d.ts +7 -0
- package/dist/topo.d.ts.map +1 -1
- package/dist/topo.js +37 -8
- package/dist/topo.js.map +1 -1
- package/dist/trail.d.ts +9 -2
- package/dist/trail.d.ts.map +1 -1
- package/dist/trail.js +2 -1
- package/dist/trail.js.map +1 -1
- package/dist/types.d.ts +27 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -1
- package/dist/types.js.map +1 -1
- package/dist/validate-topo.d.ts.map +1 -1
- package/dist/validate-topo.js +16 -0
- package/dist/validate-topo.js.map +1 -1
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +34 -3
- package/dist/validation.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/context.test.ts +12 -0
- package/src/__tests__/dispatch.test.ts +29 -2
- package/src/__tests__/execute.test.ts +318 -3
- package/src/__tests__/layer.test.ts +3 -2
- package/src/__tests__/service-config.test.ts +224 -0
- package/src/__tests__/service.test.ts +197 -0
- package/src/__tests__/topo.test.ts +71 -0
- package/src/__tests__/trail-permit.test.ts +60 -0
- package/src/__tests__/trail.test.ts +46 -2
- package/src/__tests__/validate-topo.test.ts +45 -1
- package/src/__tests__/validation.test.ts +53 -0
- package/src/context.ts +18 -9
- package/src/execute.ts +63 -9
- package/src/index.ts +20 -0
- package/src/service-config.ts +354 -0
- package/src/service.ts +145 -0
- package/src/topo.ts +53 -9
- package/src/trail.ts +21 -3
- package/src/types.ts +32 -1
- package/src/validate-topo.ts +22 -0
- package/src/validation.ts +35 -3
- package/tsconfig.tsbuildinfo +1 -1
package/src/execute.ts
CHANGED
|
@@ -8,14 +8,21 @@
|
|
|
8
8
|
|
|
9
9
|
import type { AnyTrail } from './trail.js';
|
|
10
10
|
import type { Layer } from './layer.js';
|
|
11
|
-
import type {
|
|
11
|
+
import type { ServiceOverrideMap } from './service.js';
|
|
12
|
+
import type { TrailContext, TrailContextInit } from './types.js';
|
|
12
13
|
|
|
13
14
|
import { composeLayers } from './layer.js';
|
|
14
15
|
import { createTrailContext } from './context.js';
|
|
15
16
|
import { InternalError } from './errors.js';
|
|
16
17
|
import { Result } from './result.js';
|
|
18
|
+
import { createServiceLookup } from './service.js';
|
|
19
|
+
import { resolveServices } from './service-config.js';
|
|
17
20
|
import { validateInput } from './validation.js';
|
|
18
21
|
|
|
22
|
+
type MutableTrailContext = {
|
|
23
|
+
-readonly [K in keyof TrailContext]: TrailContext[K];
|
|
24
|
+
};
|
|
25
|
+
|
|
19
26
|
// ---------------------------------------------------------------------------
|
|
20
27
|
// Options
|
|
21
28
|
// ---------------------------------------------------------------------------
|
|
@@ -23,14 +30,20 @@ import { validateInput } from './validation.js';
|
|
|
23
30
|
/** Options for executeTrail. */
|
|
24
31
|
export interface ExecuteTrailOptions {
|
|
25
32
|
/** Partial context overrides merged on top of the base context. */
|
|
26
|
-
readonly ctx?: Partial<
|
|
33
|
+
readonly ctx?: Partial<TrailContextInit> | undefined;
|
|
27
34
|
/** AbortSignal override (takes final precedence over ctx and factory). */
|
|
28
35
|
readonly signal?: AbortSignal | undefined;
|
|
29
36
|
/** Layers to compose around the implementation. */
|
|
30
37
|
readonly layers?: readonly Layer[] | undefined;
|
|
31
38
|
/** Factory that produces a base TrailContext (takes precedence over defaults). */
|
|
32
39
|
readonly createContext?:
|
|
33
|
-
| (() =>
|
|
40
|
+
| (() => TrailContextInit | Promise<TrailContextInit>)
|
|
41
|
+
| undefined;
|
|
42
|
+
/** Explicit service instance overrides keyed by service ID. */
|
|
43
|
+
readonly services?: ServiceOverrideMap | undefined;
|
|
44
|
+
/** Config values for services that declare a `config` schema, keyed by service ID. */
|
|
45
|
+
readonly configValues?:
|
|
46
|
+
| Readonly<Record<string, Record<string, unknown>>>
|
|
34
47
|
| undefined;
|
|
35
48
|
}
|
|
36
49
|
|
|
@@ -49,9 +62,10 @@ export interface ExecuteTrailOptions {
|
|
|
49
62
|
const resolveContext = async (
|
|
50
63
|
options?: ExecuteTrailOptions
|
|
51
64
|
): Promise<TrailContext> => {
|
|
52
|
-
const
|
|
65
|
+
const seed = options?.createContext
|
|
53
66
|
? await options.createContext()
|
|
54
67
|
: createTrailContext();
|
|
68
|
+
const base = seed.service ? seed : createTrailContext(seed);
|
|
55
69
|
const withOverrides = options?.ctx
|
|
56
70
|
? {
|
|
57
71
|
...base,
|
|
@@ -59,9 +73,42 @@ const resolveContext = async (
|
|
|
59
73
|
extensions: { ...base.extensions, ...options.ctx.extensions },
|
|
60
74
|
}
|
|
61
75
|
: base;
|
|
62
|
-
|
|
76
|
+
const resolved = options?.signal
|
|
63
77
|
? { ...withOverrides, signal: options.signal }
|
|
64
78
|
: withOverrides;
|
|
79
|
+
if (
|
|
80
|
+
options?.ctx?.extensions !== undefined ||
|
|
81
|
+
resolved.service === undefined
|
|
82
|
+
) {
|
|
83
|
+
const bound = { ...resolved } as MutableTrailContext;
|
|
84
|
+
bound.service = createServiceLookup(() => bound);
|
|
85
|
+
return bound;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return resolved as TrailContext;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const prepareContext = async (
|
|
92
|
+
trail: AnyTrail,
|
|
93
|
+
options?: ExecuteTrailOptions
|
|
94
|
+
): Promise<Result<TrailContext, Error>> => {
|
|
95
|
+
const baseCtx = await resolveContext(options);
|
|
96
|
+
return await resolveServices(
|
|
97
|
+
trail,
|
|
98
|
+
baseCtx,
|
|
99
|
+
options?.services,
|
|
100
|
+
options?.configValues
|
|
101
|
+
);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const runTrail = async (
|
|
105
|
+
trail: AnyTrail,
|
|
106
|
+
input: unknown,
|
|
107
|
+
ctx: TrailContext,
|
|
108
|
+
layers: readonly Layer[]
|
|
109
|
+
): Promise<Result<unknown, Error>> => {
|
|
110
|
+
const impl = composeLayers([...layers], trail, trail.run);
|
|
111
|
+
return await impl(input, ctx);
|
|
65
112
|
};
|
|
66
113
|
|
|
67
114
|
// ---------------------------------------------------------------------------
|
|
@@ -85,10 +132,17 @@ export const executeTrail = async (
|
|
|
85
132
|
return validated;
|
|
86
133
|
}
|
|
87
134
|
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
135
|
+
const resolvedCtx = await prepareContext(trail, options);
|
|
136
|
+
if (resolvedCtx.isErr()) {
|
|
137
|
+
return resolvedCtx;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return await runTrail(
|
|
141
|
+
trail,
|
|
142
|
+
validated.value,
|
|
143
|
+
resolvedCtx.value,
|
|
144
|
+
options?.layers ?? []
|
|
145
|
+
);
|
|
92
146
|
} catch (error: unknown) {
|
|
93
147
|
const message = error instanceof Error ? error.message : String(error);
|
|
94
148
|
return Result.err(new InternalError(message));
|
package/src/index.ts
CHANGED
|
@@ -30,15 +30,35 @@ export type { ErrorCategory } from './errors.js';
|
|
|
30
30
|
export type {
|
|
31
31
|
Implementation,
|
|
32
32
|
TrailContext,
|
|
33
|
+
TrailContextInit,
|
|
33
34
|
FollowFn,
|
|
35
|
+
BasePermit,
|
|
36
|
+
PermitRequirement,
|
|
34
37
|
ProgressCallback,
|
|
35
38
|
ProgressEvent,
|
|
36
39
|
Logger,
|
|
40
|
+
ServiceLookup,
|
|
37
41
|
} from './types.js';
|
|
42
|
+
export { SURFACE_KEY } from './types.js';
|
|
38
43
|
|
|
39
44
|
// Context factory
|
|
40
45
|
export { createTrailContext } from './context.js';
|
|
41
46
|
|
|
47
|
+
// Service
|
|
48
|
+
export {
|
|
49
|
+
createServiceLookup,
|
|
50
|
+
findDuplicateServiceId,
|
|
51
|
+
isService,
|
|
52
|
+
service,
|
|
53
|
+
} from './service.js';
|
|
54
|
+
export type {
|
|
55
|
+
AnyService,
|
|
56
|
+
Service,
|
|
57
|
+
ServiceContext,
|
|
58
|
+
ServiceOverrideMap,
|
|
59
|
+
ServiceSpec,
|
|
60
|
+
} from './service.js';
|
|
61
|
+
|
|
42
62
|
// Trail
|
|
43
63
|
export { trail } from './trail.js';
|
|
44
64
|
export type {
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Service resolution pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from execute.ts to keep both modules under the 400 LOC ceiling.
|
|
5
|
+
* Handles config validation, singleton caching, concurrent-creation dedup,
|
|
6
|
+
* and the full resolve-or-create flow for declared services.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
AnyService,
|
|
11
|
+
ServiceContext,
|
|
12
|
+
ServiceOverrideMap,
|
|
13
|
+
} from './service.js';
|
|
14
|
+
import type { AnyTrail } from './trail.js';
|
|
15
|
+
import type { TrailContext } from './types.js';
|
|
16
|
+
|
|
17
|
+
import { InternalError, ValidationError } from './errors.js';
|
|
18
|
+
import { Result } from './result.js';
|
|
19
|
+
import { createServiceLookup } from './service.js';
|
|
20
|
+
|
|
21
|
+
type MutableTrailContext = {
|
|
22
|
+
-readonly [K in keyof TrailContext]: TrailContext[K];
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
type ConfigValues = Readonly<Record<string, Record<string, unknown>>>;
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Singleton caches
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
const singletonServices = new WeakMap<AnyService, Map<string, unknown>>();
|
|
32
|
+
|
|
33
|
+
/** In-flight service creation promises, keyed by service x context. */
|
|
34
|
+
const pendingCreations = new WeakMap<
|
|
35
|
+
AnyService,
|
|
36
|
+
Map<string, Promise<Result<unknown, Error>>>
|
|
37
|
+
>();
|
|
38
|
+
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Context helpers
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
const toServiceContext = (
|
|
44
|
+
ctx: TrailContext,
|
|
45
|
+
config?: unknown
|
|
46
|
+
): ServiceContext => ({
|
|
47
|
+
config,
|
|
48
|
+
cwd: ctx.cwd,
|
|
49
|
+
env: ctx.env,
|
|
50
|
+
workspaceRoot: ctx.workspaceRoot,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const toServiceContextKey = (ctx: ServiceContext): string =>
|
|
54
|
+
JSON.stringify({
|
|
55
|
+
config: ctx.config,
|
|
56
|
+
cwd: ctx.cwd,
|
|
57
|
+
env: Object.entries(ctx.env ?? {}).toSorted(([left], [right]) =>
|
|
58
|
+
left.localeCompare(right)
|
|
59
|
+
),
|
|
60
|
+
workspaceRoot: ctx.workspaceRoot,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// Config validation
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
/** Validate and resolve a service's config from the provided configValues map. */
|
|
68
|
+
const resolveServiceConfig = (
|
|
69
|
+
declaredService: AnyService,
|
|
70
|
+
configValues?: ConfigValues
|
|
71
|
+
): Result<unknown, Error> => {
|
|
72
|
+
if (declaredService.config === undefined) {
|
|
73
|
+
return Result.ok();
|
|
74
|
+
}
|
|
75
|
+
const raw = configValues?.[declaredService.id];
|
|
76
|
+
if (raw === undefined) {
|
|
77
|
+
return Result.err(
|
|
78
|
+
new ValidationError(
|
|
79
|
+
`Service "${declaredService.id}" declares a config schema but no config was provided`
|
|
80
|
+
)
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const parsed = declaredService.config.safeParse(raw);
|
|
84
|
+
if (!parsed.success) {
|
|
85
|
+
return Result.err(
|
|
86
|
+
new ValidationError(
|
|
87
|
+
`Service "${declaredService.id}" config validation failed: ${parsed.error.message}`
|
|
88
|
+
)
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
return Result.ok(parsed.data);
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// Override / cache lookups
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
const hasOwnServiceOverride = (
|
|
99
|
+
overrides: ServiceOverrideMap | undefined,
|
|
100
|
+
id: string
|
|
101
|
+
): overrides is ServiceOverrideMap =>
|
|
102
|
+
overrides !== undefined && Object.hasOwn(overrides, id);
|
|
103
|
+
|
|
104
|
+
const getCachedSingletonService = (
|
|
105
|
+
declaredService: AnyService,
|
|
106
|
+
serviceContext: ServiceContext
|
|
107
|
+
): { readonly found: boolean; readonly value: unknown } => {
|
|
108
|
+
const scopedCache = singletonServices.get(declaredService);
|
|
109
|
+
if (scopedCache === undefined) {
|
|
110
|
+
return { found: false, value: undefined };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const key = toServiceContextKey(serviceContext);
|
|
114
|
+
if (!scopedCache.has(key)) {
|
|
115
|
+
return { found: false, value: undefined };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
found: true,
|
|
120
|
+
value: scopedCache.get(key),
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const getProvidedService = (
|
|
125
|
+
ctx: TrailContext,
|
|
126
|
+
overrides: ServiceOverrideMap | undefined,
|
|
127
|
+
declaredService: AnyService,
|
|
128
|
+
serviceContext: ServiceContext
|
|
129
|
+
): Result<unknown, Error> | undefined => {
|
|
130
|
+
const { id } = declaredService;
|
|
131
|
+
if (hasOwnServiceOverride(overrides, id)) {
|
|
132
|
+
return Result.ok(overrides[id]);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (Object.hasOwn(ctx.extensions ?? {}, id)) {
|
|
136
|
+
return Result.ok(ctx.extensions?.[id]);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const cached = getCachedSingletonService(declaredService, serviceContext);
|
|
140
|
+
if (cached.found) {
|
|
141
|
+
return Result.ok(cached.value);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return undefined;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const getOverrideOrExtension = (
|
|
148
|
+
ctx: TrailContext,
|
|
149
|
+
overrides: ServiceOverrideMap | undefined,
|
|
150
|
+
declaredService: AnyService
|
|
151
|
+
): Result<unknown, Error> | undefined =>
|
|
152
|
+
getProvidedService(ctx, overrides, declaredService, toServiceContext(ctx));
|
|
153
|
+
|
|
154
|
+
type ConfigAwareResolution =
|
|
155
|
+
| Result<{ readonly kind: 'provided'; readonly value: unknown }, Error>
|
|
156
|
+
| Result<
|
|
157
|
+
{ readonly kind: 'context'; readonly serviceContext: ServiceContext },
|
|
158
|
+
Error
|
|
159
|
+
>;
|
|
160
|
+
|
|
161
|
+
const resolveConfigAwareProvidedService = (
|
|
162
|
+
ctx: TrailContext,
|
|
163
|
+
declaredService: AnyService,
|
|
164
|
+
configValues: ConfigValues | undefined
|
|
165
|
+
): ConfigAwareResolution => {
|
|
166
|
+
const configResult = resolveServiceConfig(declaredService, configValues);
|
|
167
|
+
if (configResult.isErr()) {
|
|
168
|
+
return configResult;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const serviceContext = toServiceContext(ctx, configResult.value);
|
|
172
|
+
const provided = getProvidedService(
|
|
173
|
+
ctx,
|
|
174
|
+
undefined,
|
|
175
|
+
declaredService,
|
|
176
|
+
serviceContext
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
return provided
|
|
180
|
+
? Result.ok({ kind: 'provided', value: provided.unwrap() })
|
|
181
|
+
: Result.ok({ kind: 'context', serviceContext });
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
// Instance creation
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
const toInternalServiceError = (id: string, error: unknown): InternalError => {
|
|
189
|
+
const cause = error instanceof Error ? error : undefined;
|
|
190
|
+
const message = cause?.message ?? String(error);
|
|
191
|
+
return new InternalError(`Service "${id}" failed to resolve: ${message}`, {
|
|
192
|
+
...(cause ? { cause } : {}),
|
|
193
|
+
context: { serviceId: id },
|
|
194
|
+
});
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const getSingletonServiceCache = (
|
|
198
|
+
declaredService: AnyService
|
|
199
|
+
): Map<string, unknown> => {
|
|
200
|
+
const existing = singletonServices.get(declaredService);
|
|
201
|
+
if (existing !== undefined) {
|
|
202
|
+
return existing;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const created = new Map<string, unknown>();
|
|
206
|
+
singletonServices.set(declaredService, created);
|
|
207
|
+
return created;
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const doCreateServiceInstance = async (
|
|
211
|
+
declaredService: AnyService,
|
|
212
|
+
serviceContext: ServiceContext
|
|
213
|
+
): Promise<Result<unknown, Error>> => {
|
|
214
|
+
try {
|
|
215
|
+
const created = await declaredService.create(serviceContext);
|
|
216
|
+
if (created.isErr()) {
|
|
217
|
+
return Result.err(created.error);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const instance = created.unwrap();
|
|
221
|
+
getSingletonServiceCache(declaredService).set(
|
|
222
|
+
toServiceContextKey(serviceContext),
|
|
223
|
+
instance
|
|
224
|
+
);
|
|
225
|
+
return Result.ok(instance);
|
|
226
|
+
} catch (error: unknown) {
|
|
227
|
+
return Result.err(toInternalServiceError(declaredService.id, error));
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const trackPendingCreation = (
|
|
232
|
+
declaredService: AnyService,
|
|
233
|
+
key: string,
|
|
234
|
+
promise: Promise<Result<unknown, Error>>
|
|
235
|
+
): void => {
|
|
236
|
+
const pending = pendingCreations.get(declaredService);
|
|
237
|
+
if (pending) {
|
|
238
|
+
pending.set(key, promise);
|
|
239
|
+
} else {
|
|
240
|
+
pendingCreations.set(declaredService, new Map([[key, promise]]));
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Deduplicates concurrent creation of the same service singleton.
|
|
246
|
+
* If a creation is already in flight for this service x context key,
|
|
247
|
+
* returns the existing promise instead of spawning a second factory call.
|
|
248
|
+
*/
|
|
249
|
+
const createServiceInstance = async (
|
|
250
|
+
declaredService: AnyService,
|
|
251
|
+
serviceContext: ServiceContext
|
|
252
|
+
): Promise<Result<unknown, Error>> => {
|
|
253
|
+
const key = toServiceContextKey(serviceContext);
|
|
254
|
+
const inflight = pendingCreations.get(declaredService)?.get(key);
|
|
255
|
+
if (inflight) {
|
|
256
|
+
return inflight;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const promise = doCreateServiceInstance(declaredService, serviceContext);
|
|
260
|
+
trackPendingCreation(declaredService, key, promise);
|
|
261
|
+
|
|
262
|
+
try {
|
|
263
|
+
return await promise;
|
|
264
|
+
} finally {
|
|
265
|
+
pendingCreations.get(declaredService)?.delete(key);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
/** Validate config and resolve a single declared service. */
|
|
270
|
+
const resolveDeclaredService = async (
|
|
271
|
+
declaredService: AnyService,
|
|
272
|
+
ctx: TrailContext,
|
|
273
|
+
overrides: ServiceOverrideMap | undefined,
|
|
274
|
+
configValues: ConfigValues | undefined
|
|
275
|
+
): Promise<Result<unknown, Error>> => {
|
|
276
|
+
// Check overrides/extensions first — skip config validation entirely when
|
|
277
|
+
// a service instance is already provided.
|
|
278
|
+
const overrideOrExtension = getOverrideOrExtension(
|
|
279
|
+
ctx,
|
|
280
|
+
overrides,
|
|
281
|
+
declaredService
|
|
282
|
+
);
|
|
283
|
+
if (overrideOrExtension !== undefined) {
|
|
284
|
+
return overrideOrExtension;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Resolve config before consulting the singleton cache so config-aware
|
|
288
|
+
// services use the same canonical context for cache reads and writes.
|
|
289
|
+
const configAwareService = resolveConfigAwareProvidedService(
|
|
290
|
+
ctx,
|
|
291
|
+
declaredService,
|
|
292
|
+
configValues
|
|
293
|
+
);
|
|
294
|
+
if (configAwareService.isErr()) {
|
|
295
|
+
return configAwareService;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// No provided instance — create via factory.
|
|
299
|
+
const resolved = configAwareService.unwrap();
|
|
300
|
+
if (resolved.kind === 'provided') {
|
|
301
|
+
return Result.ok(resolved.value);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return await createServiceInstance(declaredService, resolved.serviceContext);
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
// Full trail service resolution
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
const withResolvedServices = (
|
|
312
|
+
ctx: TrailContext,
|
|
313
|
+
resolvedServices: Record<string, unknown>
|
|
314
|
+
): TrailContext => {
|
|
315
|
+
const extensions = { ...ctx.extensions, ...resolvedServices };
|
|
316
|
+
const resolvedCtx = { ...ctx, extensions } as MutableTrailContext;
|
|
317
|
+
resolvedCtx.service = createServiceLookup(() => resolvedCtx);
|
|
318
|
+
return resolvedCtx;
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Resolve all declared services for a trail.
|
|
323
|
+
*
|
|
324
|
+
* Validates per-service config, checks overrides and caches, and creates
|
|
325
|
+
* new instances as needed. Returns an enriched context with all service
|
|
326
|
+
* instances injected into extensions.
|
|
327
|
+
*/
|
|
328
|
+
export const resolveServices = async (
|
|
329
|
+
trail: AnyTrail,
|
|
330
|
+
ctx: TrailContext,
|
|
331
|
+
overrides?: ServiceOverrideMap,
|
|
332
|
+
configValues?: ConfigValues
|
|
333
|
+
): Promise<Result<TrailContext, Error>> => {
|
|
334
|
+
if (trail.services.length === 0) {
|
|
335
|
+
return Result.ok(ctx);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const resolvedServices: Record<string, unknown> = {};
|
|
339
|
+
|
|
340
|
+
for (const declaredService of trail.services) {
|
|
341
|
+
const resolved = await resolveDeclaredService(
|
|
342
|
+
declaredService,
|
|
343
|
+
ctx,
|
|
344
|
+
overrides,
|
|
345
|
+
configValues
|
|
346
|
+
);
|
|
347
|
+
if (resolved.isErr()) {
|
|
348
|
+
return resolved;
|
|
349
|
+
}
|
|
350
|
+
resolvedServices[declaredService.id] = resolved.unwrap();
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return Result.ok(withResolvedServices(ctx, resolvedServices));
|
|
354
|
+
};
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { NotFoundError } from './errors.js';
|
|
2
|
+
import type { Result } from './result.js';
|
|
3
|
+
import type { ServiceLookup, TrailContext } from './types.js';
|
|
4
|
+
import type { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Stable process-scoped fields available when constructing a service.
|
|
8
|
+
*
|
|
9
|
+
* Services are app-level singletons, so they intentionally do not receive the
|
|
10
|
+
* full per-request TrailContext. When a service declares a `config` schema,
|
|
11
|
+
* the validated config is passed as `svc.config`.
|
|
12
|
+
*/
|
|
13
|
+
export type ServiceContext<C = unknown> = Pick<
|
|
14
|
+
TrailContext,
|
|
15
|
+
'cwd' | 'env' | 'workspaceRoot'
|
|
16
|
+
> & {
|
|
17
|
+
readonly config: C;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Everything needed to describe a service before a factory is introduced.
|
|
22
|
+
*
|
|
23
|
+
* When `config` is a Zod schema, the `create` callback receives
|
|
24
|
+
* `ServiceContext<C>` with the validated config value.
|
|
25
|
+
*/
|
|
26
|
+
export interface ServiceSpec<T, C = unknown> {
|
|
27
|
+
/** Create the service instance from stable process-scoped context. */
|
|
28
|
+
readonly create: (
|
|
29
|
+
svc: ServiceContext<C>
|
|
30
|
+
) => Result<T, Error> | Promise<Result<T, Error>>;
|
|
31
|
+
/** Config schema — when present, config is validated and passed to `create`. */
|
|
32
|
+
readonly config?: z.ZodType<C> | undefined;
|
|
33
|
+
/** Optional cleanup performed when the hosting surface shuts down. */
|
|
34
|
+
readonly dispose?: ((service: T) => void | Promise<void>) | undefined;
|
|
35
|
+
/** Optional operational readiness probe for introspection tooling. */
|
|
36
|
+
readonly health?:
|
|
37
|
+
| ((service: T) => Result<unknown, Error> | Promise<Result<unknown, Error>>)
|
|
38
|
+
| undefined;
|
|
39
|
+
/** Optional test factory used by higher-level helpers. */
|
|
40
|
+
readonly mock?: (() => T | Promise<T>) | undefined;
|
|
41
|
+
/** Human-readable description. */
|
|
42
|
+
readonly description?: string | undefined;
|
|
43
|
+
/** Arbitrary metadata for tooling and filtering. */
|
|
44
|
+
readonly metadata?: Readonly<Record<string, unknown>> | undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A typed service definition.
|
|
49
|
+
*
|
|
50
|
+
* TRL-73 introduces the structural contract only. The `service()` factory and
|
|
51
|
+
* runtime helpers land in follow-up branches.
|
|
52
|
+
*/
|
|
53
|
+
export interface Service<T> extends ServiceSpec<T> {
|
|
54
|
+
readonly kind: 'service';
|
|
55
|
+
readonly id: string;
|
|
56
|
+
/** Read the resolved service instance from a trail context. */
|
|
57
|
+
from(ctx: TrailContext): T;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Existential type for heterogeneous service collections.
|
|
62
|
+
*
|
|
63
|
+
* `Service<T>` includes function parameters in `dispose`/`health`, so `unknown`
|
|
64
|
+
* is too narrow for mixed service arrays. `any` is the correct existential here.
|
|
65
|
+
*/
|
|
66
|
+
// oxlint-disable-next-line no-explicit-any -- existential type for heterogeneous service collections
|
|
67
|
+
export type AnyService = Service<any>;
|
|
68
|
+
|
|
69
|
+
/** Explicit runtime overrides keyed by service ID. */
|
|
70
|
+
export type ServiceOverrideMap = Readonly<Record<string, unknown>>;
|
|
71
|
+
|
|
72
|
+
const getServiceId = <T>(
|
|
73
|
+
serviceOrId: string | Pick<Service<T>, 'id'>
|
|
74
|
+
): string => (typeof serviceOrId === 'string' ? serviceOrId : serviceOrId.id);
|
|
75
|
+
|
|
76
|
+
const getServiceInstance = <T>(
|
|
77
|
+
ctx: Pick<TrailContext, 'extensions'>,
|
|
78
|
+
serviceOrId: string | Pick<Service<T>, 'id'>
|
|
79
|
+
): T => {
|
|
80
|
+
const id = getServiceId(serviceOrId);
|
|
81
|
+
return ctx.extensions?.[id] as T;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const hasServiceInstance = (
|
|
85
|
+
ctx: Pick<TrailContext, 'extensions'>,
|
|
86
|
+
serviceOrId: string | Pick<AnyService, 'id'>
|
|
87
|
+
): boolean => Object.hasOwn(ctx.extensions ?? {}, getServiceId(serviceOrId));
|
|
88
|
+
|
|
89
|
+
/** Create a `ctx.service(...)` accessor bound to a concrete context snapshot. */
|
|
90
|
+
export const createServiceLookup = (
|
|
91
|
+
getContext: () => Pick<TrailContext, 'extensions'>
|
|
92
|
+
): ServiceLookup =>
|
|
93
|
+
((serviceOrId: string | Pick<AnyService, 'id'>) => {
|
|
94
|
+
const id = getServiceId(serviceOrId);
|
|
95
|
+
const ctx = getContext();
|
|
96
|
+
if (!hasServiceInstance(ctx, id)) {
|
|
97
|
+
throw new NotFoundError(`Service "${id}" not found in trail context`);
|
|
98
|
+
}
|
|
99
|
+
return getServiceInstance(ctx, id);
|
|
100
|
+
}) as ServiceLookup;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Create a typed service definition.
|
|
104
|
+
*
|
|
105
|
+
* The service object is inert until a later execution branch resolves concrete
|
|
106
|
+
* instances into TrailContext extensions.
|
|
107
|
+
*/
|
|
108
|
+
export const service = <T>(id: string, spec: ServiceSpec<T>): Service<T> =>
|
|
109
|
+
Object.freeze({
|
|
110
|
+
...spec,
|
|
111
|
+
from(ctx: TrailContext): T {
|
|
112
|
+
const lookup = ctx.service ?? createServiceLookup(() => ctx);
|
|
113
|
+
return lookup(this);
|
|
114
|
+
},
|
|
115
|
+
id,
|
|
116
|
+
kind: 'service' as const,
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
/** Narrow unknown values to service definitions during topo discovery. */
|
|
120
|
+
export const isService = (value: unknown): value is AnyService => {
|
|
121
|
+
if (typeof value !== 'object' || value === null) {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
const v = value as { kind?: unknown; id?: unknown };
|
|
125
|
+
return v.kind === 'service' && typeof v.id === 'string';
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Return the first duplicate service ID in a collection, if any.
|
|
130
|
+
*
|
|
131
|
+
* This supports later topo registration without each caller duplicating the
|
|
132
|
+
* same scan logic.
|
|
133
|
+
*/
|
|
134
|
+
export const findDuplicateServiceId = (
|
|
135
|
+
services: readonly Pick<AnyService, 'id'>[]
|
|
136
|
+
): string | undefined => {
|
|
137
|
+
const seen = new Set<string>();
|
|
138
|
+
for (const candidate of services) {
|
|
139
|
+
if (seen.has(candidate.id)) {
|
|
140
|
+
return candidate.id;
|
|
141
|
+
}
|
|
142
|
+
seen.add(candidate.id);
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
};
|