@ericminassian/platform-core 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +947 -209
- package/dist/api.js +335 -1
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts +19 -0
- package/dist/auth.js +29 -0
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +8 -2
- package/dist/bindings.js.map +1 -1
- package/dist/cloudfront-function.js +6 -0
- package/dist/cloudfront-function.js.map +1 -1
- package/dist/config.d.ts +11 -1
- package/dist/config.js +7 -0
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +11 -0
- package/dist/constants.js.map +1 -1
- package/dist/manifest.d.ts +203 -90
- package/dist/manifest.js +129 -93
- package/dist/manifest.js.map +1 -1
- package/dist/naming.d.ts +13 -2
- package/dist/naming.js +12 -1
- package/dist/naming.js.map +1 -1
- package/dist/platform-api.d.ts +5337 -0
- package/dist/platform-api.js +343 -0
- package/dist/platform-api.js.map +1 -0
- package/dist/router/decide.d.ts +5 -1
- package/dist/router/decide.js +7 -2
- package/dist/router.d.ts +1 -1
- package/dist/telemetry.d.ts +236 -74
- package/dist/telemetry.js +97 -0
- package/dist/telemetry.js.map +1 -1
- package/package.json +12 -6
- package/src/api.ts +427 -231
- package/src/auth.ts +33 -0
- package/src/bindings.ts +8 -2
- package/src/cloudfront-function.ts +6 -0
- package/src/config.ts +10 -2
- package/src/constants.ts +12 -0
- package/src/manifest.ts +280 -113
- package/src/naming.ts +13 -2
- package/src/platform-api.ts +504 -0
- package/src/router/decide.d.ts +5 -1
- package/src/router/decide.js +7 -2
- package/src/router.ts +1 -1
- package/src/telemetry.ts +107 -85
- package/platform.schema.json +0 -213
package/src/auth.ts
CHANGED
|
@@ -21,6 +21,39 @@ export const AUTH_COOKIES = {
|
|
|
21
21
|
|
|
22
22
|
export const AUTH_SCOPES = ['openid', 'email', 'profile'] as const;
|
|
23
23
|
|
|
24
|
+
/** Backslashes, spaces, and ASCII control characters (`<= ' '` covers C0 and space). */
|
|
25
|
+
const unsafeInRedirect = (c: string) => c === '\\' || c <= ' ' || c === '\u007f';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Only same-origin absolute paths are allowed as post-login destinations.
|
|
29
|
+
* Browsers drop tabs and newlines from URLs (`/\t/evil.com` becomes
|
|
30
|
+
* `//evil.com`), so control characters and spaces are refused too.
|
|
31
|
+
*/
|
|
32
|
+
export function safeRedirect(target: string | null | undefined): string {
|
|
33
|
+
if (!target?.startsWith('/') || target.startsWith('//') || [...target].some(unsafeInRedirect)) return '/';
|
|
34
|
+
return target;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Path that starts sign-in and returns to `redirect` afterwards. */
|
|
38
|
+
export function loginPath(redirect = '/'): string {
|
|
39
|
+
return `${AUTH_ROUTES.login}?redirect=${encodeURIComponent(safeRedirect(redirect))}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Path that signs out and then goes to `redirect`. */
|
|
43
|
+
export function logoutPath(redirect = '/'): string {
|
|
44
|
+
return `${AUTH_ROUTES.logout}?redirect=${encodeURIComponent(safeRedirect(redirect))}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Body of every platform 401 (the `auth.required` gate and the SDK's
|
|
49
|
+
* `Unauthorized` error), so clients decode one shape.
|
|
50
|
+
*/
|
|
51
|
+
export const UNAUTHORIZED_BODY = {
|
|
52
|
+
_tag: 'Unauthorized',
|
|
53
|
+
message: 'Sign in required',
|
|
54
|
+
loginUrl: AUTH_ROUTES.login,
|
|
55
|
+
} as const;
|
|
56
|
+
|
|
24
57
|
/** The user object apps see. */
|
|
25
58
|
export interface PlatformUser {
|
|
26
59
|
/** Stable user id (Cognito `sub`). Same across all platform apps. */
|
package/src/bindings.ts
CHANGED
|
@@ -22,11 +22,17 @@ export interface Bindings {
|
|
|
22
22
|
queues: Record<string, { url: string; arn: string }>;
|
|
23
23
|
bus?: { name: string; arn: string };
|
|
24
24
|
/** Shared storage bucket; each named store is `prefix + <name>/`. */
|
|
25
|
-
storage?: { bucket: string; prefix: string; stores: string[] };
|
|
26
|
-
secrets: { path: string; sharedPath: string; names: string[] };
|
|
25
|
+
storage?: { bucket: string; prefix: string; stores: readonly string[] };
|
|
26
|
+
secrets: { path: string; sharedPath: string; names: readonly string[] };
|
|
27
27
|
auth?: AuthBindings;
|
|
28
28
|
/** Worker function name, for direct `invoke` jobs. */
|
|
29
29
|
worker?: string;
|
|
30
|
+
/**
|
|
31
|
+
* The stage's secret (32 random bytes, base64url), kept in SSM at
|
|
32
|
+
* `names.stageKeyParameter`. The SDK derives a key per purpose from it, e.g.
|
|
33
|
+
* to seal `db` query cursors. Absent on stages deployed before it existed.
|
|
34
|
+
*/
|
|
35
|
+
stageKey?: string;
|
|
30
36
|
}
|
|
31
37
|
|
|
32
38
|
export interface AuthBindings {
|
|
@@ -18,6 +18,11 @@ const kvs = cf.kvs(${JSON.stringify(opts.kvsId)});
|
|
|
18
18
|
|
|
19
19
|
${decideSrc}
|
|
20
20
|
|
|
21
|
+
function health(rec) {
|
|
22
|
+
var body = JSON.stringify({ ok: true, app: rec.app, stage: rec.stage, revision: rec.d });
|
|
23
|
+
return { statusCode: 200, statusDescription: 'OK', headers: { 'content-type': { value: 'application/json' }, 'cache-control': { value: 'no-store' } }, body: body };
|
|
24
|
+
}
|
|
25
|
+
|
|
21
26
|
function notFound() {
|
|
22
27
|
return { statusCode: 404, statusDescription: 'Not Found', headers: { 'content-type': { value: 'text/plain' }, 'cache-control': { value: 'no-store' } }, body: 'Nothing is deployed here.' };
|
|
23
28
|
}
|
|
@@ -32,6 +37,7 @@ async function handler(event) {
|
|
|
32
37
|
try { rec = JSON.parse(raw); } catch (e) { return notFound(); }
|
|
33
38
|
var d = decide(rec, req.uri);
|
|
34
39
|
if (d.t === 'notfound') return notFound();
|
|
40
|
+
if (d.t === 'health') return health(rec);
|
|
35
41
|
req.headers[${JSON.stringify(HOST_HEADER)}] = { value: host };
|
|
36
42
|
if (d.t === 'static') {
|
|
37
43
|
req.uri = d.key;
|
package/src/config.ts
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
* member allowlist. Members are GitHub usernames; inviting someone is a PR
|
|
4
4
|
* plus a platform deploy. No emails or account ids here (the repo is public).
|
|
5
5
|
*/
|
|
6
|
-
|
|
6
|
+
import { Schema } from 'effect';
|
|
7
|
+
export const MemberRole = Schema.Literals(['admin', 'member']);
|
|
8
|
+
export type MemberRole = typeof MemberRole.Type;
|
|
7
9
|
|
|
8
10
|
export interface Member {
|
|
9
11
|
github: string;
|
|
@@ -20,7 +22,13 @@ export interface PlatformConfig {
|
|
|
20
22
|
edgeHost: string;
|
|
21
23
|
/** Cognito managed login custom domain for app end users. */
|
|
22
24
|
loginHost: string;
|
|
23
|
-
|
|
25
|
+
/**
|
|
26
|
+
* `ownerId`/`repoId` are the numeric GitHub ids (public). Repos created with
|
|
27
|
+
* GitHub's immutable OIDC subject claims sign tokens as
|
|
28
|
+
* `repo:<owner>@<ownerId>/<repo>@<repoId>:...`, so roles that trust GitHub
|
|
29
|
+
* Actions need them (see `gh api repos/<owner>/<repo>/actions/oidc/customization/sub`).
|
|
30
|
+
*/
|
|
31
|
+
github: { owner: string; repo: string; ownerId: number; repoId: number };
|
|
24
32
|
members: Member[];
|
|
25
33
|
/** Names that already exist in the root zone (delegated or static records). */
|
|
26
34
|
reservedAppNames: string[];
|
package/src/constants.ts
CHANGED
|
@@ -20,6 +20,18 @@ export const PLATFORM_DEFAULTS = {
|
|
|
20
20
|
export const PLATFORM_PATH_PREFIX = '/__platform/';
|
|
21
21
|
export const HEALTH_PATH = '/__platform/health';
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Body served at `HEALTH_PATH`: by the SDK when the stage has a server, else
|
|
25
|
+
* by the edge router from its route record. `revision` is the deployment id,
|
|
26
|
+
* so a poller can tell which deployment answered.
|
|
27
|
+
*/
|
|
28
|
+
export interface HealthResponse {
|
|
29
|
+
ok: true;
|
|
30
|
+
app: string;
|
|
31
|
+
stage: string;
|
|
32
|
+
revision: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
23
35
|
/** Header the router sets so apps (and the cache key) see the public host. */
|
|
24
36
|
export const HOST_HEADER = 'x-platform-host';
|
|
25
37
|
/** Trace propagation header (W3C traceparent is also honored). */
|
package/src/manifest.ts
CHANGED
|
@@ -1,144 +1,315 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Effect, Schema } from 'effect';
|
|
2
2
|
import { validateCron } from './cron.ts';
|
|
3
3
|
import { APP_NAME_PATTERN, ENV_NAME_PATTERN, EVENT_TYPE_PATTERN, RESOURCE_KEY_PATTERN } from './naming.ts';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* infrastructure code. Keep this schema small and stable.
|
|
6
|
+
* The app's config file, at the app root. `plat` evaluates it and sends the
|
|
7
|
+
* result to the platform as JSON; the control plane never runs app code.
|
|
9
8
|
*/
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
9
|
+
export const APP_CONFIG_FILE = 'plat.config.ts';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What `plat.config.ts` declares: everything an app needs, in cloud-neutral
|
|
13
|
+
* terms. This is the whole contract between an app repo and the platform;
|
|
14
|
+
* apps contain no infrastructure code. Keep this schema small and stable.
|
|
15
|
+
*
|
|
16
|
+
* `ManifestSchema` validates the evaluated config (CLI and API); `AppConfig`
|
|
17
|
+
* below is the same shape written for authors. `test/manifest-types.test.ts`
|
|
18
|
+
* keeps the two in step.
|
|
19
|
+
*/
|
|
20
|
+
const RESOURCE_KEY_MESSAGE = 'must be 1-20 chars of a-z, 0-9, hyphens';
|
|
21
|
+
const resourceKey = Schema.String.check(
|
|
22
|
+
Schema.isPattern(RESOURCE_KEY_PATTERN, { message: RESOURCE_KEY_MESSAGE }),
|
|
23
|
+
);
|
|
24
|
+
const eventType = Schema.String.check(Schema.isPattern(EVENT_TYPE_PATTERN));
|
|
25
|
+
const envName = Schema.String.check(Schema.isPattern(ENV_NAME_PATTERN));
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A record whose keys must match `pattern`. `Schema.Record` drops keys that fail
|
|
29
|
+
* its key schema, which would make a misnamed queue silently disappear, so
|
|
30
|
+
* keys are checked here and reported at their path instead.
|
|
31
|
+
*/
|
|
32
|
+
const recordOf = <V extends Schema.Top>(pattern: RegExp, value: V, message = `must match ${pattern}`) =>
|
|
33
|
+
Schema.Record(Schema.String, value).check(
|
|
34
|
+
Schema.makeFilter((record) =>
|
|
35
|
+
Object.keys(record)
|
|
36
|
+
.filter((key) => !pattern.test(key))
|
|
37
|
+
.map((key) => ({ path: [key], issue: message })),
|
|
38
|
+
),
|
|
39
|
+
);
|
|
40
|
+
const intBetween = (minimum: number, maximum: number) =>
|
|
41
|
+
Schema.Int.check(Schema.isBetween({ minimum, maximum }));
|
|
42
|
+
/** Absent (or `undefined`) decodes to `value`. */
|
|
43
|
+
const orElse =
|
|
44
|
+
<S extends Schema.Top>(value: S['Encoded']) =>
|
|
45
|
+
(schema: S) =>
|
|
46
|
+
schema.pipe(Schema.withDecodingDefault(Effect.succeed(value)));
|
|
47
|
+
|
|
48
|
+
const WebSchema = Schema.Struct({
|
|
49
|
+
server: Schema.optional(Schema.String),
|
|
50
|
+
static: Schema.optional(Schema.String),
|
|
51
|
+
build: Schema.optional(Schema.String),
|
|
52
|
+
dev: Schema.optional(
|
|
53
|
+
Schema.Struct({ command: Schema.String, port: Schema.optional(intBetween(1, 65535)) }),
|
|
54
|
+
),
|
|
55
|
+
spa: Schema.Boolean.pipe(orElse(true)),
|
|
56
|
+
serverRoutes: Schema.Array(Schema.String.check(Schema.isStartingWith('/'))).pipe(orElse(['/api/'])),
|
|
57
|
+
timeoutSeconds: intBetween(3, 900).pipe(orElse(30)),
|
|
58
|
+
concurrency: intBetween(1, 128).pipe(orElse(64)),
|
|
59
|
+
}).check(
|
|
60
|
+
Schema.makeFilter((w) =>
|
|
61
|
+
w.server || w.static ? undefined : 'web needs a server, a static directory, or both',
|
|
62
|
+
),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const WorkerSchema = Schema.Struct({
|
|
66
|
+
entry: Schema.String.pipe(orElse('src/worker.ts')),
|
|
67
|
+
timeoutSeconds: intBetween(1, 900).pipe(orElse(60)),
|
|
68
|
+
memoryMb: intBetween(128, 10240).pipe(orElse(512)),
|
|
36
69
|
});
|
|
37
70
|
|
|
38
|
-
const QueueSchema =
|
|
39
|
-
batchSize:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
/** Max concurrent worker invocations draining this queue. */
|
|
44
|
-
concurrency: z.number().int().min(2).max(1000).optional(),
|
|
71
|
+
const QueueSchema = Schema.Struct({
|
|
72
|
+
batchSize: intBetween(1, 10).pipe(orElse(10)),
|
|
73
|
+
visibilityTimeoutSeconds: Schema.optional(intBetween(0, 43200)),
|
|
74
|
+
maxReceiveCount: intBetween(1, 1000).pipe(orElse(5)),
|
|
75
|
+
concurrency: Schema.optional(intBetween(2, 1000)),
|
|
45
76
|
});
|
|
46
77
|
|
|
47
|
-
const CronSchema =
|
|
78
|
+
const CronSchema = Schema.Union([
|
|
79
|
+
Schema.String,
|
|
80
|
+
Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) }),
|
|
81
|
+
]).check(
|
|
82
|
+
Schema.makeFilter((cron) => validateCron(typeof cron === 'string' ? cron : cron.schedule) ?? undefined),
|
|
83
|
+
);
|
|
48
84
|
|
|
49
|
-
const AuthSchema =
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
/** Require a signed-in user for every non-platform route (`/__platform/*` stays open). */
|
|
53
|
-
required: z.boolean().default(false),
|
|
54
|
-
}),
|
|
85
|
+
const AuthSchema = Schema.Union([
|
|
86
|
+
Schema.Boolean,
|
|
87
|
+
Schema.Struct({ required: Schema.Boolean.pipe(orElse(false)) }),
|
|
55
88
|
]);
|
|
56
89
|
|
|
57
|
-
export const ManifestSchema =
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
export const ManifestSchema = Schema.Struct({
|
|
91
|
+
// Reserved names are enforced when an app is registered (API), not here:
|
|
92
|
+
// the control plane itself is the app named `platform`.
|
|
93
|
+
name: Schema.String.check(
|
|
94
|
+
Schema.isPattern(APP_NAME_PATTERN, { message: 'must be 3-30 chars of a-z, 0-9, single hyphens' }),
|
|
95
|
+
),
|
|
96
|
+
description: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
|
|
97
|
+
web: Schema.optional(WebSchema),
|
|
98
|
+
worker: Schema.optional(WorkerSchema),
|
|
99
|
+
auth: AuthSchema.pipe(orElse(false)),
|
|
100
|
+
db: Schema.Boolean.pipe(orElse(false)),
|
|
101
|
+
queues: recordOf(RESOURCE_KEY_PATTERN, QueueSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
|
|
102
|
+
// The array form predates typed event payloads; deployments recorded
|
|
103
|
+
// before then still store it.
|
|
104
|
+
events: Schema.Union([Schema.Array(eventType), recordOf(EVENT_TYPE_PATTERN, Schema.Struct({}))]).pipe(
|
|
105
|
+
orElse([]),
|
|
106
|
+
),
|
|
107
|
+
crons: recordOf(RESOURCE_KEY_PATTERN, CronSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
|
|
108
|
+
storage: Schema.Array(resourceKey).pipe(orElse([])),
|
|
109
|
+
secrets: Schema.Array(envName).pipe(orElse([])),
|
|
110
|
+
env: recordOf(ENV_NAME_PATTERN, Schema.String).pipe(orElse({})),
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
/** The evaluated config as JSON: what the CLI sends and deployments store. */
|
|
114
|
+
export type ManifestInput = typeof ManifestSchema.Encoded;
|
|
115
|
+
export type Manifest = typeof ManifestSchema.Type;
|
|
116
|
+
|
|
117
|
+
// ---------------------------------------------------------------------------
|
|
118
|
+
// Authoring types. Arrays are readonly so `defineApp` can keep literal names.
|
|
119
|
+
|
|
120
|
+
/** Type-only marker for a queue's message body or an event's detail. Never set at runtime. */
|
|
121
|
+
declare const payloadType: unique symbol;
|
|
122
|
+
|
|
123
|
+
// A type literal, not an interface, so it fits the schema's `Record<string, never>` event options.
|
|
124
|
+
type Payload<T> = { readonly [payloadType]?: T };
|
|
125
|
+
|
|
126
|
+
/** The message or detail type declared with `queue<T>()` / `event<T>()`; `unknown` if none. */
|
|
127
|
+
export type PayloadOf<D> = D extends Payload<infer T> ? (unknown extends T ? unknown : T) : unknown;
|
|
128
|
+
|
|
129
|
+
export interface WebConfig {
|
|
130
|
+
/** Entry module whose default export is `toFetchHandler(...)` from `@ericminassian/platform`. */
|
|
131
|
+
server?: string;
|
|
132
|
+
/** Directory of built static assets, served from the edge. */
|
|
133
|
+
static?: string;
|
|
134
|
+
/** Shell command that builds `static` (run by `plat build`). */
|
|
135
|
+
build?: string;
|
|
136
|
+
/**
|
|
137
|
+
* Dev server for the frontend, proxied by `plat dev` (e.g. Vite). The command
|
|
138
|
+
* listens on the port `plat dev` passes in `PLATFORM_DEV_WEB_PORT` (and `PORT`):
|
|
139
|
+
* `port` when it is free, otherwise any free port.
|
|
140
|
+
*/
|
|
141
|
+
dev?: { command: string; port?: number };
|
|
142
|
+
/** Serve `index.html` for unknown non-file paths (client-side routing). Default `true`. */
|
|
143
|
+
spa?: boolean;
|
|
144
|
+
/** When both `server` and `static` exist, path prefixes handled by the server. Default `['/api/']`. */
|
|
145
|
+
serverRoutes?: readonly string[];
|
|
146
|
+
/** 3-900. Default 30. */
|
|
147
|
+
timeoutSeconds?: number;
|
|
148
|
+
/** Max concurrent requests per Web Function environment, 1-128. Default 64. */
|
|
149
|
+
concurrency?: number;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface WorkerConfig {
|
|
153
|
+
/** Module whose default export is `defineWorker(...)`. Default `src/worker.ts`. */
|
|
154
|
+
entry?: string;
|
|
155
|
+
/** 1-900. Default 60. */
|
|
156
|
+
timeoutSeconds?: number;
|
|
157
|
+
/** 128-10240. Default 512. */
|
|
158
|
+
memoryMb?: number;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Declare one with `queue<Body>({ ... })` to type what is sent and received. */
|
|
162
|
+
export interface QueueConfig<Body = unknown> extends Payload<Body> {
|
|
163
|
+
/** Messages per worker invocation, 1-10. Default 10. */
|
|
164
|
+
batchSize?: number;
|
|
165
|
+
/** Defaults to 6x the worker timeout, as AWS recommends for Lambda consumers. */
|
|
166
|
+
visibilityTimeoutSeconds?: number;
|
|
167
|
+
/** Deliveries before a message moves to the dead-letter queue, 1-1000. Default 5. */
|
|
168
|
+
maxReceiveCount?: number;
|
|
169
|
+
/** Max concurrent worker invocations draining this queue, 2-1000. */
|
|
170
|
+
concurrency?: number;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Declare one with `event<Detail>()` to type what is published and handled. */
|
|
174
|
+
export type EventConfig<Detail = unknown> = Payload<Detail>;
|
|
175
|
+
|
|
176
|
+
/** 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`. */
|
|
177
|
+
export type CronConfig = string | { schedule: string; timezone?: string };
|
|
178
|
+
|
|
179
|
+
export interface AppConfig {
|
|
180
|
+
/** 3-30 chars of a-z, 0-9 and single hyphens; also the app's host name. */
|
|
94
181
|
name: string;
|
|
95
182
|
description?: string;
|
|
96
|
-
web?:
|
|
97
|
-
/** Present when any queue, event
|
|
98
|
-
worker?:
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
183
|
+
web?: WebConfig;
|
|
184
|
+
/** Present automatically when any queue, event or cron exists. */
|
|
185
|
+
worker?: WorkerConfig;
|
|
186
|
+
/** Sign-in with the shared user pool. `{ required: true }` guards every non-platform route. */
|
|
187
|
+
auth?: boolean | { required?: boolean };
|
|
188
|
+
/** One document database per stage; collections are declared in code. */
|
|
189
|
+
db?: boolean;
|
|
190
|
+
/** Keys are 1-20 chars of a-z, 0-9 and hyphens. Each needs a handler in the worker. */
|
|
191
|
+
queues?: { readonly [name: string]: QueueConfig };
|
|
192
|
+
/** Event types the worker subscribes to, e.g. `order.created`. Each needs a handler in the worker. */
|
|
193
|
+
events?: readonly string[] | { readonly [type: string]: EventConfig };
|
|
194
|
+
/** Scheduled jobs. Each needs a handler in the worker. */
|
|
195
|
+
crons?: { readonly [name: string]: CronConfig };
|
|
196
|
+
/** Named file stores. */
|
|
197
|
+
storage?: readonly string[];
|
|
198
|
+
/** Secret names like `STRIPE_KEY`; values are set with `plat secrets set`. */
|
|
199
|
+
secrets?: readonly string[];
|
|
200
|
+
/** Plain, non-secret configuration exposed as environment variables. */
|
|
201
|
+
env?: { readonly [name: string]: string };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Maps every key `T` has but `Shape` doesn't to `never`, recursively, so a
|
|
206
|
+
* misspelled field is a type error. `defineApp` needs this because a generic
|
|
207
|
+
* parameter (which keeps the literal names) skips excess-property checks.
|
|
208
|
+
*/
|
|
209
|
+
type Exact<T, Shape> = Shape extends readonly (infer S)[]
|
|
210
|
+
? T extends readonly (infer E)[]
|
|
211
|
+
? readonly Exact<E, S>[]
|
|
212
|
+
: Shape
|
|
213
|
+
: Shape extends object
|
|
214
|
+
? T extends object
|
|
215
|
+
? { [K in keyof T]: K extends keyof Shape ? Exact<T[K], Shape[K]> : never }
|
|
216
|
+
: Shape
|
|
217
|
+
: Shape;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The default export of `plat.config.ts`. Returns the config unchanged with
|
|
221
|
+
* its literal names, which `Register` hands to the SDK so queue, event, cron,
|
|
222
|
+
* store and secret names (and payload types) are checked in app code.
|
|
223
|
+
*/
|
|
224
|
+
export function defineApp<const T extends AppConfig>(config: T & Exact<T, AppConfig>): T {
|
|
225
|
+
return config;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ batchSize: 5 }) }`. */
|
|
229
|
+
export function queue<Body>(options: QueueConfig = {}): QueueConfig<Body> {
|
|
230
|
+
return options as QueueConfig<Body>;
|
|
107
231
|
}
|
|
108
232
|
|
|
233
|
+
/** An event subscription whose detail is `Detail`: `events: { 'todo.created': event<TodoCreated>() }`. */
|
|
234
|
+
export function event<Detail>(): EventConfig<Detail> {
|
|
235
|
+
return {};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ---------------------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Manifest with defaults applied and derived fields normalized: what
|
|
242
|
+
* deployments store. Decoding fills defaults for fields added since a stored
|
|
243
|
+
* manifest was written, so earlier deployments keep decoding.
|
|
244
|
+
*/
|
|
245
|
+
export const ResolvedManifest = Schema.Struct({
|
|
246
|
+
name: Schema.String,
|
|
247
|
+
description: Schema.optional(Schema.String),
|
|
248
|
+
web: Schema.optional(WebSchema),
|
|
249
|
+
/** Present when any queue, event subscription or cron exists. */
|
|
250
|
+
worker: Schema.optional(WorkerSchema),
|
|
251
|
+
auth: Schema.Struct({ enabled: Schema.Boolean, required: Schema.Boolean }),
|
|
252
|
+
db: Schema.Boolean,
|
|
253
|
+
queues: Schema.Record(
|
|
254
|
+
Schema.String,
|
|
255
|
+
Schema.Struct({ ...QueueSchema.fields, visibilityTimeoutSeconds: Schema.Finite }),
|
|
256
|
+
),
|
|
257
|
+
events: Schema.Array(Schema.String),
|
|
258
|
+
crons: Schema.Record(
|
|
259
|
+
Schema.String,
|
|
260
|
+
Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) }),
|
|
261
|
+
),
|
|
262
|
+
storage: Schema.Array(Schema.String),
|
|
263
|
+
secrets: Schema.Array(Schema.String),
|
|
264
|
+
env: Schema.Record(Schema.String, Schema.String),
|
|
265
|
+
});
|
|
266
|
+
export type ResolvedManifest = typeof ResolvedManifest.Type;
|
|
267
|
+
|
|
109
268
|
export class ManifestError extends Error {
|
|
110
269
|
readonly issues: string[];
|
|
111
270
|
constructor(issues: string[]) {
|
|
112
|
-
super(`Invalid
|
|
271
|
+
super(`Invalid ${APP_CONFIG_FILE}:\n - ${issues.join('\n - ')}`);
|
|
113
272
|
this.issues = issues;
|
|
114
273
|
}
|
|
115
274
|
}
|
|
116
275
|
|
|
276
|
+
const validateManifest = Schema.toStandardSchemaV1(ManifestSchema, { parseOptions: { errors: 'all' } })[
|
|
277
|
+
'~standard'
|
|
278
|
+
].validate;
|
|
279
|
+
|
|
117
280
|
export function parseManifest(input: unknown): ResolvedManifest {
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
281
|
+
const result = validateManifest(input);
|
|
282
|
+
// The schema has no asynchronous checks, so validation is synchronous.
|
|
283
|
+
if (result instanceof Promise) throw new Error('manifest validation must be synchronous');
|
|
284
|
+
if (result.issues) {
|
|
285
|
+
throw new ManifestError(
|
|
286
|
+
result.issues.map((i) => {
|
|
287
|
+
const path = (i.path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
288
|
+
return `${path || '(root)'}: ${i.message}`;
|
|
289
|
+
}),
|
|
290
|
+
);
|
|
121
291
|
}
|
|
122
|
-
return resolveManifest(
|
|
292
|
+
return resolveManifest(result.value);
|
|
123
293
|
}
|
|
124
294
|
|
|
125
295
|
export function resolveManifest(m: Manifest): ResolvedManifest {
|
|
296
|
+
const events = Array.isArray(m.events) ? m.events : Object.keys(m.events);
|
|
126
297
|
const needsWorker =
|
|
127
|
-
Object.keys(m.queues).length > 0 ||
|
|
128
|
-
const worker = m.worker ?? (needsWorker ?
|
|
298
|
+
Object.keys(m.queues).length > 0 || events.length > 0 || Object.keys(m.crons).length > 0;
|
|
299
|
+
const worker = m.worker ?? (needsWorker ? Schema.decodeUnknownSync(WorkerSchema)({}) : undefined);
|
|
129
300
|
const auth =
|
|
130
301
|
typeof m.auth === 'boolean'
|
|
131
302
|
? { enabled: m.auth, required: false }
|
|
132
303
|
: { enabled: true, required: m.auth.required };
|
|
133
|
-
const queues: ResolvedManifest['queues'] =
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
...q,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
304
|
+
const queues: ResolvedManifest['queues'] = Object.fromEntries(
|
|
305
|
+
Object.entries(m.queues).map(([key, q]) => [
|
|
306
|
+
key,
|
|
307
|
+
{ ...q, visibilityTimeoutSeconds: q.visibilityTimeoutSeconds ?? (worker?.timeoutSeconds ?? 60) * 6 },
|
|
308
|
+
]),
|
|
309
|
+
);
|
|
310
|
+
const crons: ResolvedManifest['crons'] = Object.fromEntries(
|
|
311
|
+
Object.entries(m.crons).map(([key, c]) => [key, typeof c === 'string' ? { schedule: c } : c]),
|
|
312
|
+
);
|
|
142
313
|
return {
|
|
143
314
|
name: m.name,
|
|
144
315
|
...(m.description ? { description: m.description } : {}),
|
|
@@ -147,14 +318,10 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
|
|
|
147
318
|
auth,
|
|
148
319
|
db: m.db,
|
|
149
320
|
queues,
|
|
150
|
-
events: [...new Set(
|
|
321
|
+
events: [...new Set(events)],
|
|
151
322
|
crons,
|
|
152
323
|
storage: [...new Set(m.storage)],
|
|
153
324
|
secrets: [...new Set(m.secrets)],
|
|
154
325
|
env: m.env,
|
|
155
326
|
};
|
|
156
327
|
}
|
|
157
|
-
|
|
158
|
-
/** JSON Schema URL apps reference for editor completion. */
|
|
159
|
-
export const MANIFEST_SCHEMA_URL =
|
|
160
|
-
'https://raw.githubusercontent.com/eric-minassian/platform/main/packages/core/platform.schema.json';
|
package/src/naming.ts
CHANGED
|
@@ -94,7 +94,12 @@ export const names = {
|
|
|
94
94
|
base: (app: string, stage: string) => `${app}--${stage}`,
|
|
95
95
|
table: (app: string, stage: string) => `${app}--${stage}`,
|
|
96
96
|
webFunction: (app: string, stage: string) => `${app}--${stage}`,
|
|
97
|
-
|
|
97
|
+
/**
|
|
98
|
+
* The Web Function's two endpoints, each pinned to one revision. Neither
|
|
99
|
+
* name means "current": a deploy uses whichever the live route doesn't
|
|
100
|
+
* (`live` predates the second one).
|
|
101
|
+
*/
|
|
102
|
+
webEndpoints: () => ['live', 'live-b'] as const,
|
|
98
103
|
workerFunction: (app: string, stage: string) => `${app}--${stage}--worker`,
|
|
99
104
|
/** IAM role name; created under {@link IAM_APP_PATH}. */
|
|
100
105
|
role: (app: string, stage: string) => `${app}--${stage}`,
|
|
@@ -107,12 +112,18 @@ export const names = {
|
|
|
107
112
|
scheduleGroup: (app: string, stage: string) => `${app}--${stage}`,
|
|
108
113
|
schedule: (cronKey: string) => cronKey,
|
|
109
114
|
userPoolClient: (app: string, stage: string) => `${app}--${stage}`,
|
|
110
|
-
|
|
115
|
+
/**
|
|
116
|
+
* A stage's log groups. Lambda also writes a Web Function's environments to
|
|
117
|
+
* `<web group>.local`, so the engine creates that one too.
|
|
118
|
+
*/
|
|
119
|
+
logGroup: (app: string, stage: string, component: 'web' | 'web.local' | 'worker') =>
|
|
111
120
|
`/platform/apps/${app}/${stage}/${component}`,
|
|
112
121
|
logGroupPrefix: (app: string, stage?: string) =>
|
|
113
122
|
stage ? `/platform/apps/${app}/${stage}/` : `/platform/apps/${app}/`,
|
|
114
123
|
secretsPath: (app: string, stage: string) => `/platform/apps/${app}/${stage}/secrets/`,
|
|
115
124
|
sharedSecretsPath: (app: string) => `/platform/apps/${app}/_shared/secrets/`,
|
|
125
|
+
/** SSM SecureString holding the stage key (see `Bindings.stageKey`); outside the secrets path. */
|
|
126
|
+
stageKeyParameter: (app: string, stage: string) => `/platform/apps/${app}/${stage}/stage-key`,
|
|
116
127
|
/** Prefix inside the shared storage bucket: `<app>/<stage>/<bucket>/`. */
|
|
117
128
|
storagePrefix: (app: string, stage: string, bucket?: string) =>
|
|
118
129
|
bucket ? `${app}/${stage}/${bucket}/` : `${app}/${stage}/`,
|