@haakco/custd-sdk 0.0.0-stage → 3.71.1
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/README.md +958 -2
- package/dist/admin-accounting-evidence.d.ts +48 -0
- package/dist/admin-accounting-evidence.js +24 -0
- package/dist/admin-app-releases.d.ts +116 -0
- package/dist/admin-app-releases.js +8 -0
- package/dist/admin-apps.d.ts +120 -0
- package/dist/admin-apps.js +47 -0
- package/dist/admin-auth-project-domain.d.ts +125 -0
- package/dist/admin-auth-project-domain.js +37 -0
- package/dist/admin-auth-projects.d.ts +989 -0
- package/dist/admin-auth-projects.js +527 -0
- package/dist/admin-campaign-email.d.ts +120 -0
- package/dist/admin-campaign-email.js +64 -0
- package/dist/admin-client-setup.d.ts +122 -0
- package/dist/admin-client-setup.js +408 -0
- package/dist/admin-data-labels.d.ts +124 -0
- package/dist/admin-data-labels.js +51 -0
- package/dist/admin-data-scopes.d.ts +93 -0
- package/dist/admin-data-scopes.js +154 -0
- package/dist/admin-email-relay.d.ts +66 -0
- package/dist/admin-email-relay.js +25 -0
- package/dist/admin-environment-policy.d.ts +32 -0
- package/dist/admin-environment-policy.js +26 -0
- package/dist/admin-error-issues.d.ts +91 -0
- package/dist/admin-error-issues.js +52 -0
- package/dist/admin-event-types.d.ts +57 -0
- package/dist/admin-event-types.js +28 -0
- package/dist/admin-impersonation.d.ts +48 -0
- package/dist/admin-impersonation.js +27 -0
- package/dist/admin-ingest-claims.d.ts +35 -0
- package/dist/admin-ingest-claims.js +26 -0
- package/dist/admin-managed-audit.d.ts +13 -0
- package/dist/admin-managed-audit.js +13 -0
- package/dist/admin-measurement-projects.d.ts +166 -0
- package/dist/admin-measurement-projects.js +120 -0
- package/dist/admin-notification-destinations.d.ts +31 -0
- package/dist/admin-notification-destinations.js +19 -0
- package/dist/admin-notification-webhooks.d.ts +64 -0
- package/dist/admin-notification-webhooks.js +42 -0
- package/dist/admin-oauth-client-admissions.d.ts +65 -0
- package/dist/admin-oauth-client-admissions.js +46 -0
- package/dist/admin-offboarding.d.ts +123 -0
- package/dist/admin-offboarding.js +129 -0
- package/dist/admin-predictions.d.ts +266 -0
- package/dist/admin-predictions.js +93 -0
- package/dist/admin-privacy-erasures.d.ts +74 -0
- package/dist/admin-privacy-erasures.js +73 -0
- package/dist/admin-retention.d.ts +99 -0
- package/dist/admin-retention.js +60 -0
- package/dist/admin-rls.d.ts +94 -0
- package/dist/admin-rls.js +33 -0
- package/dist/admin-sdk-usage.d.ts +41 -0
- package/dist/admin-sdk-usage.js +23 -0
- package/dist/admin-site-ai.d.ts +72 -0
- package/dist/admin-site-ai.js +1 -0
- package/dist/admin-site-analytics.d.ts +52 -0
- package/dist/admin-site-analytics.js +14 -0
- package/dist/admin-site-audit-pages.d.ts +76 -0
- package/dist/admin-site-audit-pages.js +27 -0
- package/dist/admin-site-campaign-links.d.ts +40 -0
- package/dist/admin-site-campaign-links.js +9 -0
- package/dist/admin-site-domains.d.ts +733 -0
- package/dist/admin-site-domains.js +768 -0
- package/dist/admin-site-export.d.ts +76 -0
- package/dist/admin-site-export.js +15 -0
- package/dist/admin-site-insights-tasks.d.ts +44 -0
- package/dist/admin-site-insights-tasks.js +28 -0
- package/dist/admin-site-insights.d.ts +527 -0
- package/dist/admin-site-insights.js +61 -0
- package/dist/admin-site-links.d.ts +87 -0
- package/dist/admin-site-links.js +16 -0
- package/dist/admin-site-monitors.d.ts +110 -0
- package/dist/admin-site-monitors.js +25 -0
- package/dist/admin-site-next-actions.d.ts +93 -0
- package/dist/admin-site-next-actions.js +36 -0
- package/dist/admin-site-page-queries.d.ts +63 -0
- package/dist/admin-site-page-queries.js +20 -0
- package/dist/admin-site-rankings.d.ts +98 -0
- package/dist/admin-site-rankings.js +46 -0
- package/dist/admin-site-regional-trends.d.ts +30 -0
- package/dist/admin-site-regional-trends.js +1 -0
- package/dist/admin-site-saved-reports.d.ts +45 -0
- package/dist/admin-site-saved-reports.js +13 -0
- package/dist/admin-site-search-pool.d.ts +77 -0
- package/dist/admin-site-search-pool.js +41 -0
- package/dist/admin-site-search-value.d.ts +97 -0
- package/dist/admin-site-search-value.js +29 -0
- package/dist/admin-site-status-page.d.ts +57 -0
- package/dist/admin-site-status-page.js +10 -0
- package/dist/admin-site-traffic.d.ts +145 -0
- package/dist/admin-site-traffic.js +32 -0
- package/dist/admin-site-web-data.d.ts +258 -0
- package/dist/admin-site-web-data.js +60 -0
- package/dist/admin-subject-exports.d.ts +79 -0
- package/dist/admin-subject-exports.js +44 -0
- package/dist/admin-support-access.d.ts +32 -0
- package/dist/admin-support-access.js +21 -0
- package/dist/admin-system.d.ts +283 -0
- package/dist/admin-system.js +65 -0
- package/dist/admin-tenant-storage.d.ts +35 -0
- package/dist/admin-tenant-storage.js +24 -0
- package/dist/admin-timeplans.d.ts +512 -0
- package/dist/admin-timeplans.js +200 -0
- package/dist/admin-uncertainty-models.d.ts +42 -0
- package/dist/admin-uncertainty-models.js +53 -0
- package/dist/admin-usage.d.ts +124 -0
- package/dist/admin-usage.js +169 -0
- package/dist/admin-users.d.ts +124 -0
- package/dist/admin-users.js +82 -0
- package/dist/admin-workflow-timings.d.ts +367 -0
- package/dist/admin-workflow-timings.js +117 -0
- package/dist/analytics-events.d.ts +167 -0
- package/dist/analytics-events.js +197 -0
- package/dist/analytics-reads.d.ts +81 -0
- package/dist/analytics-reads.js +5 -0
- package/dist/app-account.d.ts +84 -0
- package/dist/app-account.js +177 -0
- package/dist/app-alerts.d.ts +120 -0
- package/dist/app-alerts.js +44 -0
- package/dist/app-items.d.ts +786 -0
- package/dist/app-items.js +524 -0
- package/dist/app-live.d.ts +84 -0
- package/dist/app-live.js +228 -0
- package/dist/app-meetings.d.ts +95 -0
- package/dist/app-meetings.js +26 -0
- package/dist/app-models.d.ts +271 -0
- package/dist/app-models.js +83 -0
- package/dist/app-push.d.ts +64 -0
- package/dist/app-push.js +178 -0
- package/dist/backend-lifecycle.d.ts +85 -0
- package/dist/backend-lifecycle.js +212 -0
- package/dist/browser-manifest.json +7 -0
- package/dist/browser-script-BWnwDjAC.js +711 -0
- package/dist/browser-script.d.ts +1 -0
- package/dist/browser-script.js +5 -0
- package/dist/browser-sign-in.d.ts +153 -0
- package/dist/browser-sign-in.js +410 -0
- package/dist/browser-tracker.d.ts +142 -0
- package/dist/browser-tracker.js +775 -0
- package/dist/browser-web-vitals.d.ts +22 -0
- package/dist/browser-web-vitals.js +116 -0
- package/dist/browser.d.ts +10 -0
- package/dist/browser.js +10 -0
- package/dist/download-stream.d.ts +16 -0
- package/dist/download-stream.js +55 -0
- package/dist/error-capture.d.ts +62 -0
- package/dist/error-capture.js +168 -0
- package/dist/hosted-app.d.ts +115 -0
- package/dist/hosted-app.js +275 -0
- package/dist/index.d.ts +2324 -0
- package/dist/index.js +2226 -0
- package/dist/ingest-operations.d.ts +483 -0
- package/dist/ingest-operations.js +154 -0
- package/dist/measurement.d.ts +164 -0
- package/dist/measurement.js +104 -0
- package/dist/mobile-adapter.d.ts +25 -0
- package/dist/mobile-adapter.js +57 -0
- package/dist/mobile-context.d.ts +32 -0
- package/dist/mobile-context.js +156 -0
- package/dist/mobile-queue.d.ts +22 -0
- package/dist/mobile-queue.js +73 -0
- package/dist/oauth.d.ts +1 -0
- package/dist/oauth.js +8 -0
- package/dist/parsers.d.ts +149 -0
- package/dist/parsers.js +115 -0
- package/dist/public-reads.d.ts +79 -0
- package/dist/public-reads.js +57 -0
- package/dist/reporting-catalogue.d.ts +264 -0
- package/dist/reporting-catalogue.js +5 -0
- package/dist/reporting-state.d.ts +46 -0
- package/dist/reporting-state.js +76 -0
- package/dist/response-lists.d.ts +16 -0
- package/dist/response-lists.generated.d.ts +7 -0
- package/dist/response-lists.generated.js +1927 -0
- package/dist/response-lists.js +70 -0
- package/dist/response-validation.d.ts +30 -0
- package/dist/response-validation.js +94 -0
- package/dist/runtime-readiness.d.ts +30 -0
- package/dist/runtime-readiness.js +150 -0
- package/dist/schema-registry.d.ts +45 -0
- package/dist/schema-registry.js +9 -0
- package/dist/secure-url.d.ts +4 -0
- package/dist/secure-url.js +23 -0
- package/dist/site-ai-owner.d.ts +34 -0
- package/dist/site-ai-owner.js +99 -0
- package/dist/site-monitor-reports.d.ts +15 -0
- package/dist/site-monitor-reports.js +87 -0
- package/dist/testing/fake-custd.d.ts +150 -0
- package/dist/testing/fake-custd.js +842 -0
- package/dist/testing/fake-results.d.ts +30 -0
- package/dist/testing/fake-results.js +293 -0
- package/dist/testing.d.ts +2 -0
- package/dist/testing.js +3 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +10 -0
- package/package.json +57 -4
|
@@ -0,0 +1,842 @@
|
|
|
1
|
+
// An in-memory Custd for app tests: the hosted app discovery file, the /api/v1/app/ item, link,
|
|
2
|
+
// measurement, estimate, forecast, model, alert and meeting routes, and a PKCE sign-in. It answers
|
|
3
|
+
// at the wire level (`handle`, for a browser route interceptor) and as a `fetch` (for the SDK's own
|
|
4
|
+
// clients), records every request, and builds every answer from the SDK's DTOs, so a contract
|
|
5
|
+
// change fails the typecheck here first. Results are deterministic and deliberately simple.
|
|
6
|
+
import { APP_ALERT_CHANNELS, APP_ALERT_DELIVERY_OUTCOMES, APP_ALERT_DESTINATION_KINDS, APP_ALERT_ERROR_CODES, APP_ALERT_RULE_TYPES, } from "../app-alerts.js";
|
|
7
|
+
import { APP_ITEM_ERROR_CODES, APP_ITEM_KINDS, APP_ITEM_OWNERSHIPS, APP_ITEM_SITE_KEY_HEADER, APP_ITEM_USER_TOKEN_HEADER, APP_LINK_ROLES, AppItemsClient, } from "../app-items.js";
|
|
8
|
+
import { APP_MODEL_ERROR_CODES, } from "../app-models.js";
|
|
9
|
+
import { HOSTED_APP_CAPABILITIES, HOSTED_APP_DISCOVERY_PATH, } from "../hosted-app.js";
|
|
10
|
+
import { advanceFakeMeeting, endFakeMeeting, FakeCustdProblem, fakeEstimateList, fakeForecastRun, fakeForecastStory, fakeMeeting, fakeModelResults, fakeSensitivity, fromEnd, startFakeMeeting, } from "./fake-results.js";
|
|
11
|
+
export const FAKE_CUSTD_ORIGIN = "https://app.custd.test";
|
|
12
|
+
export const FAKE_CUSTD_SITE_KEY = "site_pk_fake";
|
|
13
|
+
export const FAKE_CUSTD_API_PATH = "/__custd";
|
|
14
|
+
export const FAKE_CUSTD_AUTH_PATH = "/__auth";
|
|
15
|
+
const DEFAULT_IDLE_SECONDS = 7 * 86400;
|
|
16
|
+
const MAX_ALERT_RULES = 10;
|
|
17
|
+
const MAX_ALERT_WEBHOOKS = 5;
|
|
18
|
+
const SLACK_WEBHOOK_PREFIX = "https://hooks.slack.com/services/";
|
|
19
|
+
const json = (status, body, headers = {}) => ({
|
|
20
|
+
status,
|
|
21
|
+
headers: { "content-type": "application/json", ...headers },
|
|
22
|
+
body: JSON.stringify(body),
|
|
23
|
+
});
|
|
24
|
+
const noContent = () => ({ status: 204, headers: {} });
|
|
25
|
+
function lowercaseHeaders(headers) {
|
|
26
|
+
return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
|
|
27
|
+
}
|
|
28
|
+
function parseJson(body) {
|
|
29
|
+
if (!body)
|
|
30
|
+
return undefined;
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(body);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Sign-in storage held in memory, for tests that have no `sessionStorage`. */
|
|
39
|
+
export function memorySignInStorage() {
|
|
40
|
+
const items = new Map();
|
|
41
|
+
return {
|
|
42
|
+
getItem: (key) => items.get(key) ?? null,
|
|
43
|
+
setItem: (key, value) => {
|
|
44
|
+
items.set(key, value);
|
|
45
|
+
},
|
|
46
|
+
removeItem: (key) => {
|
|
47
|
+
items.delete(key);
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Signs `user` in through the real PKCE flow of `signIn`, against the fake's authorize and token endpoints. */
|
|
52
|
+
export async function signInWithFake(fake, signIn, user) {
|
|
53
|
+
const start = await signIn.startSignIn();
|
|
54
|
+
const completion = await signIn.completeSignIn(fake.authorize(start.authorizationUrl, user));
|
|
55
|
+
return completion.session;
|
|
56
|
+
}
|
|
57
|
+
export class FakeCustd {
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
/** Every request the fake answered, oldest first. */
|
|
60
|
+
this.requests = [];
|
|
61
|
+
/** Every event the hosted app tracked, oldest first. Page views appear as `page-view`. */
|
|
62
|
+
this.trackedEvents = [];
|
|
63
|
+
/** Every error the hosted app captured, oldest first. */
|
|
64
|
+
this.capturedErrors = [];
|
|
65
|
+
this.items = new Map();
|
|
66
|
+
this.links = new Map();
|
|
67
|
+
this.codes = new Map();
|
|
68
|
+
this.sequence = 0;
|
|
69
|
+
this.userCount = 0;
|
|
70
|
+
/** The fake as a `fetch`, for the SDK's clients. */
|
|
71
|
+
this.fetch = async (input, init) => {
|
|
72
|
+
const request = new Request(input, init);
|
|
73
|
+
const headers = {};
|
|
74
|
+
request.headers.forEach((value, name) => {
|
|
75
|
+
headers[name] = value;
|
|
76
|
+
});
|
|
77
|
+
const text = request.method === "GET" || request.method === "HEAD" ? "" : await request.text();
|
|
78
|
+
const answer = this.handle({ method: request.method, url: request.url, headers, body: text === "" ? null : text });
|
|
79
|
+
return new Response(answer.body ?? null, { status: answer.status, headers: answer.headers });
|
|
80
|
+
};
|
|
81
|
+
this.origin = (options.origin ?? FAKE_CUSTD_ORIGIN).replace(/\/+$/, "");
|
|
82
|
+
this.apiBaseUrl = `${this.origin}${FAKE_CUSTD_API_PATH}`;
|
|
83
|
+
this.siteKey = options.siteKey ?? FAKE_CUSTD_SITE_KEY;
|
|
84
|
+
this.clientId = options.clientId ?? "custd-fake-app";
|
|
85
|
+
this.capabilities = options.capabilities ?? Object.values(HOSTED_APP_CAPABILITIES);
|
|
86
|
+
this.now = options.now ?? Date.now;
|
|
87
|
+
this.verifiedEmail = options.signedInUsersHaveVerifiedEmail ?? true;
|
|
88
|
+
this.routes = { ...this.itemRoutes(), ...this.resultRoutes(), ...this.alertRoutes() };
|
|
89
|
+
}
|
|
90
|
+
discovery() {
|
|
91
|
+
return {
|
|
92
|
+
apiBaseUrl: this.apiBaseUrl,
|
|
93
|
+
host: new URL(this.origin).host,
|
|
94
|
+
siteUuid: "00000000-0000-4000-8000-000000000001",
|
|
95
|
+
browserKey: this.siteKey,
|
|
96
|
+
environment: "test",
|
|
97
|
+
capabilities: [...this.capabilities],
|
|
98
|
+
identityMode: "cookieless",
|
|
99
|
+
allowedOrigins: [this.origin],
|
|
100
|
+
pageViewSchemaVersion: "1.0.0",
|
|
101
|
+
signIn: {
|
|
102
|
+
issuer: this.origin,
|
|
103
|
+
authorizationEndpoint: `${this.origin}${FAKE_CUSTD_AUTH_PATH}/authorize`,
|
|
104
|
+
tokenEndpoint: `${this.origin}${FAKE_CUSTD_AUTH_PATH}/token`,
|
|
105
|
+
clientId: this.clientId,
|
|
106
|
+
audience: "custd-fake-app",
|
|
107
|
+
redirectUri: `${this.origin}/auth/callback`,
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** Options for `startHostedApp` (or `CustdHostedAppProvider`) that reach this fake. */
|
|
112
|
+
hostedAppOptions() {
|
|
113
|
+
return {
|
|
114
|
+
discoveryUrl: `${this.origin}${HOSTED_APP_DISCOVERY_PATH}`,
|
|
115
|
+
fetch: this.fetch,
|
|
116
|
+
signInStorage: memorySignInStorage(),
|
|
117
|
+
createTracker: () => this.recordingTracker(),
|
|
118
|
+
startErrorCapture: () => ({ client: this.recordingErrorCapture(), uninstall: () => { } }),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
// The tracker and error capture record what the app hands them and touch no page globals.
|
|
122
|
+
recordingTracker() {
|
|
123
|
+
const record = async (eventTypeSlug, payload) => {
|
|
124
|
+
this.trackedEvents.push(payload === undefined ? { eventTypeSlug } : { eventTypeSlug, payload });
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
track: record,
|
|
128
|
+
trackPageView: () => record("page-view"),
|
|
129
|
+
installSpaTracking: () => { },
|
|
130
|
+
setConsent: () => { },
|
|
131
|
+
flush: async () => { },
|
|
132
|
+
close: () => { },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
recordingErrorCapture() {
|
|
136
|
+
return {
|
|
137
|
+
captureException: async (request) => {
|
|
138
|
+
const exceptionType = request.error instanceof Error ? request.error.name : "Error";
|
|
139
|
+
this.capturedErrors.push({
|
|
140
|
+
exceptionType,
|
|
141
|
+
...(request.mode ? { mode: request.mode } : {}),
|
|
142
|
+
...(request.correlationId ? { correlationId: request.correlationId } : {}),
|
|
143
|
+
});
|
|
144
|
+
return { outcome: "accepted" };
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** A client that reaches this fake; `userToken` is the signed-in user, as the fake names them. */
|
|
149
|
+
appItemsClient(options = {}) {
|
|
150
|
+
return AppItemsClient.fromDiscovery(this.discovery(), { fetch: this.fetch, userToken: () => options.userToken });
|
|
151
|
+
}
|
|
152
|
+
/** Approves a sign-in as `user` (a new user when absent) and returns the redirect back to the app. */
|
|
153
|
+
authorize(authorizationUrl, user) {
|
|
154
|
+
const url = new URL(authorizationUrl);
|
|
155
|
+
const code = this.token();
|
|
156
|
+
this.userCount += 1;
|
|
157
|
+
this.codes.set(code, user ?? `user-${this.userCount}`);
|
|
158
|
+
const back = new URL(url.searchParams.get("redirect_uri") ?? `${this.origin}/auth/callback`);
|
|
159
|
+
back.searchParams.set("code", code);
|
|
160
|
+
back.searchParams.set("state", url.searchParams.get("state") ?? "");
|
|
161
|
+
return back.toString();
|
|
162
|
+
}
|
|
163
|
+
/** Answers one request, as a browser route interceptor hands it over. */
|
|
164
|
+
handle(raw) {
|
|
165
|
+
const url = new URL(raw.url);
|
|
166
|
+
const request = {
|
|
167
|
+
...raw,
|
|
168
|
+
headers: lowercaseHeaders(raw.headers),
|
|
169
|
+
path: url.pathname.startsWith(FAKE_CUSTD_API_PATH)
|
|
170
|
+
? url.pathname.slice(FAKE_CUSTD_API_PATH.length)
|
|
171
|
+
: url.pathname,
|
|
172
|
+
json: parseJson(raw.body),
|
|
173
|
+
};
|
|
174
|
+
this.requests.push(request);
|
|
175
|
+
try {
|
|
176
|
+
return this.dispatch(request, url);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (!(error instanceof FakeCustdProblem))
|
|
180
|
+
throw error;
|
|
181
|
+
return json(error.status, { status: error.status, code: error.code, title: error.code });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
dispatch(request, url) {
|
|
185
|
+
if (url.pathname === HOSTED_APP_DISCOVERY_PATH)
|
|
186
|
+
return json(200, this.discovery());
|
|
187
|
+
if (url.pathname.startsWith(FAKE_CUSTD_AUTH_PATH))
|
|
188
|
+
return this.auth(request, url);
|
|
189
|
+
if (!url.pathname.startsWith(FAKE_CUSTD_API_PATH))
|
|
190
|
+
return json(404, { code: "not_found" });
|
|
191
|
+
if (request.method === "OPTIONS")
|
|
192
|
+
return noContent();
|
|
193
|
+
if (request.headers[APP_ITEM_SITE_KEY_HEADER.toLowerCase()] !== this.siteKey) {
|
|
194
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.keyRefused);
|
|
195
|
+
}
|
|
196
|
+
const user = request.headers[APP_ITEM_USER_TOKEN_HEADER.toLowerCase()] ?? null;
|
|
197
|
+
const context = { request, url, path: request.path, user };
|
|
198
|
+
const route = this.routes[`${request.method} ${request.path}`];
|
|
199
|
+
return route ? route(context) : this.routeWithId(context);
|
|
200
|
+
}
|
|
201
|
+
// ---- Sign-in ----
|
|
202
|
+
auth(request, url) {
|
|
203
|
+
if (url.pathname.endsWith("/authorize"))
|
|
204
|
+
return { status: 302, headers: { location: this.authorize(url.toString()) } };
|
|
205
|
+
const form = new URLSearchParams(request.body ?? "");
|
|
206
|
+
const code = form.get("code") ?? "";
|
|
207
|
+
const user = this.codes.get(code) ?? form.get("refresh_token")?.replace(/^refresh-/, "");
|
|
208
|
+
this.codes.delete(code);
|
|
209
|
+
if (!user)
|
|
210
|
+
return json(400, { error: "invalid_grant" });
|
|
211
|
+
return json(200, {
|
|
212
|
+
access_token: user,
|
|
213
|
+
token_type: "Bearer",
|
|
214
|
+
expires_in: 3600,
|
|
215
|
+
refresh_token: `refresh-${user}`,
|
|
216
|
+
scope: "openid profile offline_access",
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
// ---- Routes ----
|
|
220
|
+
itemRoutes() {
|
|
221
|
+
const base = "/api/v1/app/item";
|
|
222
|
+
return {
|
|
223
|
+
"POST /api/v1/app/items": (c) => json(201, this.create(c.request.json, c.user)),
|
|
224
|
+
"GET /api/v1/app/items": (c) => json(200, { items: this.mine(c.user) }),
|
|
225
|
+
[`GET ${base}`]: (c) => this.itemRead(c),
|
|
226
|
+
[`PATCH ${base}`]: (c) => this.change(c, (item) => this.settings(item, c.request.json)),
|
|
227
|
+
[`POST ${base}/claim`]: (c) => json(200, this.claim(this.caller(c))),
|
|
228
|
+
[`POST ${base}/measurements`]: (c) => this.measure(c, c.request.json.rows),
|
|
229
|
+
[`POST ${base}/measurements/csv`]: (c) => this.measure(c, csvRows(c.request.json.csv)),
|
|
230
|
+
[`POST ${base}/estimates`]: (c) => json(201, this.estimate(c, c.request.json)),
|
|
231
|
+
[`POST ${base}/complete`]: (c) => this.change(c, (item) => this.complete(item, c.request.json.completedAt)),
|
|
232
|
+
[`POST ${base}/cancel`]: (c) => this.change(c, (item) => this.setStatus(item, "canceled")),
|
|
233
|
+
[`POST ${base}/reopen`]: (c) => this.change(c, (item) => this.setStatus(item, "active")),
|
|
234
|
+
[`POST ${base}/entries`]: (c) => json(201, this.addEntry(c, c.request.json)),
|
|
235
|
+
[`POST ${base}/meeting/start`]: (c) => this.change(c, (item) => startFakeMeeting(this.meetingOf(item), this.now())),
|
|
236
|
+
[`POST ${base}/meeting/advance`]: (c) => this.advance(c, c.request.json),
|
|
237
|
+
[`POST ${base}/meeting/end`]: (c) => this.change(c, (item) => endFakeMeeting(this.meetingOf(item), this.now())),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
resultRoutes() {
|
|
241
|
+
return {
|
|
242
|
+
"POST /api/v1/app/forecast/runs": (c) => json(201, this.runForecast(c, c.request.json)),
|
|
243
|
+
"GET /api/v1/app/forecast/latest": (c) => this.latestForecast(c),
|
|
244
|
+
"GET /api/v1/app/forecast/story": (c) => this.story(c),
|
|
245
|
+
"POST /api/v1/app/item/model/versions": (c) => {
|
|
246
|
+
const body = c.request.json;
|
|
247
|
+
return this.change(c, (item) => this.saveVersion(item, body.quantities, body.note ?? ""), 201);
|
|
248
|
+
},
|
|
249
|
+
"POST /api/v1/app/item/model/copy": (c) => json(201, this.copyModel(c, c.request.json)),
|
|
250
|
+
"POST /api/v1/app/models/runs": (c) => json(201, this.runModel(c, c.request.json)),
|
|
251
|
+
"POST /api/v1/app/models/calculate": (c) => json(200, this.calculate(this.caller(c), c.request.json)),
|
|
252
|
+
"GET /api/v1/app/models/latest": (c) => this.latestModelRun(c),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
alertRoutes() {
|
|
256
|
+
const base = "/api/v1/app/item/alerts";
|
|
257
|
+
return {
|
|
258
|
+
[`GET ${base}`]: (c) => json(200, this.alertSettings(this.caller(c))),
|
|
259
|
+
[`GET ${base}/deliveries`]: (c) => json(200, { deliveries: [...this.owned(this.caller(c)).alerts.deliveries].reverse() }),
|
|
260
|
+
[`POST ${base}/rules`]: (c) => json(201, this.addRule(this.owned(this.caller(c)), c.request.json)),
|
|
261
|
+
[`POST ${base}/webhooks`]: (c) => json(201, this.addWebhook(this.owned(this.caller(c)), c.request.json)),
|
|
262
|
+
[`POST ${base}/slack`]: (c) => json(201, this.addSlack(this.owned(this.caller(c)), c.request.json)),
|
|
263
|
+
[`PUT ${base}/subscription`]: (c) => json(200, this.subscribe(this.caller(c))),
|
|
264
|
+
[`DELETE ${base}/subscription`]: (c) => {
|
|
265
|
+
this.owned(this.caller(c)).alerts.subscriptions.delete(c.user ?? "");
|
|
266
|
+
return noContent();
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
routeWithId(context) {
|
|
271
|
+
const run = /^\/api\/v1\/app\/forecast\/runs\/([^/]+)$/.exec(context.path);
|
|
272
|
+
if (run && context.request.method === "GET")
|
|
273
|
+
return this.forecastRun(context, run[1] ?? "");
|
|
274
|
+
const match = /^\/api\/v1\/app\/item\/(entries|links|alerts\/rules|alerts\/webhooks)\/([^/]+)(\/rotate)?$/.exec(context.path);
|
|
275
|
+
if (!match)
|
|
276
|
+
throw new FakeCustdProblem(404, "not_found");
|
|
277
|
+
const [, collection, id = "", rotate] = match;
|
|
278
|
+
const item = this.owned(this.caller(context));
|
|
279
|
+
if (collection === "links" && rotate && context.request.method === "POST")
|
|
280
|
+
return json(200, this.rotate(item, id));
|
|
281
|
+
if (context.request.method !== "DELETE" || rotate)
|
|
282
|
+
throw new FakeCustdProblem(405, "method_not_allowed");
|
|
283
|
+
this.remove(item, collection ?? "", id);
|
|
284
|
+
return noContent();
|
|
285
|
+
}
|
|
286
|
+
remove(item, collection, id) {
|
|
287
|
+
if (collection === "links")
|
|
288
|
+
this.revoke(item, id);
|
|
289
|
+
if (collection === "entries")
|
|
290
|
+
item.entries = item.entries.filter((entry) => entry.entryUuid !== id);
|
|
291
|
+
if (collection === "alerts/rules")
|
|
292
|
+
item.alerts.rules = item.alerts.rules.filter((rule) => rule.ruleUuid !== id);
|
|
293
|
+
if (collection === "alerts/webhooks") {
|
|
294
|
+
item.alerts.webhooks = item.alerts.webhooks.filter((hook) => hook.webhookUuid !== id);
|
|
295
|
+
}
|
|
296
|
+
this.touch(item);
|
|
297
|
+
}
|
|
298
|
+
conditional(context, etag, body) {
|
|
299
|
+
if (context.request.headers["if-none-match"] === etag)
|
|
300
|
+
return { status: 304, headers: { etag } };
|
|
301
|
+
return json(200, body(), { etag });
|
|
302
|
+
}
|
|
303
|
+
// ---- Callers ----
|
|
304
|
+
caller(context) {
|
|
305
|
+
const bearer = context.request.headers.authorization?.replace(/^Bearer /, "");
|
|
306
|
+
const itemParam = context.url.searchParams.get("item");
|
|
307
|
+
if (bearer)
|
|
308
|
+
return this.linkCaller(bearer, itemParam, context.user);
|
|
309
|
+
if (!context.user)
|
|
310
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.signInRequired);
|
|
311
|
+
const item = itemParam ? this.items.get(itemParam) : undefined;
|
|
312
|
+
if (item && item.ownerUser === context.user)
|
|
313
|
+
return { item, role: APP_LINK_ROLES.owner, user: context.user };
|
|
314
|
+
const viaOwnedCollection = [...this.items.values()].some((candidate) => candidate.ownerUser === context.user && candidate.entries.some((entry) => entry.itemUuid === itemParam));
|
|
315
|
+
if (item && viaOwnedCollection)
|
|
316
|
+
return { item, role: APP_LINK_ROLES.share, user: context.user };
|
|
317
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.notFound);
|
|
318
|
+
}
|
|
319
|
+
linkCaller(token, itemParam, user) {
|
|
320
|
+
const link = this.links.get(token);
|
|
321
|
+
const item = link ? this.items.get(link.itemUuid) : undefined;
|
|
322
|
+
if (!link || !item)
|
|
323
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.linkRefused);
|
|
324
|
+
if (!itemParam || itemParam === item.uuid)
|
|
325
|
+
return { item, role: link.role, user };
|
|
326
|
+
const entry = item.entries.find((candidate) => candidate.itemUuid === itemParam);
|
|
327
|
+
const target = entry ? this.items.get(entry.itemUuid) : undefined;
|
|
328
|
+
if (!target)
|
|
329
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.notFound);
|
|
330
|
+
return { item: target, role: APP_LINK_ROLES.share, user };
|
|
331
|
+
}
|
|
332
|
+
owned(caller) {
|
|
333
|
+
if (caller.role !== APP_LINK_ROLES.owner)
|
|
334
|
+
throw new FakeCustdProblem(403, APP_ITEM_ERROR_CODES.readOnlyLink);
|
|
335
|
+
return caller.item;
|
|
336
|
+
}
|
|
337
|
+
touch(item) {
|
|
338
|
+
item.version += 1;
|
|
339
|
+
item.changeSequence = this.nextSequence();
|
|
340
|
+
item.updatedAt = new Date(this.now()).toISOString();
|
|
341
|
+
}
|
|
342
|
+
change(context, apply, status = 200) {
|
|
343
|
+
const caller = this.caller(context);
|
|
344
|
+
apply(this.owned(caller));
|
|
345
|
+
this.touch(caller.item);
|
|
346
|
+
return json(status, this.read(caller));
|
|
347
|
+
}
|
|
348
|
+
// ---- Ids ----
|
|
349
|
+
nextSequence() {
|
|
350
|
+
this.sequence += 1;
|
|
351
|
+
return this.sequence;
|
|
352
|
+
}
|
|
353
|
+
uuid() {
|
|
354
|
+
return `00000000-0000-4000-8000-${this.nextSequence().toString(16).padStart(12, "0")}`;
|
|
355
|
+
}
|
|
356
|
+
/** 43 base64url characters, the shape of a real link token. */
|
|
357
|
+
token() {
|
|
358
|
+
return `fake${this.nextSequence()}`.padStart(43, "A");
|
|
359
|
+
}
|
|
360
|
+
nowIso() {
|
|
361
|
+
return new Date(this.now()).toISOString();
|
|
362
|
+
}
|
|
363
|
+
// ---- Items ----
|
|
364
|
+
create(request, user) {
|
|
365
|
+
const item = this.newItem(request.kind, request.idleExpirySeconds, user);
|
|
366
|
+
if (request.kind === APP_ITEM_KINDS.uncertaintyModel) {
|
|
367
|
+
const create = request.uncertaintyModel;
|
|
368
|
+
item.model = this.newModel(create.name, create.description ?? "");
|
|
369
|
+
if (create.quantities)
|
|
370
|
+
this.saveVersion(item, create.quantities, create.note ?? "");
|
|
371
|
+
}
|
|
372
|
+
if (request.kind === APP_ITEM_KINDS.measurementProject)
|
|
373
|
+
item.project = this.newProject(item, request);
|
|
374
|
+
if (request.kind === APP_ITEM_KINDS.meeting)
|
|
375
|
+
item.meeting = fakeMeeting(request.meeting, () => this.uuid());
|
|
376
|
+
return this.issueLinks(item);
|
|
377
|
+
}
|
|
378
|
+
newItem(kind, idleExpirySeconds, user) {
|
|
379
|
+
const item = {
|
|
380
|
+
uuid: this.uuid(),
|
|
381
|
+
kind,
|
|
382
|
+
version: 1,
|
|
383
|
+
changeSequence: this.nextSequence(),
|
|
384
|
+
idleExpirySeconds: idleExpirySeconds ?? DEFAULT_IDLE_SECONDS,
|
|
385
|
+
updatedAt: this.nowIso(),
|
|
386
|
+
ownerUser: user,
|
|
387
|
+
observations: [],
|
|
388
|
+
estimates: [],
|
|
389
|
+
entries: [],
|
|
390
|
+
runs: [],
|
|
391
|
+
modelRuns: [],
|
|
392
|
+
alerts: { rules: [], webhooks: [], subscriptions: new Map(), deliveries: [] },
|
|
393
|
+
};
|
|
394
|
+
this.items.set(item.uuid, item);
|
|
395
|
+
return item;
|
|
396
|
+
}
|
|
397
|
+
issueLinks(item) {
|
|
398
|
+
const ownerToken = this.issue(item.uuid, APP_LINK_ROLES.owner);
|
|
399
|
+
const shareToken = this.issue(item.uuid, APP_LINK_ROLES.share);
|
|
400
|
+
return { item: this.read({ item, role: APP_LINK_ROLES.owner, user: item.ownerUser }), ownerToken, shareToken };
|
|
401
|
+
}
|
|
402
|
+
newModel(name, description) {
|
|
403
|
+
const now = this.nowIso();
|
|
404
|
+
return { modelUuid: this.uuid(), name, description, latestVersion: 0, createdAt: now, updatedAt: now };
|
|
405
|
+
}
|
|
406
|
+
newProject(item, request) {
|
|
407
|
+
const create = request.measurementProject;
|
|
408
|
+
const now = this.nowIso();
|
|
409
|
+
return {
|
|
410
|
+
projectUuid: this.uuid(),
|
|
411
|
+
projectCode: `app-${item.uuid.slice(-8)}`,
|
|
412
|
+
kind: create.kind,
|
|
413
|
+
status: "active",
|
|
414
|
+
name: create.name,
|
|
415
|
+
description: create.description ?? "",
|
|
416
|
+
series: create.series.map((series) => ({ ...series, seriesUuid: this.uuid() })),
|
|
417
|
+
target: { ...create.target, targetUuid: this.uuid() },
|
|
418
|
+
delivery: { definitionOfDone: "" },
|
|
419
|
+
run: { similar: true },
|
|
420
|
+
createdAt: now,
|
|
421
|
+
updatedAt: now,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
issue(itemUuid, role) {
|
|
425
|
+
const token = this.token();
|
|
426
|
+
this.links.set(token, { token, itemUuid, role, linkUuid: this.uuid(), createdAt: this.nowIso() });
|
|
427
|
+
return token;
|
|
428
|
+
}
|
|
429
|
+
rotate(item, linkUuid) {
|
|
430
|
+
const old = this.linkOf(item, linkUuid);
|
|
431
|
+
this.links.delete(old.token);
|
|
432
|
+
const token = this.issue(item.uuid, old.role);
|
|
433
|
+
const { linkUuid: newUuid, role, createdAt } = this.links.get(token) ?? old;
|
|
434
|
+
this.touch(item);
|
|
435
|
+
return { link: { linkUuid: newUuid, role, createdAt }, token };
|
|
436
|
+
}
|
|
437
|
+
revoke(item, linkUuid) {
|
|
438
|
+
this.links.delete(this.linkOf(item, linkUuid).token);
|
|
439
|
+
}
|
|
440
|
+
linkOf(item, linkUuid) {
|
|
441
|
+
const link = [...this.links.values()].find((c) => c.itemUuid === item.uuid && c.linkUuid === linkUuid);
|
|
442
|
+
if (!link)
|
|
443
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.notFound);
|
|
444
|
+
return link;
|
|
445
|
+
}
|
|
446
|
+
itemRead(context) {
|
|
447
|
+
const caller = this.caller(context);
|
|
448
|
+
return this.conditional(context, `"${caller.item.version}"`, () => this.read(caller));
|
|
449
|
+
}
|
|
450
|
+
read(caller) {
|
|
451
|
+
const { item } = caller;
|
|
452
|
+
const read = {
|
|
453
|
+
item: {
|
|
454
|
+
itemUuid: item.uuid,
|
|
455
|
+
kind: item.kind,
|
|
456
|
+
role: caller.role,
|
|
457
|
+
ownership: this.ownership(item, caller.user),
|
|
458
|
+
version: item.version,
|
|
459
|
+
idleExpirySeconds: item.idleExpirySeconds,
|
|
460
|
+
updatedAt: item.updatedAt,
|
|
461
|
+
expiresAt: new Date(Date.parse(item.updatedAt) + item.idleExpirySeconds * 1000).toISOString(),
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
if (caller.role === APP_LINK_ROLES.owner)
|
|
465
|
+
read.links = this.linksOf(item);
|
|
466
|
+
if (item.project) {
|
|
467
|
+
read.measurementProject = structuredClone(item.project);
|
|
468
|
+
read.estimates = fakeEstimateList(item.estimates, item.project.delivery.targetDate, this.now());
|
|
469
|
+
}
|
|
470
|
+
if (item.kind === APP_ITEM_KINDS.linkCollection)
|
|
471
|
+
read.linkCollection = { entries: [...item.entries] };
|
|
472
|
+
if (item.model)
|
|
473
|
+
read.uncertaintyModel = structuredClone(item.model);
|
|
474
|
+
if (item.meeting)
|
|
475
|
+
read.meeting = structuredClone(item.meeting);
|
|
476
|
+
return read;
|
|
477
|
+
}
|
|
478
|
+
ownership(item, user) {
|
|
479
|
+
if (item.ownerUser === null)
|
|
480
|
+
return APP_ITEM_OWNERSHIPS.unowned;
|
|
481
|
+
return item.ownerUser === user ? APP_ITEM_OWNERSHIPS.yours : APP_ITEM_OWNERSHIPS.other;
|
|
482
|
+
}
|
|
483
|
+
linksOf(item) {
|
|
484
|
+
return [...this.links.values()]
|
|
485
|
+
.filter((link) => link.itemUuid === item.uuid)
|
|
486
|
+
.map(({ linkUuid, role, createdAt }) => ({ linkUuid, role, createdAt }));
|
|
487
|
+
}
|
|
488
|
+
mine(user) {
|
|
489
|
+
if (!user)
|
|
490
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.signInRequired);
|
|
491
|
+
return [...this.items.values()]
|
|
492
|
+
.filter((item) => item.ownerUser === user)
|
|
493
|
+
.sort((a, b) => b.changeSequence - a.changeSequence)
|
|
494
|
+
.map((item) => ({
|
|
495
|
+
...this.read({ item, role: APP_LINK_ROLES.owner, user }).item,
|
|
496
|
+
name: item.project?.name ?? item.meeting?.name ?? item.model?.name ?? "",
|
|
497
|
+
status: item.project?.status ?? item.meeting?.status ?? "",
|
|
498
|
+
}));
|
|
499
|
+
}
|
|
500
|
+
claim(caller) {
|
|
501
|
+
const item = this.owned(caller);
|
|
502
|
+
if (!caller.user)
|
|
503
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.signInRequired);
|
|
504
|
+
if (item.ownerUser !== null && item.ownerUser !== caller.user) {
|
|
505
|
+
throw new FakeCustdProblem(409, APP_ITEM_ERROR_CODES.claimed);
|
|
506
|
+
}
|
|
507
|
+
item.ownerUser = caller.user;
|
|
508
|
+
this.touch(item);
|
|
509
|
+
return this.read(caller);
|
|
510
|
+
}
|
|
511
|
+
projectOf(item) {
|
|
512
|
+
if (!item.project)
|
|
513
|
+
throw new FakeCustdProblem(409, APP_ITEM_ERROR_CODES.wrongKind);
|
|
514
|
+
return item.project;
|
|
515
|
+
}
|
|
516
|
+
meetingOf(item) {
|
|
517
|
+
if (!item.meeting)
|
|
518
|
+
throw new FakeCustdProblem(409, APP_ITEM_ERROR_CODES.wrongKind);
|
|
519
|
+
return item.meeting;
|
|
520
|
+
}
|
|
521
|
+
settings(item, request) {
|
|
522
|
+
if (request.idleExpirySeconds !== undefined)
|
|
523
|
+
item.idleExpirySeconds = request.idleExpirySeconds;
|
|
524
|
+
const change = request.project;
|
|
525
|
+
if (!change)
|
|
526
|
+
return;
|
|
527
|
+
const project = this.projectOf(item);
|
|
528
|
+
if (change.name !== undefined)
|
|
529
|
+
project.name = change.name;
|
|
530
|
+
if (change.description !== undefined)
|
|
531
|
+
project.description = change.description;
|
|
532
|
+
if (change.status !== undefined)
|
|
533
|
+
project.status = change.status;
|
|
534
|
+
if (change.definitionOfDone !== undefined)
|
|
535
|
+
project.delivery.definitionOfDone = change.definitionOfDone;
|
|
536
|
+
if (change.deliveryTargetDate !== undefined)
|
|
537
|
+
project.delivery.targetDate = change.deliveryTargetDate;
|
|
538
|
+
if (change.forecastMethod !== undefined)
|
|
539
|
+
project.run.forecastMethod = change.forecastMethod;
|
|
540
|
+
if (change.runSimilar !== undefined)
|
|
541
|
+
project.run.similar = change.runSimilar;
|
|
542
|
+
}
|
|
543
|
+
complete(item, completedAt) {
|
|
544
|
+
const project = this.projectOf(item);
|
|
545
|
+
project.status = "completed";
|
|
546
|
+
project.delivery.completedAt = completedAt;
|
|
547
|
+
if (project.target)
|
|
548
|
+
project.target.state = "completed";
|
|
549
|
+
}
|
|
550
|
+
setStatus(item, status) {
|
|
551
|
+
const project = this.projectOf(item);
|
|
552
|
+
project.status = status;
|
|
553
|
+
if (status === "active" && project.target)
|
|
554
|
+
project.target.state = "active";
|
|
555
|
+
}
|
|
556
|
+
measure(context, rows) {
|
|
557
|
+
const item = this.owned(this.caller(context));
|
|
558
|
+
const project = this.projectOf(item);
|
|
559
|
+
item.observations.push(...rows.map((row) => ({ observedAt: row.observedAt, value: row.value })));
|
|
560
|
+
const response = {
|
|
561
|
+
importId: this.uuid(),
|
|
562
|
+
accepted: rows.length,
|
|
563
|
+
rejected: 0,
|
|
564
|
+
results: rows.map((_, rowIndex) => ({ rowIndex, success: true, observationUuid: this.uuid() })),
|
|
565
|
+
};
|
|
566
|
+
const target = project.target;
|
|
567
|
+
if (target?.state === "active" && rows.some((row) => row.value >= target.targetValue)) {
|
|
568
|
+
target.state = "completed";
|
|
569
|
+
target.completedAt = this.nowIso();
|
|
570
|
+
response.completedTargetUuid = target.targetUuid;
|
|
571
|
+
}
|
|
572
|
+
this.touch(item);
|
|
573
|
+
this.evaluateAlerts(item);
|
|
574
|
+
return json(200, response);
|
|
575
|
+
}
|
|
576
|
+
estimate(context, request) {
|
|
577
|
+
const item = this.owned(this.caller(context));
|
|
578
|
+
this.projectOf(item);
|
|
579
|
+
const estimate = {
|
|
580
|
+
estimateUuid: this.uuid(),
|
|
581
|
+
estimatedAt: request.estimatedAt ?? this.nowIso(),
|
|
582
|
+
lowDate: request.lowDate,
|
|
583
|
+
highDate: request.highDate,
|
|
584
|
+
note: request.note ?? "",
|
|
585
|
+
};
|
|
586
|
+
item.estimates.push(estimate);
|
|
587
|
+
this.touch(item);
|
|
588
|
+
this.evaluateAlerts(item);
|
|
589
|
+
return estimate;
|
|
590
|
+
}
|
|
591
|
+
addEntry(context, request) {
|
|
592
|
+
const item = this.owned(this.caller(context));
|
|
593
|
+
if (item.kind !== APP_ITEM_KINDS.linkCollection)
|
|
594
|
+
throw new FakeCustdProblem(409, APP_ITEM_ERROR_CODES.wrongKind);
|
|
595
|
+
const link = this.links.get(request.token);
|
|
596
|
+
const target = link ? this.items.get(link.itemUuid) : undefined;
|
|
597
|
+
if (!target)
|
|
598
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.notFound);
|
|
599
|
+
if (target.kind === APP_ITEM_KINDS.linkCollection) {
|
|
600
|
+
throw new FakeCustdProblem(422, APP_ITEM_ERROR_CODES.notCollectable);
|
|
601
|
+
}
|
|
602
|
+
const entry = {
|
|
603
|
+
entryUuid: this.uuid(),
|
|
604
|
+
itemUuid: target.uuid,
|
|
605
|
+
kind: target.kind,
|
|
606
|
+
position: item.entries.length,
|
|
607
|
+
createdAt: this.nowIso(),
|
|
608
|
+
};
|
|
609
|
+
item.entries.push(entry);
|
|
610
|
+
this.touch(item);
|
|
611
|
+
return entry;
|
|
612
|
+
}
|
|
613
|
+
advance(context, request) {
|
|
614
|
+
const caller = this.caller(context);
|
|
615
|
+
const item = this.owned(caller);
|
|
616
|
+
if (advanceFakeMeeting(this.meetingOf(item), request.blockUuid, this.now()))
|
|
617
|
+
this.touch(item);
|
|
618
|
+
return json(200, this.read(caller));
|
|
619
|
+
}
|
|
620
|
+
// ---- Forecasts ----
|
|
621
|
+
runForecast(context, request) {
|
|
622
|
+
const item = this.owned(this.caller(context));
|
|
623
|
+
const meta = { runUuid: this.uuid(), now: this.now() };
|
|
624
|
+
const run = fakeForecastRun(this.projectOf(item), item.observations, request ?? {}, meta);
|
|
625
|
+
item.runs.push(run);
|
|
626
|
+
this.evaluateAlerts(item);
|
|
627
|
+
return run;
|
|
628
|
+
}
|
|
629
|
+
latestForecast(context) {
|
|
630
|
+
const { item } = this.caller(context);
|
|
631
|
+
const run = fromEnd(item.runs, 1);
|
|
632
|
+
if (!run)
|
|
633
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.forecastMissing);
|
|
634
|
+
return this.conditional(context, `"run-${item.runs.length}"`, () => run);
|
|
635
|
+
}
|
|
636
|
+
forecastRun(context, runUuid) {
|
|
637
|
+
const run = this.caller(context).item.runs.find((candidate) => candidate.forecastRunUuid === runUuid);
|
|
638
|
+
if (!run)
|
|
639
|
+
throw new FakeCustdProblem(404, APP_ITEM_ERROR_CODES.forecastMissing);
|
|
640
|
+
return this.conditional(context, `"${run.forecastRunUuid}"`, () => run);
|
|
641
|
+
}
|
|
642
|
+
story(context) {
|
|
643
|
+
const { item } = this.caller(context);
|
|
644
|
+
const project = this.projectOf(item);
|
|
645
|
+
return this.conditional(context, `"${item.version}"`, () => fakeForecastStory(project, item.observations, this.now()));
|
|
646
|
+
}
|
|
647
|
+
// ---- Models ----
|
|
648
|
+
saveVersion(item, quantities, note) {
|
|
649
|
+
const model = item.model;
|
|
650
|
+
if (!model)
|
|
651
|
+
throw new FakeCustdProblem(409, APP_ITEM_ERROR_CODES.wrongKind);
|
|
652
|
+
model.latestVersion += 1;
|
|
653
|
+
model.updatedAt = this.nowIso();
|
|
654
|
+
model.version = {
|
|
655
|
+
versionUuid: this.uuid(),
|
|
656
|
+
versionNumber: model.latestVersion,
|
|
657
|
+
note,
|
|
658
|
+
quantities: structuredClone(quantities),
|
|
659
|
+
createdAt: this.nowIso(),
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
modelVersion(item) {
|
|
663
|
+
const model = item.model;
|
|
664
|
+
if (!model?.version)
|
|
665
|
+
throw new FakeCustdProblem(409, APP_MODEL_ERROR_CODES.runInvalid);
|
|
666
|
+
return { model, quantities: model.version.quantities };
|
|
667
|
+
}
|
|
668
|
+
copyModel(context, request) {
|
|
669
|
+
const source = this.owned(this.caller(context));
|
|
670
|
+
const { model, quantities } = this.modelVersion(source);
|
|
671
|
+
const copy = this.newItem(APP_ITEM_KINDS.uncertaintyModel, source.idleExpirySeconds, context.user);
|
|
672
|
+
copy.model = this.newModel(request.name ?? `Copy of ${model.name}`, model.description);
|
|
673
|
+
this.saveVersion(copy, quantities, "");
|
|
674
|
+
return this.issueLinks(copy);
|
|
675
|
+
}
|
|
676
|
+
runModel(context, request) {
|
|
677
|
+
const item = this.owned(this.caller(context));
|
|
678
|
+
const { model, quantities } = this.modelVersion(item);
|
|
679
|
+
const output = request.sensitivityOutput ?? request.decision?.output;
|
|
680
|
+
const run = {
|
|
681
|
+
runUuid: this.uuid(),
|
|
682
|
+
modelUuid: model.modelUuid,
|
|
683
|
+
versionNumber: model.latestVersion,
|
|
684
|
+
trigger: "request",
|
|
685
|
+
seed: request.seed,
|
|
686
|
+
sampleCount: request.sampleCount ?? 10000,
|
|
687
|
+
createdAt: this.nowIso(),
|
|
688
|
+
quantities: fakeModelResults(quantities),
|
|
689
|
+
boundInputs: [],
|
|
690
|
+
...(request.decision ? { decision: request.decision } : {}),
|
|
691
|
+
...(output ? { sensitivityOutput: output, sensitivity: fakeSensitivity(quantities, output) } : {}),
|
|
692
|
+
};
|
|
693
|
+
item.modelRuns.push(run);
|
|
694
|
+
this.touch(item);
|
|
695
|
+
return run;
|
|
696
|
+
}
|
|
697
|
+
calculate(caller, request) {
|
|
698
|
+
const { model, quantities } = this.modelVersion(caller.item);
|
|
699
|
+
const overrides = new Map((request.inputs ?? []).map((input) => [input.name, input.input]));
|
|
700
|
+
const changed = quantities.map((quantity) => {
|
|
701
|
+
const input = overrides.get(quantity.name);
|
|
702
|
+
return input && quantity.kind === "input" ? { ...quantity, input } : quantity;
|
|
703
|
+
});
|
|
704
|
+
const outputs = new Set(request.outputs);
|
|
705
|
+
return {
|
|
706
|
+
modelUuid: model.modelUuid,
|
|
707
|
+
versionNumber: model.latestVersion,
|
|
708
|
+
seed: request.seed ?? 1,
|
|
709
|
+
sampleCount: request.sampleCount ?? 10000,
|
|
710
|
+
quantities: fakeModelResults(changed).filter((result) => outputs.has(result.name)),
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
latestModelRun(context) {
|
|
714
|
+
const { item } = this.caller(context);
|
|
715
|
+
const run = fromEnd(item.modelRuns, 1);
|
|
716
|
+
if (!run)
|
|
717
|
+
throw new FakeCustdProblem(404, APP_MODEL_ERROR_CODES.runMissing);
|
|
718
|
+
return this.conditional(context, `"model-run-${item.modelRuns.length}"`, () => run);
|
|
719
|
+
}
|
|
720
|
+
// ---- Alerts ----
|
|
721
|
+
alertSettings(caller) {
|
|
722
|
+
const { alerts } = this.owned(caller);
|
|
723
|
+
const subscription = caller.user ? alerts.subscriptions.get(caller.user) : undefined;
|
|
724
|
+
return {
|
|
725
|
+
rules: [...alerts.rules],
|
|
726
|
+
webhooks: [...alerts.webhooks],
|
|
727
|
+
...(subscription ? { subscription } : {}),
|
|
728
|
+
deliveryAvailable: true,
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
addRule(item, spec) {
|
|
732
|
+
if (item.alerts.rules.length >= MAX_ALERT_RULES)
|
|
733
|
+
throw new FakeCustdProblem(409, APP_ALERT_ERROR_CODES.limit);
|
|
734
|
+
if (!Object.values(APP_ALERT_RULE_TYPES).includes(spec.type)) {
|
|
735
|
+
throw new FakeCustdProblem(400, APP_ALERT_ERROR_CODES.ruleInvalid);
|
|
736
|
+
}
|
|
737
|
+
const rule = {
|
|
738
|
+
...spec,
|
|
739
|
+
ruleUuid: this.uuid(),
|
|
740
|
+
conditionMet: false,
|
|
741
|
+
crossings: 0,
|
|
742
|
+
createdAt: this.nowIso(),
|
|
743
|
+
};
|
|
744
|
+
item.alerts.rules.push(rule);
|
|
745
|
+
return rule;
|
|
746
|
+
}
|
|
747
|
+
addWebhook(item, request) {
|
|
748
|
+
if (item.alerts.webhooks.length >= MAX_ALERT_WEBHOOKS)
|
|
749
|
+
throw new FakeCustdProblem(409, APP_ALERT_ERROR_CODES.limit);
|
|
750
|
+
if (!request.endpoint.startsWith("https://"))
|
|
751
|
+
throw new FakeCustdProblem(400, APP_ITEM_ERROR_CODES.invalid);
|
|
752
|
+
const webhook = {
|
|
753
|
+
webhookUuid: this.uuid(),
|
|
754
|
+
kind: APP_ALERT_DESTINATION_KINDS.webhook,
|
|
755
|
+
endpoint: request.endpoint,
|
|
756
|
+
createdAt: this.nowIso(),
|
|
757
|
+
};
|
|
758
|
+
item.alerts.webhooks.push(webhook);
|
|
759
|
+
return { webhook, signingSecret: `whsec_${this.token()}` };
|
|
760
|
+
}
|
|
761
|
+
// A Slack destination shares the webhook bound and removal; like Custd, only a hint of its URL is kept.
|
|
762
|
+
addSlack(item, request) {
|
|
763
|
+
if (item.alerts.webhooks.length >= MAX_ALERT_WEBHOOKS)
|
|
764
|
+
throw new FakeCustdProblem(409, APP_ALERT_ERROR_CODES.limit);
|
|
765
|
+
if (!request.webhookUrl.startsWith(SLACK_WEBHOOK_PREFIX))
|
|
766
|
+
throw new FakeCustdProblem(400, APP_ITEM_ERROR_CODES.invalid);
|
|
767
|
+
const hint = `${request.webhookUrl.slice("https://".length).split("/").slice(0, 3).join("/")}/…`;
|
|
768
|
+
const slack = {
|
|
769
|
+
webhookUuid: this.uuid(),
|
|
770
|
+
kind: APP_ALERT_DESTINATION_KINDS.slack,
|
|
771
|
+
endpoint: hint,
|
|
772
|
+
createdAt: this.nowIso(),
|
|
773
|
+
};
|
|
774
|
+
item.alerts.webhooks.push(slack);
|
|
775
|
+
return slack;
|
|
776
|
+
}
|
|
777
|
+
subscribe(caller) {
|
|
778
|
+
const item = this.owned(caller);
|
|
779
|
+
if (!caller.user)
|
|
780
|
+
throw new FakeCustdProblem(401, APP_ITEM_ERROR_CODES.signInRequired);
|
|
781
|
+
if (!this.verifiedEmail)
|
|
782
|
+
throw new FakeCustdProblem(422, APP_ALERT_ERROR_CODES.noVerifiedEmail);
|
|
783
|
+
const existing = item.alerts.subscriptions.get(caller.user);
|
|
784
|
+
if (existing)
|
|
785
|
+
return existing;
|
|
786
|
+
const subscription = { subscriptionUuid: this.uuid(), createdAt: this.nowIso() };
|
|
787
|
+
item.alerts.subscriptions.set(caller.user, subscription);
|
|
788
|
+
return subscription;
|
|
789
|
+
}
|
|
790
|
+
conditionMet(item, rule) {
|
|
791
|
+
const target = item.project?.target;
|
|
792
|
+
const counter = fromEnd(item.runs, 1)?.counter;
|
|
793
|
+
if (rule.type === APP_ALERT_RULE_TYPES.targetReached)
|
|
794
|
+
return target?.state === "completed";
|
|
795
|
+
if (rule.type === APP_ALERT_RULE_TYPES.deadlineProbabilityBelow) {
|
|
796
|
+
return counter?.deadlineProbability !== undefined && counter.deadlineProbability < (rule.threshold ?? 0);
|
|
797
|
+
}
|
|
798
|
+
if (rule.type === APP_ALERT_RULE_TYPES.forecastMovedInsideTarget) {
|
|
799
|
+
const upper = counter?.completionInterval?.upper;
|
|
800
|
+
return upper !== undefined && !!target?.targetDate && Date.parse(upper) <= Date.parse(target.targetDate);
|
|
801
|
+
}
|
|
802
|
+
const latest = fromEnd(item.estimates, 1);
|
|
803
|
+
return latest !== undefined && this.now() - Date.parse(latest.estimatedAt) > (rule.staleDays ?? 0) * 86400000;
|
|
804
|
+
}
|
|
805
|
+
evaluateAlerts(item) {
|
|
806
|
+
for (const rule of item.alerts.rules) {
|
|
807
|
+
const met = this.conditionMet(item, rule);
|
|
808
|
+
if (met && !rule.conditionMet) {
|
|
809
|
+
rule.crossings += 1;
|
|
810
|
+
this.deliver(item, rule);
|
|
811
|
+
}
|
|
812
|
+
rule.conditionMet = met;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
deliver(item, rule) {
|
|
816
|
+
const now = this.nowIso();
|
|
817
|
+
const delivery = (channel, webhookUuid) => ({
|
|
818
|
+
deliveryUuid: this.uuid(),
|
|
819
|
+
ruleUuid: rule.ruleUuid,
|
|
820
|
+
ruleType: rule.type,
|
|
821
|
+
crossing: rule.crossings,
|
|
822
|
+
channel,
|
|
823
|
+
...(webhookUuid ? { webhookUuid } : {}),
|
|
824
|
+
outcome: APP_ALERT_DELIVERY_OUTCOMES.sent,
|
|
825
|
+
attempts: 1,
|
|
826
|
+
createdAt: now,
|
|
827
|
+
updatedAt: now,
|
|
828
|
+
});
|
|
829
|
+
for (const hook of item.alerts.webhooks)
|
|
830
|
+
item.alerts.deliveries.push(delivery(APP_ALERT_CHANNELS[hook.kind], hook.webhookUuid));
|
|
831
|
+
for (const _ of item.alerts.subscriptions.values())
|
|
832
|
+
item.alerts.deliveries.push(delivery(APP_ALERT_CHANNELS.email));
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
/** `observedAt,value` lines; a first line that is not a measurement is read as the header. */
|
|
836
|
+
function csvRows(csv) {
|
|
837
|
+
return csv
|
|
838
|
+
.split(/\r?\n/)
|
|
839
|
+
.map((line) => line.split(","))
|
|
840
|
+
.filter(([observedAt, value]) => observedAt && value !== undefined && !Number.isNaN(Number(value)))
|
|
841
|
+
.map(([observedAt = "", value]) => ({ observedAt: observedAt.trim(), value: Number(value) }));
|
|
842
|
+
}
|