refactor(api): validate shared product response contracts (CL25)
This commit is contained in:
parent
e2292e4883
commit
366a6054bf
22 changed files with 989 additions and 451 deletions
|
|
@ -72,6 +72,10 @@
|
|||
"./diagnostics": {
|
||||
"types": "./dist/contracts/diagnostics.d.ts",
|
||||
"default": "./dist/contracts/diagnostics.js"
|
||||
},
|
||||
"./product-responses": {
|
||||
"types": "./dist/contracts/product-responses/index.d.ts",
|
||||
"default": "./dist/contracts/product-responses/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
import { z } from 'zod';
|
||||
import { datasetHashSchema } from '../backtest';
|
||||
|
||||
// Read contracts accept existing identifiers and date-only legacy dates. New-input
|
||||
// validation belongs to the command schemas; response parsing never rewrites saved data.
|
||||
const id = z.string().min(1);
|
||||
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
|
||||
const parameters = z.record(z.union([z.string(), z.number().finite(), z.boolean()]));
|
||||
|
||||
export const backtestResponseSchema = z.object({
|
||||
id,
|
||||
name: z.string(),
|
||||
strategy: id,
|
||||
strategyVersionId: id.nullable().optional(),
|
||||
strategyParameters: parameters.nullable().optional(),
|
||||
symbols: z.array(id),
|
||||
startDate: date,
|
||||
endDate: date,
|
||||
initialCapital: z.number().finite(),
|
||||
config: z.record(z.unknown()),
|
||||
createdAt: date,
|
||||
updatedAt: date,
|
||||
archivedAt: date.nullable(),
|
||||
});
|
||||
|
||||
export const runResponseSchema = z.object({
|
||||
id,
|
||||
originalRunId: id.nullable().optional(),
|
||||
backtestId: id,
|
||||
runNumber: z.number().int().positive(),
|
||||
status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled', 'paused']),
|
||||
speedMultiplier: z.number().finite().nullable(),
|
||||
error: z.string().nullable().optional(),
|
||||
startedAt: date.nullable().optional(),
|
||||
completedAt: date.nullable().optional(),
|
||||
pausedAt: date.nullable().optional(),
|
||||
progress: z.number().finite(),
|
||||
cancelRequested: z.boolean().optional(),
|
||||
attemptNumber: z.number().int().nonnegative().optional(),
|
||||
currentDate: date.nullable().optional(),
|
||||
createdAt: date,
|
||||
updatedAt: date,
|
||||
dataset: z
|
||||
.object({
|
||||
requestedHash: datasetHashSchema.nullable(),
|
||||
pinnedHash: datasetHashSchema.nullable(),
|
||||
source: z.enum(['auto', 'questdb', 'eod']).nullable(),
|
||||
state: z.enum(['requested', 'preparing', 'pinned', 'unavailable', 'unknown']),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/** JSON wire values, after Date serialization; financial result contracts stay separate. */
|
||||
export type BacktestResponse = z.infer<typeof backtestResponseSchema>;
|
||||
export type RunResponse = z.infer<typeof runResponseSchema>;
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** Browser-safe read contracts shared by HTTP producers and consumers. */
|
||||
export * from './backtests';
|
||||
export * from './strategies';
|
||||
export * from './research';
|
||||
106
apps/stock/config/src/contracts/product-responses/research.ts
Normal file
106
apps/stock/config/src/contracts/product-responses/research.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import { z } from 'zod';
|
||||
import { researchActorSchema, researchFindingSourceSchema } from '../research';
|
||||
|
||||
const id = z.string().min(1);
|
||||
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
|
||||
const ordinal = z.number().int().positive();
|
||||
const authorship = {
|
||||
submittedBy: researchActorSchema,
|
||||
contentOrigin: z.enum(['human', 'ai', 'unknown']),
|
||||
};
|
||||
const record = {
|
||||
id,
|
||||
ownerPrincipal: researchActorSchema,
|
||||
updatedBy: researchActorSchema,
|
||||
archived: z.boolean(),
|
||||
createdAt: date,
|
||||
updatedAt: date,
|
||||
};
|
||||
export const researchProjectResponseSchema = z.object({
|
||||
...record,
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
revision: ordinal,
|
||||
});
|
||||
export const researchHypothesisRevisionResponseSchema = z.object({
|
||||
...authorship,
|
||||
id,
|
||||
hypothesisId: id,
|
||||
ordinal,
|
||||
title: z.string(),
|
||||
proposition: z.string(),
|
||||
validationCriteria: z.string(),
|
||||
validationState: z.literal('unvalidated'),
|
||||
createdAt: date,
|
||||
});
|
||||
export const researchHypothesisResponseSchema = z
|
||||
.object({
|
||||
...record,
|
||||
projectId: id,
|
||||
latestRevision: researchHypothesisRevisionResponseSchema,
|
||||
})
|
||||
.refine(value => value.latestRevision.hypothesisId === value.id, 'Wrong hypothesis revision');
|
||||
export const researchEvidenceResponseSchema = z.object({
|
||||
runId: id,
|
||||
backtestId: id,
|
||||
strategyVersionId: id.nullable().optional(),
|
||||
metricsVersion: z.enum(['canonical-analytics/v1', 'legacy-display/v1']),
|
||||
metricPath: z.string().min(1),
|
||||
value: z.number().finite().nullable(),
|
||||
unit: z.enum(['fraction', 'ratio', 'count', 'currency']),
|
||||
availability: z.enum(['available', 'unavailable']),
|
||||
unavailableReason: z.string().nullable(),
|
||||
resultKind: z.enum(['canonical', 'legacy']),
|
||||
financialEngine: z.enum(['rust', 'native', 'typescript', 'legacy']),
|
||||
datasetHash: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/)
|
||||
.nullable(),
|
||||
limitations: z.array(z.object({ code: z.string(), message: z.string() })),
|
||||
});
|
||||
export const researchArtifactRevisionResponseSchema = z.object({
|
||||
...authorship,
|
||||
id,
|
||||
artifactId: id,
|
||||
ordinal,
|
||||
title: z.string(),
|
||||
body: z.string(),
|
||||
validationState: z.literal('unvalidated'),
|
||||
evidenceState: z.enum(['none', 'referenced']),
|
||||
evidence: z.array(researchEvidenceResponseSchema),
|
||||
// Older retained records do not have a source scope.
|
||||
source: researchFindingSourceSchema.nullable().optional(),
|
||||
createdAt: date,
|
||||
});
|
||||
export const researchArtifactResponseSchema = z
|
||||
.object({
|
||||
...record,
|
||||
projectId: id,
|
||||
hypothesisRevisionId: id.nullable(),
|
||||
kind: z.enum(['note', 'finding']),
|
||||
latestRevision: researchArtifactRevisionResponseSchema,
|
||||
})
|
||||
.refine(value => value.latestRevision.artifactId === value.id, 'Wrong artifact revision');
|
||||
|
||||
export const researchProjectEnvelopeSchema = z.object({ project: researchProjectResponseSchema });
|
||||
export const researchProjectsEnvelopeSchema = z.object({
|
||||
projects: z.array(researchProjectResponseSchema),
|
||||
});
|
||||
export const researchHypothesisEnvelopeSchema = z.object({
|
||||
hypothesis: researchHypothesisResponseSchema,
|
||||
});
|
||||
export const researchHypothesesEnvelopeSchema = z.object({
|
||||
hypotheses: z.array(researchHypothesisResponseSchema),
|
||||
});
|
||||
export const researchHypothesisRevisionsEnvelopeSchema = z.object({
|
||||
revisions: z.array(researchHypothesisRevisionResponseSchema),
|
||||
});
|
||||
export const researchArtifactEnvelopeSchema = z.object({
|
||||
artifact: researchArtifactResponseSchema,
|
||||
});
|
||||
export const researchArtifactsEnvelopeSchema = z.object({
|
||||
artifacts: z.array(researchArtifactResponseSchema),
|
||||
});
|
||||
export const researchArtifactRevisionsEnvelopeSchema = z.object({
|
||||
revisions: z.array(researchArtifactRevisionResponseSchema),
|
||||
});
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
import { z } from 'zod';
|
||||
import { researchActorSchema } from '../research';
|
||||
import { parseStrategyVersionPackage, strategyVersionPackageSchema } from '../strategy';
|
||||
|
||||
const id = z.string().min(1);
|
||||
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
|
||||
export const strategyRecordResponseSchema = z.object({
|
||||
id,
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
ownerPrincipal: researchActorSchema,
|
||||
updatedBy: researchActorSchema,
|
||||
archived: z.boolean(),
|
||||
createdAt: date,
|
||||
updatedAt: date,
|
||||
});
|
||||
|
||||
// A catalog summary deliberately excludes executable content. Reuse the stored
|
||||
// package schema rather than creating a second parameter or provenance format.
|
||||
const packageMetadata = strategyVersionPackageSchema.extend({
|
||||
artifact: strategyVersionPackageSchema.shape.artifact.omit({ content: true }),
|
||||
dependencyLock: strategyVersionPackageSchema.shape.dependencyLock.omit({ content: true }),
|
||||
});
|
||||
export const strategyVersionResponseSchema = z.object({
|
||||
id,
|
||||
strategyId: id,
|
||||
ordinal: z.number().int().positive(),
|
||||
parentVersionId: id.nullable(),
|
||||
createdBy: researchActorSchema,
|
||||
origin: z.enum(['candidate', 'builtin']),
|
||||
createdAt: date,
|
||||
package: packageMetadata,
|
||||
reviewStatus: z.enum(['pending', 'approved', 'revoked']),
|
||||
runnable: z.literal(false),
|
||||
reason: z.string(),
|
||||
});
|
||||
export const strategyReviewResponseSchema = z.object({
|
||||
id,
|
||||
ordinal: z.number().int().positive(),
|
||||
decision: z.enum(['approve', 'revoke']),
|
||||
actor: z.literal('operator'),
|
||||
reason: z.string(),
|
||||
createdAt: date,
|
||||
});
|
||||
export const strategyParameterValidationResponseSchema = z.object({
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
runnable: z.literal(false),
|
||||
reason: z.string(),
|
||||
});
|
||||
export const strategyArtifactResponseSchema = z.object({
|
||||
package: z.unknown().transform((value, ctx) => {
|
||||
try {
|
||||
return parseStrategyVersionPackage(value);
|
||||
} catch {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid retained strategy package' });
|
||||
return z.NEVER;
|
||||
}
|
||||
}),
|
||||
});
|
||||
export const strategyResponseSchema = z.object({ strategy: strategyRecordResponseSchema });
|
||||
export const strategiesResponseSchema = z.object({
|
||||
strategies: z.array(strategyRecordResponseSchema),
|
||||
});
|
||||
export const strategyVersionsResponseSchema = z.object({
|
||||
versions: z.array(strategyVersionResponseSchema),
|
||||
});
|
||||
export const strategyVersionDetailResponseSchema = z.object({
|
||||
version: strategyVersionResponseSchema,
|
||||
reviews: z.array(strategyReviewResponseSchema),
|
||||
});
|
||||
export const strategyReviewReceiptSchema = z.object({ version: strategyVersionResponseSchema });
|
||||
export const strategyCloneResponseSchema = z.object({
|
||||
strategy: strategyRecordResponseSchema,
|
||||
version: strategyVersionResponseSchema,
|
||||
});
|
||||
|
|
@ -101,6 +101,12 @@ const packageSchema = z
|
|||
})
|
||||
.strict();
|
||||
|
||||
// Response contracts reuse the retained package shape without evaluating executable bytes.
|
||||
export {
|
||||
parameterSchema as strategyParameterSchema,
|
||||
packageSchema as strategyVersionPackageSchema,
|
||||
};
|
||||
|
||||
const period = (minimum: number): StrategyParameterProperty => ({
|
||||
type: 'integer',
|
||||
minimum,
|
||||
|
|
|
|||
|
|
@ -83,7 +83,7 @@ export class BacktestService {
|
|||
runId: run?.id,
|
||||
status: run?.status ?? 'pending',
|
||||
updatedAt: run?.updatedAt ?? backtest.updatedAt,
|
||||
error: run?.error,
|
||||
error: run?.error ?? undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { BacktestDefinitionInput } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestResponse, RunResponse } from '@stock-bot/stock-config/product-responses';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
ResearchActor,
|
||||
|
|
@ -28,38 +29,30 @@ export interface BacktestRequest {
|
|||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
}
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
archivedAt: string | null;
|
||||
/** The HTTP serializer converts these database Dates to the shared JSON wire shape. */
|
||||
export interface Backtest
|
||||
extends Omit<BacktestResponse, 'startDate' | 'endDate' | 'createdAt' | 'updatedAt'> {
|
||||
strategyVersionId: string | null;
|
||||
strategyParameters: Record<string, StrategyParameterValue> | null;
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
export interface Run
|
||||
extends Omit<
|
||||
RunResponse,
|
||||
'startedAt' | 'completedAt' | 'pausedAt' | 'currentDate' | 'createdAt' | 'updatedAt'
|
||||
> {
|
||||
originalRunId: string | null;
|
||||
dataset: BacktestRunDatasetSelection;
|
||||
id: string;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
pausedAt?: Date;
|
||||
progress: number;
|
||||
startedAt?: Date | null;
|
||||
completedAt?: Date | null;
|
||||
pausedAt?: Date | null;
|
||||
cancelRequested: boolean;
|
||||
attemptNumber: number;
|
||||
currentDate?: Date;
|
||||
currentDate?: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -175,11 +175,11 @@ export function RunControls({ run, onPause, onResume, onCancel, onSpeedChange }:
|
|||
<span className="text-text-secondary">Duration:</span>
|
||||
<span className="ml-2 text-text-primary font-medium">{formatDuration()}</span>
|
||||
</div>
|
||||
{run.currentSimulationDate && (
|
||||
{run.currentDate && (
|
||||
<div className="col-span-2">
|
||||
<span className="text-text-secondary">Current Date:</span>
|
||||
<span className="ml-2 text-text-primary font-medium">
|
||||
{formatDate(run.currentSimulationDate)}
|
||||
{formatDate(run.currentDate)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -18,50 +18,25 @@ import type {
|
|||
CanonicalStoredSourcePreparation,
|
||||
ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
backtestResponseSchema,
|
||||
runResponseSchema,
|
||||
type BacktestResponse as Backtest,
|
||||
type RunResponse as Run,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
HistoricalDatasetCatalogEntry,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
archivedAt: string | null;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
id: string;
|
||||
originalRunId?: string | null;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
pausedAt?: string;
|
||||
progress: number;
|
||||
cancelRequested?: boolean;
|
||||
attemptNumber?: number;
|
||||
currentSimulationDate?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
dataset?: BacktestRunDatasetSelection;
|
||||
}
|
||||
export type {
|
||||
BacktestResponse as Backtest,
|
||||
RunResponse as Run,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
|
||||
export interface CreateBacktestRequest {
|
||||
name: string;
|
||||
|
|
@ -112,6 +87,28 @@ export class ReproductionSubmissionError extends Error {
|
|||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
function productRequest<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, parse, {
|
||||
create: message => new Error(message),
|
||||
invalid: () =>
|
||||
new Error(
|
||||
'The backtest response could not be verified. Check saved runs before submitting again.'
|
||||
),
|
||||
lostMessage: 'The backtest response was lost. Check saved runs before submitting again.',
|
||||
failureLabel: 'Backtest request failed',
|
||||
});
|
||||
}
|
||||
const jsonRequest = (method: string, body: unknown): RequestInit => ({
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const acknowledgement = z.object({ message: z.string() });
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const nullableText = (value: unknown) => value === null || typeof value === 'string';
|
||||
|
|
@ -456,45 +453,33 @@ export const backtestApiV2 = {
|
|||
};
|
||||
},
|
||||
async reproduceRun(originalRunId: string, submissionKey: string): Promise<Run> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
|
||||
body: '{}',
|
||||
return requestJson(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
|
||||
body: '{}',
|
||||
},
|
||||
202,
|
||||
body => {
|
||||
const run = runResponseSchema.parse(body);
|
||||
if (run.id === originalRunId || run.originalRunId !== originalRunId) {
|
||||
throw new Error('Wrong original run identity');
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
|
||||
null
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = await requestError(response, 'Could not reproduce original run');
|
||||
throw new ReproductionSubmissionError(error.message, response.status);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (
|
||||
response.status !== 202 ||
|
||||
!isRecord(body) ||
|
||||
typeof body.id !== 'string' ||
|
||||
!body.id ||
|
||||
body.id === originalRunId ||
|
||||
typeof body.backtestId !== 'string' ||
|
||||
body.originalRunId !== originalRunId ||
|
||||
!['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes(
|
||||
String(body.status)
|
||||
)
|
||||
) {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The accepted reproduction response could not be verified. Retry with this same submission key.',
|
||||
null
|
||||
);
|
||||
}
|
||||
return body as unknown as Run;
|
||||
return run;
|
||||
},
|
||||
{
|
||||
create: (message, status) => new ReproductionSubmissionError(message, status),
|
||||
invalid: () =>
|
||||
new ReproductionSubmissionError(
|
||||
'The accepted reproduction response could not be verified. Retry with this same submission key.',
|
||||
null
|
||||
),
|
||||
lostMessage:
|
||||
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
|
||||
failureLabel: 'Could not reproduce original run',
|
||||
}
|
||||
);
|
||||
},
|
||||
async reproductionComparison(
|
||||
id: string,
|
||||
|
|
@ -636,130 +621,95 @@ export const backtestApiV2 = {
|
|||
}
|
||||
return (await response.json()).dataset;
|
||||
},
|
||||
// Backtest operations
|
||||
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
// Web saves are deliberately separate from durable run submission.
|
||||
body: JSON.stringify({ ...request, autoStart: false }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to create backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
// Templates are saved separately from durable run submission.
|
||||
createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
|
||||
return productRequest(
|
||||
'backtests',
|
||||
jsonRequest('POST', { ...request, autoStart: false }),
|
||||
201,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async getBacktest(id: string): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get backtest: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
getBacktest(id: string): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
{},
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async listBacktests(
|
||||
listBacktests(
|
||||
limit = 50,
|
||||
offset = 0,
|
||||
includeArchived = false,
|
||||
signal?: AbortSignal
|
||||
): Promise<Backtest[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
|
||||
{ signal }
|
||||
return productRequest(
|
||||
`backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
|
||||
{ signal },
|
||||
200,
|
||||
backtestResponseSchema.array().parse
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to list backtests');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
jsonRequest('PUT', updates),
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
deleteBacktest(id: string): Promise<void> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}`,
|
||||
{ method: 'DELETE' },
|
||||
204,
|
||||
z.undefined().parse
|
||||
);
|
||||
},
|
||||
setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(id)}/archive`,
|
||||
jsonRequest('POST', { archived }),
|
||||
200,
|
||||
backtestResponseSchema.parse
|
||||
);
|
||||
},
|
||||
createRun(backtestId: string, request?: CreateRunRequest, submissionKey?: string): Promise<Run> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(backtestId)}/runs`,
|
||||
{
|
||||
...jsonRequest('POST', request || {}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
|
||||
},
|
||||
},
|
||||
body: JSON.stringify(updates),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to update backtest');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
202,
|
||||
body => {
|
||||
const run = runResponseSchema.parse(body);
|
||||
if (run.backtestId !== backtestId) {
|
||||
throw new Error('Wrong backtest identity');
|
||||
}
|
||||
return run;
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async deleteBacktest(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to delete backtest');
|
||||
}
|
||||
listRuns(backtestId: string): Promise<Run[]> {
|
||||
return productRequest(
|
||||
`backtests/${encodeURIComponent(backtestId)}/runs`,
|
||||
{},
|
||||
200,
|
||||
runResponseSchema.array().parse
|
||||
);
|
||||
},
|
||||
|
||||
async setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ archived }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to change archive status');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
|
||||
// Run operations
|
||||
async createRun(
|
||||
backtestId: string,
|
||||
request?: CreateRunRequest,
|
||||
submissionKey?: string
|
||||
): Promise<Run> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
|
||||
},
|
||||
body: JSON.stringify(request || {}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to create run');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async listRuns(backtestId: string): Promise<Run[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to list runs: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
async getRun(id: string, signal?: AbortSignal): Promise<Run> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get run: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
getRun(id: string, signal?: AbortSignal): Promise<Run> {
|
||||
return productRequest(
|
||||
`runs/${encodeURIComponent(id)}`,
|
||||
{ signal },
|
||||
200,
|
||||
runResponseSchema.parse
|
||||
);
|
||||
},
|
||||
|
||||
async getRunResults(runId: string, signal?: AbortSignal): Promise<ResearchRunResult> {
|
||||
|
|
@ -777,48 +727,36 @@ export const backtestApiV2 = {
|
|||
},
|
||||
|
||||
async pauseRun(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to pause run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/pause`,
|
||||
{ method: 'POST' },
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to resume run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/resume`,
|
||||
{ method: 'POST' },
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async cancelRun(id: string, signal?: AbortSignal): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
|
||||
method: 'POST',
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to cancel run: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/cancel`,
|
||||
{ method: 'POST', signal },
|
||||
202,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ speedMultiplier }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to update run speed: ${response.statusText}`);
|
||||
}
|
||||
await productRequest(
|
||||
`runs/${encodeURIComponent(id)}/speed`,
|
||||
jsonRequest('PUT', { speedMultiplier }),
|
||||
200,
|
||||
acknowledgement.parse
|
||||
);
|
||||
},
|
||||
|
||||
// Note: WebSocket connections are handled by the useWebSocket hook
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
import type { z } from 'zod';
|
||||
import { researchFindingSourceSchema } from '@stock-bot/stock-config/research';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
researchArtifactEnvelopeSchema,
|
||||
researchArtifactRevisionsEnvelopeSchema,
|
||||
researchArtifactsEnvelopeSchema,
|
||||
researchHypothesesEnvelopeSchema,
|
||||
researchHypothesisEnvelopeSchema,
|
||||
researchHypothesisRevisionsEnvelopeSchema,
|
||||
researchProjectEnvelopeSchema,
|
||||
researchProjectsEnvelopeSchema,
|
||||
strategiesResponseSchema,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
import type {
|
||||
createResearchArtifactSchema,
|
||||
createResearchHypothesisSchema,
|
||||
|
|
@ -8,15 +18,8 @@ import type {
|
|||
reviseResearchHypothesisSchema,
|
||||
updateResearchProjectSchema,
|
||||
} from '@stock-bot/stock-config/research';
|
||||
import type {
|
||||
ResearchArtifact,
|
||||
ResearchArtifactRevision,
|
||||
ResearchHypothesis,
|
||||
ResearchHypothesisRevision,
|
||||
ResearchProject,
|
||||
StrategyRecord,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export type ProjectInput = z.input<typeof createResearchProjectSchema>;
|
||||
export type ProjectUpdate = z.input<typeof updateResearchProjectSchema>;
|
||||
|
|
@ -37,86 +40,23 @@ export class ResearchApiError extends Error {
|
|||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
type ResponseField =
|
||||
| 'project'
|
||||
| 'projects'
|
||||
| 'strategies'
|
||||
| 'hypothesis'
|
||||
| 'hypotheses'
|
||||
| 'artifact'
|
||||
| 'artifacts'
|
||||
| 'revisions';
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const identified = (value: unknown): value is Record<string, unknown> =>
|
||||
record(value) && typeof value.id === 'string' && value.id.length > 0;
|
||||
function validSource(value: Record<string, unknown>): boolean {
|
||||
if (value.source === undefined || value.source === null) {
|
||||
return true;
|
||||
}
|
||||
const parsed = researchFindingSourceSchema.safeParse(value.source);
|
||||
if (!parsed.success) {
|
||||
return false;
|
||||
}
|
||||
value.source = parsed.data;
|
||||
return true;
|
||||
}
|
||||
function validEnvelope(body: unknown, field: ResponseField): boolean {
|
||||
if (!record(body)) {
|
||||
return false;
|
||||
}
|
||||
const validItem = (item: unknown): boolean => {
|
||||
if (!identified(item)) {
|
||||
return false;
|
||||
}
|
||||
if (field === 'project' || field === 'projects') {
|
||||
return typeof item.title === 'string' && Number.isInteger(item.revision);
|
||||
}
|
||||
if (['hypothesis', 'hypotheses', 'artifact', 'artifacts'].includes(field)) {
|
||||
return (
|
||||
typeof item.projectId === 'string' &&
|
||||
identified(item.latestRevision) &&
|
||||
validSource(item.latestRevision)
|
||||
);
|
||||
}
|
||||
return validSource(item);
|
||||
};
|
||||
const value = body[field];
|
||||
return ['project', 'hypothesis', 'artifact'].includes(field)
|
||||
? validItem(value)
|
||||
: Array.isArray(value) && value.every(validItem);
|
||||
}
|
||||
async function request<T>(
|
||||
function request<S extends z.ZodTypeAny>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
field: ResponseField | null
|
||||
): Promise<T> {
|
||||
let response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init?.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new ResearchApiError(
|
||||
schema: S,
|
||||
status = 200
|
||||
): Promise<z.output<S>> {
|
||||
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, body => schema.parse(body), {
|
||||
create: (message, code) => new ResearchApiError(message, code),
|
||||
invalid: () =>
|
||||
new ResearchApiError(
|
||||
'The research response could not be read. Check saved records before submitting again.',
|
||||
null
|
||||
),
|
||||
lostMessage:
|
||||
'The research request response was lost. Check saved records before submitting again.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body = response.status === 204 ? undefined : await response.json().catch(() => undefined);
|
||||
if (!response.ok) {
|
||||
throw new ResearchApiError(
|
||||
typeof body?.error === 'string' ? body.error : `Research request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
if (field === null ? response.status !== 204 : !validEnvelope(body, field)) {
|
||||
throw new ResearchApiError(
|
||||
'The research response could not be read. Check saved records before submitting again.',
|
||||
null
|
||||
);
|
||||
}
|
||||
return body as T;
|
||||
failureLabel: 'Research request failed',
|
||||
});
|
||||
}
|
||||
const id = encodeURIComponent;
|
||||
const json = (method: string, body: unknown): RequestInit => ({
|
||||
|
|
@ -126,119 +66,113 @@ const json = (method: string, body: unknown): RequestInit => ({
|
|||
});
|
||||
export const researchApi = {
|
||||
listProjects: (includeArchived = false, signal?: AbortSignal) =>
|
||||
request<{ projects: ResearchProject[] }>(
|
||||
request(
|
||||
`research-projects?includeArchived=${includeArchived}`,
|
||||
{ signal },
|
||||
'projects'
|
||||
researchProjectsEnvelopeSchema
|
||||
),
|
||||
createProject: (body: ProjectInput) =>
|
||||
request<{ project: ResearchProject }>('research-projects', json('POST', body), 'project'),
|
||||
request('research-projects', json('POST', body), researchProjectEnvelopeSchema, 201),
|
||||
getProject: (projectId: string, signal?: AbortSignal) =>
|
||||
request<{ project: ResearchProject }>(
|
||||
`research-projects/${id(projectId)}`,
|
||||
{ signal },
|
||||
'project'
|
||||
),
|
||||
request(`research-projects/${id(projectId)}`, { signal }, researchProjectEnvelopeSchema),
|
||||
updateProject: (projectId: string, body: ProjectUpdate) =>
|
||||
request<{ project: ResearchProject }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}`,
|
||||
json('PATCH', body),
|
||||
'project'
|
||||
researchProjectEnvelopeSchema
|
||||
),
|
||||
listStrategies: (projectId: string, signal?: AbortSignal) =>
|
||||
request<{ strategies: StrategyRecord[] }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/strategies`,
|
||||
{
|
||||
signal,
|
||||
},
|
||||
'strategies'
|
||||
strategiesResponseSchema
|
||||
),
|
||||
linkStrategy: (projectId: string, strategyId: string) =>
|
||||
request<void>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
},
|
||||
null
|
||||
z.undefined(),
|
||||
204
|
||||
),
|
||||
unlinkStrategy: (projectId: string, strategyId: string) =>
|
||||
request<void>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
},
|
||||
null
|
||||
z.undefined(),
|
||||
204
|
||||
),
|
||||
listHypotheses: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
|
||||
request<{ hypotheses: ResearchHypothesis[] }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/hypotheses?includeArchived=${includeArchived}`,
|
||||
{ signal },
|
||||
'hypotheses'
|
||||
researchHypothesesEnvelopeSchema
|
||||
),
|
||||
createHypothesis: (projectId: string, body: HypothesisInput) =>
|
||||
request<{ hypothesis: ResearchHypothesis }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/hypotheses`,
|
||||
json('POST', body),
|
||||
'hypothesis'
|
||||
researchHypothesisEnvelopeSchema,
|
||||
201
|
||||
),
|
||||
getHypothesis: (hypothesisId: string, signal?: AbortSignal) =>
|
||||
request<{ hypothesis: ResearchHypothesis }>(
|
||||
`hypotheses/${id(hypothesisId)}`,
|
||||
{ signal },
|
||||
'hypothesis'
|
||||
),
|
||||
request(`hypotheses/${id(hypothesisId)}`, { signal }, researchHypothesisEnvelopeSchema),
|
||||
hypothesisRevisions: (hypothesisId: string, signal?: AbortSignal) =>
|
||||
request<{ revisions: ResearchHypothesisRevision[] }>(
|
||||
request(
|
||||
`hypotheses/${id(hypothesisId)}/revisions`,
|
||||
{ signal },
|
||||
'revisions'
|
||||
researchHypothesisRevisionsEnvelopeSchema
|
||||
),
|
||||
reviseHypothesis: (hypothesisId: string, body: HypothesisRevisionInput) =>
|
||||
request<{ hypothesis: ResearchHypothesis }>(
|
||||
request(
|
||||
`hypotheses/${id(hypothesisId)}/revisions`,
|
||||
json('POST', body),
|
||||
'hypothesis'
|
||||
researchHypothesisEnvelopeSchema,
|
||||
201
|
||||
),
|
||||
archiveHypothesis: (hypothesisId: string, archived: boolean) =>
|
||||
request<{ hypothesis: ResearchHypothesis }>(
|
||||
request(
|
||||
`hypotheses/${id(hypothesisId)}`,
|
||||
json('PATCH', { archived }),
|
||||
'hypothesis'
|
||||
researchHypothesisEnvelopeSchema
|
||||
),
|
||||
listArtifacts: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
|
||||
request<{ artifacts: ResearchArtifact[] }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/analysis-artifacts?includeArchived=${includeArchived}`,
|
||||
{ signal },
|
||||
'artifacts'
|
||||
researchArtifactsEnvelopeSchema
|
||||
),
|
||||
createArtifact: (projectId: string, body: ArtifactInput) =>
|
||||
request<{ artifact: ResearchArtifact }>(
|
||||
request(
|
||||
`research-projects/${id(projectId)}/analysis-artifacts`,
|
||||
json('POST', body),
|
||||
'artifact'
|
||||
researchArtifactEnvelopeSchema,
|
||||
201
|
||||
),
|
||||
getArtifact: (artifactId: string, signal?: AbortSignal) =>
|
||||
request<{ artifact: ResearchArtifact }>(
|
||||
`analysis-artifacts/${id(artifactId)}`,
|
||||
{ signal },
|
||||
'artifact'
|
||||
),
|
||||
request(`analysis-artifacts/${id(artifactId)}`, { signal }, researchArtifactEnvelopeSchema),
|
||||
artifactRevisions: (artifactId: string, signal?: AbortSignal) =>
|
||||
request<{ revisions: ResearchArtifactRevision[] }>(
|
||||
request(
|
||||
`analysis-artifacts/${id(artifactId)}/revisions`,
|
||||
{ signal },
|
||||
'revisions'
|
||||
researchArtifactRevisionsEnvelopeSchema
|
||||
),
|
||||
reviseArtifact: (artifactId: string, body: ArtifactRevisionInput) =>
|
||||
request<{ artifact: ResearchArtifact }>(
|
||||
request(
|
||||
`analysis-artifacts/${id(artifactId)}/revisions`,
|
||||
json('POST', body),
|
||||
'artifact'
|
||||
researchArtifactEnvelopeSchema,
|
||||
201
|
||||
),
|
||||
archiveArtifact: (artifactId: string, archived: boolean) =>
|
||||
request<{ artifact: ResearchArtifact }>(
|
||||
request(
|
||||
`analysis-artifacts/${id(artifactId)}`,
|
||||
json('PATCH', { archived }),
|
||||
'artifact'
|
||||
researchArtifactEnvelopeSchema
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,23 +1,34 @@
|
|||
import type {
|
||||
ParameterValidationResult,
|
||||
StrategyParameterValue,
|
||||
StrategyRecord,
|
||||
StrategyReviewEvent,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import type { z } from 'zod';
|
||||
import {
|
||||
strategiesResponseSchema,
|
||||
strategyArtifactResponseSchema,
|
||||
strategyCloneResponseSchema,
|
||||
strategyParameterValidationResponseSchema,
|
||||
strategyResponseSchema,
|
||||
strategyReviewReceiptSchema,
|
||||
strategyVersionDetailResponseSchema,
|
||||
strategyVersionsResponseSchema,
|
||||
} from '@stock-bot/stock-config/product-responses';
|
||||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export type Parameters = Record<string, StrategyParameterValue>;
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
typeof body?.error === 'string' ? body.error : `Strategy request failed (${response.status})`
|
||||
);
|
||||
}
|
||||
return body as T;
|
||||
function request<S extends z.ZodTypeAny>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
schema: S,
|
||||
status = 200
|
||||
): Promise<z.output<S>> {
|
||||
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, body => schema.parse(body), {
|
||||
create: message => new Error(message),
|
||||
invalid: () =>
|
||||
new Error(
|
||||
'The strategy response could not be verified. Check saved records before submitting again.'
|
||||
),
|
||||
lostMessage: 'The strategy response was lost. Check saved records before submitting again.',
|
||||
failureLabel: 'Strategy request failed',
|
||||
});
|
||||
}
|
||||
const json = (method: string, body: unknown, key?: string): RequestInit => ({
|
||||
method,
|
||||
|
|
@ -26,40 +37,41 @@ const json = (method: string, body: unknown, key?: string): RequestInit => ({
|
|||
});
|
||||
const id = encodeURIComponent;
|
||||
export const strategyApi = {
|
||||
list: (signal?: AbortSignal) =>
|
||||
request<{ strategies: StrategyRecord[] }>('strategies', { signal }),
|
||||
list: (signal?: AbortSignal) => request('strategies', { signal }, strategiesResponseSchema),
|
||||
get: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, { signal }),
|
||||
request(`strategies/${id(strategyId)}`, { signal }, strategyResponseSchema),
|
||||
create: (body: { name: string; description: string }) =>
|
||||
request<{ strategy: StrategyRecord }>('strategies', json('POST', body)),
|
||||
request('strategies', json('POST', body), strategyResponseSchema, 201),
|
||||
update: (strategyId: string, body: { name?: string; description?: string; archived?: boolean }) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, json('PATCH', body)),
|
||||
request(`strategies/${id(strategyId)}`, json('PATCH', body), strategyResponseSchema),
|
||||
versions: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ versions: StrategyVersionSummary[] }>(`strategies/${id(strategyId)}/versions`, {
|
||||
signal,
|
||||
}),
|
||||
request(`strategies/${id(strategyId)}/versions`, { signal }, strategyVersionsResponseSchema),
|
||||
version: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ version: StrategyVersionSummary; reviews: StrategyReviewEvent[] }>(
|
||||
`strategy-versions/${id(versionId)}`,
|
||||
{ signal }
|
||||
),
|
||||
request(`strategy-versions/${id(versionId)}`, { signal }, strategyVersionDetailResponseSchema),
|
||||
artifact: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ package: StrategyVersionPackage }>(`strategy-versions/${id(versionId)}/artifact`, {
|
||||
signal,
|
||||
}),
|
||||
request(
|
||||
`strategy-versions/${id(versionId)}/artifact`,
|
||||
{ signal },
|
||||
strategyArtifactResponseSchema
|
||||
),
|
||||
validate: (versionId: string, parameters: Parameters) =>
|
||||
request<ParameterValidationResult>(
|
||||
request(
|
||||
`strategy-versions/${id(versionId)}/validate`,
|
||||
json('POST', { parameters })
|
||||
json('POST', { parameters }),
|
||||
strategyParameterValidationResponseSchema
|
||||
),
|
||||
review: (versionId: string, body: { decision: 'approve'; reason: string }) =>
|
||||
request<{ version: StrategyVersionSummary }>(
|
||||
request(
|
||||
`strategy-versions/${id(versionId)}/reviews`,
|
||||
json('POST', body)
|
||||
json('POST', body),
|
||||
strategyReviewReceiptSchema,
|
||||
201
|
||||
),
|
||||
clone: (versionId: string, body: { name: string; description: string }, key: string) =>
|
||||
request<{ strategy: StrategyRecord; version: StrategyVersionSummary }>(
|
||||
request(
|
||||
`strategy-versions/${id(versionId)}/clone`,
|
||||
json('POST', body, key)
|
||||
json('POST', body, key),
|
||||
strategyCloneResponseSchema,
|
||||
201
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ export async function requestJson<T>(
|
|||
}
|
||||
throw errors.create(errors.lostMessage, null);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
const body: unknown =
|
||||
response.status === 204 ? undefined : await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const message =
|
||||
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue