@ericminassian/platform-core 0.2.0 → 0.4.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.
Files changed (89) hide show
  1. package/dist/api.d.ts +1847 -212
  2. package/dist/api.js +694 -1
  3. package/dist/api.js.map +1 -1
  4. package/dist/auth.d.ts +19 -0
  5. package/dist/auth.js +32 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/base64url.d.ts +3 -0
  8. package/dist/base64url.js +15 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/bindings.d.ts +69 -13
  11. package/dist/bindings.js +1 -1
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/cloudfront-function.d.ts +5 -1
  14. package/dist/cloudfront-function.js +70 -2
  15. package/dist/cloudfront-function.js.map +1 -1
  16. package/dist/compute.d.ts +52 -0
  17. package/dist/compute.js +65 -0
  18. package/dist/compute.js.map +1 -0
  19. package/dist/config.d.ts +21 -1
  20. package/dist/config.js +16 -0
  21. package/dist/config.js.map +1 -1
  22. package/dist/constants.d.ts +67 -1
  23. package/dist/constants.js +56 -1
  24. package/dist/constants.js.map +1 -1
  25. package/dist/email.d.ts +84 -0
  26. package/dist/email.js +111 -0
  27. package/dist/email.js.map +1 -0
  28. package/dist/fingerprint.d.ts +9 -0
  29. package/dist/fingerprint.js +19 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +6 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/jobs.d.ts +111 -0
  35. package/dist/jobs.js +214 -0
  36. package/dist/jobs.js.map +1 -0
  37. package/dist/manifest.d.ts +357 -112
  38. package/dist/manifest.js +270 -72
  39. package/dist/manifest.js.map +1 -1
  40. package/dist/naming.d.ts +93 -6
  41. package/dist/naming.js +98 -6
  42. package/dist/naming.js.map +1 -1
  43. package/dist/platform-api.d.ts +7792 -0
  44. package/dist/platform-api.js +455 -0
  45. package/dist/platform-api.js.map +1 -0
  46. package/dist/realtime.d.ts +139 -0
  47. package/dist/realtime.js +201 -0
  48. package/dist/realtime.js.map +1 -0
  49. package/dist/router/decide.d.ts +7 -1
  50. package/dist/router/decide.js +42 -5
  51. package/dist/router.d.ts +35 -13
  52. package/dist/router.js +36 -0
  53. package/dist/router.js.map +1 -1
  54. package/dist/runtime-config.d.ts +57 -0
  55. package/dist/runtime-config.js +12 -0
  56. package/dist/runtime-config.js.map +1 -1
  57. package/dist/storage.d.ts +55 -0
  58. package/dist/storage.js +112 -0
  59. package/dist/storage.js.map +1 -0
  60. package/dist/telemetry.d.ts +350 -83
  61. package/dist/telemetry.js +188 -15
  62. package/dist/telemetry.js.map +1 -1
  63. package/dist/web-compute.d.ts +191 -0
  64. package/dist/web-compute.js +257 -0
  65. package/dist/web-compute.js.map +1 -0
  66. package/package.json +28 -8
  67. package/src/api.ts +864 -238
  68. package/src/auth.ts +37 -0
  69. package/src/base64url.ts +13 -0
  70. package/src/bindings.ts +74 -7
  71. package/src/cloudfront-function.ts +70 -2
  72. package/src/compute.ts +86 -0
  73. package/src/config.ts +34 -2
  74. package/src/constants.ts +76 -1
  75. package/src/email.ts +168 -0
  76. package/src/fingerprint.ts +20 -0
  77. package/src/index.ts +6 -0
  78. package/src/jobs.ts +281 -0
  79. package/src/manifest.ts +542 -114
  80. package/src/naming.ts +103 -8
  81. package/src/platform-api.ts +630 -0
  82. package/src/realtime.ts +298 -0
  83. package/src/router/decide.d.ts +7 -1
  84. package/src/router/decide.js +42 -5
  85. package/src/router.ts +33 -13
  86. package/src/runtime-config.ts +70 -0
  87. package/src/storage.ts +120 -0
  88. package/src/telemetry.ts +198 -93
  89. package/src/web-compute.ts +342 -0
package/src/manifest.ts CHANGED
@@ -1,6 +1,17 @@
1
- import { z } from 'zod';
1
+ import { Effect, Schema } from 'effect';
2
+ import { FARGATE_CPUS, type FargateCpu, fargateSizeIssue } from './compute.ts';
2
3
  import { validateCron } from './cron.ts';
3
- import { APP_NAME_PATTERN, ENV_NAME_PATTERN, EVENT_TYPE_PATTERN, RESOURCE_KEY_PATTERN } from './naming.ts';
4
+ import { EMAIL_DEFAULT_DAILY_LIMIT, EMAIL_NAME_MESSAGE, EMAIL_NAME_PATTERN } from './email.ts';
5
+ import { DEFAULT_ATTEMPTS, MAX_ATTEMPTS } from './jobs.ts';
6
+ import {
7
+ APP_NAME_PATTERN,
8
+ ENV_NAME_PATTERN,
9
+ EVENT_TYPE_PATTERN,
10
+ names,
11
+ RESOURCE_KEY_PATTERN,
12
+ } from './naming.ts';
13
+ import { CHANNEL_DECLARATION_PATTERN, CHANNEL_MESSAGE, realtimeIssues } from './realtime.ts';
14
+ import { WEB_COMPUTE_SETTINGS, WEB_REQUEST_MEMORY_MB, type WebComputeSetting } from './web-compute.ts';
4
15
 
5
16
  /**
6
17
  * The app's config file, at the app root. `plat` evaluates it and sends the
@@ -17,70 +28,186 @@ export const APP_CONFIG_FILE = 'plat.config.ts';
17
28
  * below is the same shape written for authors. `test/manifest-types.test.ts`
18
29
  * keeps the two in step.
19
30
  */
20
- const resourceKey = z.string().regex(RESOURCE_KEY_PATTERN, 'must be 1-20 chars of a-z, 0-9, hyphens');
21
- const eventType = z.string().regex(EVENT_TYPE_PATTERN);
22
-
23
- const WebSchema = z
24
- .object({
25
- server: z.string().optional(),
26
- static: z.string().optional(),
27
- build: z.string().optional(),
28
- dev: z.object({ command: z.string(), port: z.number().int().positive() }).optional(),
29
- spa: z.boolean().default(true),
30
- serverRoutes: z.array(z.string().startsWith('/')).default(['/api/']),
31
- timeoutSeconds: z.number().int().min(3).max(900).default(30),
32
- concurrency: z.number().int().min(1).max(128).default(64),
33
- })
34
- .refine((w) => w.server || w.static, { message: 'web needs a server, a static directory, or both' });
35
-
36
- const WorkerSchema = z.object({
37
- entry: z.string().default('src/worker.ts'),
38
- timeoutSeconds: z.number().int().min(1).max(900).default(60),
39
- memoryMb: z.number().int().min(128).max(10240).default(512),
31
+ const RESOURCE_KEY_MESSAGE = 'must be 1-20 chars of a-z, 0-9, hyphens';
32
+ const resourceKey = Schema.String.check(
33
+ Schema.isPattern(RESOURCE_KEY_PATTERN, { message: RESOURCE_KEY_MESSAGE }),
34
+ );
35
+ const eventType = Schema.String.check(Schema.isPattern(EVENT_TYPE_PATTERN));
36
+ const envName = Schema.String.check(Schema.isPattern(ENV_NAME_PATTERN));
37
+
38
+ /**
39
+ * A record whose keys must match `pattern`. `Schema.Record` drops keys that fail
40
+ * its key schema, which would make a misnamed queue silently disappear, so
41
+ * keys are checked here and reported at their path instead.
42
+ */
43
+ const recordOf = <V extends Schema.Top>(pattern: RegExp, value: V, message = `must match ${pattern}`) =>
44
+ Schema.Record(Schema.String, value).check(
45
+ Schema.makeFilter((record) =>
46
+ Object.keys(record)
47
+ .filter((key) => !pattern.test(key))
48
+ .map((key) => ({ path: [key], issue: message })),
49
+ ),
50
+ );
51
+ const intBetween = (minimum: number, maximum: number) =>
52
+ Schema.Int.check(Schema.isBetween({ minimum, maximum }));
53
+ /** Absent (or `undefined`) decodes to `value`. */
54
+ const orElse =
55
+ <S extends Schema.Top>(value: S['Encoded']) =>
56
+ (schema: S) =>
57
+ schema.pipe(Schema.withDecodingDefault(Effect.succeed(value)));
58
+
59
+ const WebSchema = Schema.Struct({
60
+ server: Schema.optional(Schema.String),
61
+ static: Schema.optional(Schema.String),
62
+ build: Schema.optional(Schema.String),
63
+ dev: Schema.optional(
64
+ Schema.Struct({ command: Schema.String, port: Schema.optional(intBetween(1, 65535)) }),
65
+ ),
66
+ spa: Schema.Boolean.pipe(orElse(true)),
67
+ serverRoutes: Schema.Array(Schema.String.check(Schema.isStartingWith('/'))).pipe(orElse(['/api/'])),
68
+ timeoutSeconds: intBetween(3, 900).pipe(orElse(30)),
69
+ concurrency: intBetween(1, 128).pipe(orElse(64)),
70
+ compute: Schema.Literals(WEB_COMPUTE_SETTINGS).pipe(orElse('auto')),
71
+ memoryMb: intBetween(128, 10240).pipe(orElse(WEB_REQUEST_MEMORY_MB)),
72
+ maxEnvironments: Schema.optional(intBetween(2, 10000)),
73
+ }).check(
74
+ Schema.makeFilter((w) =>
75
+ w.server || w.static ? undefined : 'web needs a server, a static directory, or both',
76
+ ),
77
+ );
78
+
79
+ const WORKER_TIMEOUT_SECONDS = 60;
80
+ const WORKER_MEMORY_MB = 512;
81
+ const timeoutSeconds = intBetween(1, 900);
82
+ const memoryMb = intBetween(128, 10240);
83
+
84
+ const WorkerSchema = Schema.Struct({
85
+ entry: Schema.String.pipe(orElse('src/worker.ts')),
86
+ timeoutSeconds: timeoutSeconds.pipe(orElse(WORKER_TIMEOUT_SECONDS)),
87
+ memoryMb: memoryMb.pipe(orElse(WORKER_MEMORY_MB)),
88
+ });
89
+
90
+ /** A queue, event or cron handler's own settings; unset ones are the worker's. */
91
+ const HandlerFields = {
92
+ timeoutSeconds: Schema.optional(timeoutSeconds),
93
+ memoryMb: Schema.optional(memoryMb),
94
+ };
95
+ const attempts = intBetween(1, MAX_ATTEMPTS);
96
+ /** An event handler's settings. Unset attempts are `DEFAULT_ATTEMPTS.event`. */
97
+ const HandlerSchema = Schema.Struct({ ...HandlerFields, maxAttempts: Schema.optional(attempts) });
98
+
99
+ const QueueFields = {
100
+ maxAttempts: attempts.pipe(orElse(DEFAULT_ATTEMPTS.queue)),
101
+ concurrency: Schema.optional(intBetween(1, 1000)),
102
+ ...HandlerFields,
103
+ };
104
+
105
+ /** A field that was removed: present at all, it fails with `message`. */
106
+ const removed = (message: string) => Schema.optional(Schema.Unknown.check(Schema.makeFilter(() => message)));
107
+
108
+ // Queues were SQS queues polled by Lambda until 0.4.0; these settings had no meaning after.
109
+ const QueueSchema = Schema.Struct({
110
+ ...QueueFields,
111
+ batchSize: removed('removed in 0.4.0: a queue delivers one message per run'),
112
+ visibilityTimeoutSeconds: removed("removed in 0.4.0: a run has its handler's timeoutSeconds"),
113
+ maxReceiveCount: removed('renamed to maxAttempts in 0.4.0'),
40
114
  });
41
115
 
42
- const QueueSchema = z.object({
43
- batchSize: z.number().int().min(1).max(10).default(10),
44
- visibilityTimeoutSeconds: z.number().int().min(0).max(43200).optional(),
45
- maxReceiveCount: z.number().int().min(1).max(1000).default(5),
46
- concurrency: z.number().int().min(2).max(1000).optional(),
116
+ const CronScheduleSchema = Schema.Struct({
117
+ schedule: Schema.String,
118
+ timezone: Schema.optional(Schema.String),
119
+ maxAttempts: Schema.optional(attempts),
120
+ ...HandlerFields,
47
121
  });
48
122
 
49
- const CronSchema = z.union([z.string(), z.object({ schedule: z.string(), timezone: z.string().optional() })]);
50
-
51
- const AuthSchema = z.union([z.boolean(), z.object({ required: z.boolean().default(false) })]);
52
-
53
- export const ManifestSchema = z
54
- .object({
55
- name: z
56
- .string()
57
- // Reserved names are enforced when an app is registered (API), not here:
58
- // the control plane itself is the app named `platform`.
59
- .regex(APP_NAME_PATTERN, 'must be 3-30 chars of a-z, 0-9, single hyphens'),
60
- description: z.string().max(200).optional(),
61
- web: WebSchema.optional(),
62
- worker: WorkerSchema.optional(),
63
- auth: AuthSchema.default(false),
64
- db: z.boolean().default(false),
65
- queues: z.record(resourceKey, QueueSchema).default({}),
66
- // The array form predates typed event payloads; deployments recorded
67
- // before then still store it.
68
- events: z.union([z.array(eventType), z.record(eventType, z.object({}))]).default([]),
69
- crons: z.record(resourceKey, CronSchema).default({}),
70
- storage: z.array(resourceKey).default([]),
71
- secrets: z.array(z.string().regex(ENV_NAME_PATTERN)).default([]),
72
- env: z.record(z.string().regex(ENV_NAME_PATTERN), z.string()).default({}),
73
- })
74
- .superRefine((m, ctx) => {
75
- for (const [key, cron] of Object.entries(m.crons)) {
76
- const err = validateCron(typeof cron === 'string' ? cron : cron.schedule);
77
- if (err) ctx.addIssue({ code: 'custom', path: ['crons', key], message: err });
78
- }
79
- });
123
+ const CronSchema = Schema.Union([Schema.String, CronScheduleSchema]).check(
124
+ Schema.makeFilter((cron) => validateCron(typeof cron === 'string' ? cron : cron.schedule) ?? undefined),
125
+ );
126
+
127
+ const AuthSchema = Schema.Union([
128
+ Schema.Boolean,
129
+ Schema.Struct({ required: Schema.Boolean.pipe(orElse(false)) }),
130
+ ]);
131
+
132
+ const StoreSchema = Schema.Struct({
133
+ public: Schema.Boolean.pipe(orElse(false)),
134
+ expireAfterDays: Schema.optional(intBetween(1, 3650)),
135
+ });
136
+ const ServiceSchema = Schema.Struct({
137
+ entry: Schema.String,
138
+ cpu: Schema.Literals(FARGATE_CPUS).pipe(orElse(0.25)),
139
+ memoryMb: Schema.Int.pipe(orElse(512)),
140
+ spot: Schema.Boolean.pipe(orElse(true)),
141
+ previewMinutes: intBetween(0, 1440).pipe(orElse(30)),
142
+ }).check(
143
+ Schema.makeFilter((s) => {
144
+ const issue = fargateSizeIssue(s.cpu, s.memoryMb);
145
+ return issue ? [{ path: ['memoryMb'], issue }] : undefined;
146
+ }),
147
+ );
148
+
149
+ const RealtimeSubscribeSchema = Schema.Literals(['public', 'signed-in']);
150
+
151
+ const EmailSchema = Schema.Union([
152
+ Schema.Boolean,
153
+ Schema.Struct({
154
+ name: Schema.optional(
155
+ Schema.String.check(Schema.isPattern(EMAIL_NAME_PATTERN, { message: EMAIL_NAME_MESSAGE })),
156
+ ),
157
+ // The platform's ceiling (`limits.emailsPerDay`) is checked when a deployment is created.
158
+ dailyLimit: Schema.optional(intBetween(1, 1_000_000)),
159
+ }),
160
+ ]);
161
+
162
+ const RealtimeSchema = Schema.Struct({
163
+ subscribe: RealtimeSubscribeSchema.pipe(orElse('public')),
164
+ channels: recordOf(CHANNEL_DECLARATION_PATTERN, Schema.Struct({}), CHANNEL_MESSAGE),
165
+ });
166
+
167
+ export const ManifestSchema = Schema.Struct({
168
+ // Reserved names are enforced when an app is registered (API), not here:
169
+ // the control plane itself is the app named `platform`.
170
+ name: Schema.String.check(
171
+ Schema.isPattern(APP_NAME_PATTERN, { message: 'must be 3-30 chars of a-z, 0-9, single hyphens' }),
172
+ ),
173
+ description: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
174
+ web: Schema.optional(WebSchema),
175
+ worker: Schema.optional(WorkerSchema),
176
+ auth: AuthSchema.pipe(orElse(false)),
177
+ db: Schema.Boolean.pipe(orElse(false)),
178
+ queues: recordOf(RESOURCE_KEY_PATTERN, QueueSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
179
+ // The array form predates typed event payloads; deployments recorded
180
+ // before then still store it.
181
+ events: Schema.Union([Schema.Array(eventType), recordOf(EVENT_TYPE_PATTERN, HandlerSchema)]).pipe(
182
+ orElse([]),
183
+ ),
184
+ crons: recordOf(RESOURCE_KEY_PATTERN, CronSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
185
+ // The array form (every store private, kept forever) is still accepted.
186
+ storage: Schema.Union([
187
+ Schema.Array(resourceKey),
188
+ recordOf(RESOURCE_KEY_PATTERN, StoreSchema, RESOURCE_KEY_MESSAGE),
189
+ ]).pipe(orElse([])),
190
+ secrets: Schema.Array(envName).pipe(orElse([])),
191
+ env: recordOf(ENV_NAME_PATTERN, Schema.String).pipe(orElse({})),
192
+ realtime: Schema.optional(RealtimeSchema),
193
+ email: EmailSchema.pipe(orElse(false)),
194
+ services: recordOf(RESOURCE_KEY_PATTERN, ServiceSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
195
+ }).check(
196
+ Schema.makeFilter((m) => {
197
+ if (!m.realtime) return undefined;
198
+ const issues = realtimeIssues({
199
+ subscribe: m.realtime.subscribe,
200
+ channels: Object.keys(m.realtime.channels),
201
+ auth: m.auth !== false,
202
+ server: Boolean(m.web?.server),
203
+ });
204
+ return issues.map((i) => ({ path: ['realtime', ...i.path], issue: i.message }));
205
+ }),
206
+ );
80
207
 
81
208
  /** The evaluated config as JSON: what the CLI sends and deployments store. */
82
- export type ManifestInput = z.input<typeof ManifestSchema>;
83
- export type Manifest = z.output<typeof ManifestSchema>;
209
+ export type ManifestInput = typeof ManifestSchema.Encoded;
210
+ export type Manifest = typeof ManifestSchema.Type;
84
211
 
85
212
  // ---------------------------------------------------------------------------
86
213
  // Authoring types. Arrays are readonly so `defineApp` can keep literal names.
@@ -95,50 +222,181 @@ type Payload<T> = { readonly [payloadType]?: T };
95
222
  export type PayloadOf<D> = D extends Payload<infer T> ? (unknown extends T ? unknown : T) : unknown;
96
223
 
97
224
  export interface WebConfig {
98
- /** Entry module whose default export is a fetch handler (`{ fetch }`, a function, or a Hono app). */
225
+ /** Entry module whose default export is `toFetchHandler(...)` from `@ericminassian/platform`. */
99
226
  server?: string;
100
227
  /** Directory of built static assets, served from the edge. */
101
228
  static?: string;
102
229
  /** Shell command that builds `static` (run by `plat build`). */
103
230
  build?: string;
104
- /** Dev server for the frontend, proxied by `plat dev` (e.g. Vite). */
105
- dev?: { command: string; port: number };
231
+ /**
232
+ * Dev server for the frontend, proxied by `plat dev` (e.g. Vite). The command
233
+ * listens on the port `plat dev` passes in `PLATFORM_DEV_WEB_PORT` (and `PORT`):
234
+ * `port` when it is free, otherwise any free port.
235
+ */
236
+ dev?: { command: string; port?: number };
106
237
  /** Serve `index.html` for unknown non-file paths (client-side routing). Default `true`. */
107
238
  spa?: boolean;
108
239
  /** When both `server` and `static` exist, path prefixes handled by the server. Default `['/api/']`. */
109
240
  serverRoutes?: readonly string[];
110
241
  /** 3-900. Default 30. */
111
242
  timeoutSeconds?: number;
112
- /** Max concurrent requests per Web Function environment, 1-128. Default 64. */
243
+ /** Max concurrent requests per Web Function environment (instance mode), 1-128. Default 64. */
113
244
  concurrency?: number;
245
+ /**
246
+ * How the server runs. `request`: one invocation per request, billed by the
247
+ * millisecond and nothing while idle. `instance`: a Web Function, whose
248
+ * environments serve many requests at once and are billed for their memory
249
+ * while they live (until about five minutes after the last request).
250
+ * `auto` (default): previews run `request`; prod starts on `request` and
251
+ * moves to whichever mode its traffic makes cheaper, checked daily.
252
+ */
253
+ compute?: WebComputeSetting;
254
+ /** Memory of the server in request mode, 128-10240 MB (CPU grows with it). Default 1024. */
255
+ memoryMb?: number;
256
+ /** Most environments prod's Web Function (instance mode) runs at once, 2-10000. Default 10; previews 2. */
257
+ maxEnvironments?: number;
114
258
  }
115
259
 
116
260
  export interface WorkerConfig {
117
261
  /** Module whose default export is `defineWorker(...)`. Default `src/worker.ts`. */
118
262
  entry?: string;
119
- /** 1-900. Default 60. */
263
+ /** 1-900. Default 60. Handlers can set their own (`HandlerConfig`). */
264
+ timeoutSeconds?: number;
265
+ /** 128-10240. Default 512. Handlers can set their own (`HandlerConfig`). */
266
+ memoryMb?: number;
267
+ }
268
+
269
+ /**
270
+ * A queue, event or cron handler's own Lambda settings, for handlers whose
271
+ * needs differ from the rest (a big parse, a long idle wait). A handler that
272
+ * sets either runs in a function of its own, from the same worker bundle;
273
+ * the one it doesn't set is the worker's.
274
+ */
275
+ export interface HandlerConfig {
276
+ /** 1-900. Default: the worker's `timeoutSeconds`. */
120
277
  timeoutSeconds?: number;
121
- /** 128-10240. Default 512. */
278
+ /** 128-10240. Default: the worker's `memoryMb`. */
122
279
  memoryMb?: number;
123
280
  }
124
281
 
125
- /** Declare one with `queue<Body>({ ... })` to type what is sent and received. */
126
- export interface QueueConfig<Body = unknown> extends Payload<Body> {
127
- /** Messages per worker invocation, 1-10. Default 10. */
128
- batchSize?: number;
129
- /** Defaults to 6x the worker timeout, as AWS recommends for Lambda consumers. */
130
- visibilityTimeoutSeconds?: number;
131
- /** Deliveries before a message moves to the dead-letter queue, 1-1000. Default 5. */
132
- maxReceiveCount?: number;
133
- /** Max concurrent worker invocations draining this queue, 2-1000. */
282
+ /** How often a failed run is tried again, for every kind of handler. */
283
+ export interface RetryConfig {
284
+ /**
285
+ * Runs before the job goes to the stage's dead-letter queue, 1-100: the
286
+ * first, then retries 1, 2, 4 … minutes apart (at most an hour). Default 5
287
+ * for queues, 3 for events and crons.
288
+ */
289
+ maxAttempts?: number;
290
+ }
291
+
292
+ /**
293
+ * Declare one with `queue<Body>({ ... })` to type what is sent and received.
294
+ * Each message is one run of its handler, at least once and in no set order.
295
+ */
296
+ export interface QueueConfig<Body = unknown> extends Payload<Body>, HandlerConfig, RetryConfig {
297
+ /**
298
+ * At most this many runs at once, 1-1000. Setting it runs the handler in a
299
+ * function of its own with that much reserved Lambda concurrency; messages
300
+ * past it wait (up to six hours) instead of failing.
301
+ */
134
302
  concurrency?: number;
135
303
  }
136
304
 
305
+ /** Event handler options. */
306
+ export type EventOptions = HandlerConfig & RetryConfig;
307
+
137
308
  /** Declare one with `event<Detail>()` to type what is published and handled. */
138
- export type EventConfig<Detail = unknown> = Payload<Detail>;
309
+ export type EventConfig<Detail = unknown> = Payload<Detail> & EventOptions;
310
+
311
+ /**
312
+ * 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`; the object form adds
313
+ * a timezone or the handler's own settings.
314
+ */
315
+ export type CronConfig = string | CronSchedule;
316
+
317
+ export interface CronSchedule extends HandlerConfig, RetryConfig {
318
+ schedule: string;
319
+ /** IANA name, e.g. `America/Los_Angeles`. Default UTC. */
320
+ timezone?: string;
321
+ }
322
+
323
+ /** Declare one with `channel<Event>()` to type what is published and received. */
324
+ export type ChannelConfig<Event = unknown> = Payload<Event>;
325
+
326
+ /** A file store. `{}` is a private store whose files are kept until deleted. */
327
+ export interface StoreConfig {
328
+ /**
329
+ * Serve the store's files from the edge at `/__platform/storage/<store>/<key>`
330
+ * on the app's host, to anyone with the URL (`auth.required` doesn't cover
331
+ * it), with no server in the path. Files are cached as their `cacheControl`
332
+ * says; without one, browsers revalidate on each use. Default `false`.
333
+ */
334
+ public?: boolean;
335
+ /** Delete files not written for this many days, 1-3650. Checked daily. Default: kept until deleted. */
336
+ expireAfterDays?: number;
337
+ }
338
+
339
+ /**
340
+ * A long-running process: it holds connections open (WebSocket or
341
+ * server-sent-event sources) and writes what it receives to the db, storage,
342
+ * queues or realtime. One instance per stage, restarted when it crashes and
343
+ * replaced on each deploy. Unlike everything else it is billed while it runs:
344
+ * about $6 a month at the default size on Spot.
345
+ */
346
+ export interface ServiceConfig {
347
+ /** Module whose default export is `defineService(...)` from `@ericminassian/platform`. */
348
+ entry: string;
349
+ /** vCPUs: 0.25 (default), 0.5, 1, 2 or 4. */
350
+ cpu?: FargateCpu;
351
+ /**
352
+ * Memory in MB, one of the sizes Fargate pairs with `cpu`: 512, 1024 or
353
+ * 2048 for 0.25 vCPU; 1024-4096 for 0.5; 2048-8192 for 1; 4096-16384 for 2;
354
+ * 8192-30720 for 4 (steps of 1024). Default 512.
355
+ */
356
+ memoryMb?: number;
357
+ /**
358
+ * Run on Fargate Spot, about 70% cheaper. AWS may reclaim it with two
359
+ * minutes' notice (the service gets SIGTERM) and the platform starts a
360
+ * replacement. Default `true`.
361
+ */
362
+ spot?: boolean;
363
+ /** Minutes a preview stage runs it after each deploy before stopping it; 0 means never. Default 30. */
364
+ previewMinutes?: number;
365
+ }
139
366
 
140
- /** 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`. */
141
- export type CronConfig = string | { schedule: string; timezone?: string };
367
+ /**
368
+ * Live updates pushed to browsers. The server and worker publish; browsers
369
+ * subscribe (they never publish). Events aren't stored: a browser that was
370
+ * away re-reads what it shows after reconnecting.
371
+ */
372
+ export interface RealtimeConfig {
373
+ /**
374
+ * Who may subscribe: anyone (`public`, the default), or signed-in users of
375
+ * this app (`signed-in`, needs `auth` and `web.server`).
376
+ */
377
+ subscribe?: 'public' | 'signed-in';
378
+ /**
379
+ * Channels and their event types: `board: channel<BoardEvent>()`, or
380
+ * `'boards/*': channel<BoardEvent>()` for every channel below `boards/`.
381
+ * Names are 1-4 segments of a-z, 0-9 and hyphens. `'user/*'` channels
382
+ * (`user/<user id>/...`) are private to that user (`signed-in` only).
383
+ */
384
+ channels: { readonly [pattern: string]: ChannelConfig };
385
+ }
386
+
387
+ /**
388
+ * Transactional email, sent from `<app>@mail.<platform zone>` (previews from
389
+ * `<app>--<stage>@…`). Replies need `replyTo`: the sending address takes no mail.
390
+ */
391
+ export interface EmailConfig {
392
+ /** Display name recipients see, e.g. `Todo` → `"Todo" <todo@mail…>`. */
393
+ name?: string;
394
+ /**
395
+ * Recipients per UTC day (default 200), up to the platform's
396
+ * `limits.emailsPerDay`. Previews and `plat dev` get at most 50.
397
+ */
398
+ dailyLimit?: number;
399
+ }
142
400
 
143
401
  export interface AppConfig {
144
402
  /** 3-30 chars of a-z, 0-9 and single hyphens; also the app's host name. */
@@ -157,12 +415,23 @@ export interface AppConfig {
157
415
  events?: readonly string[] | { readonly [type: string]: EventConfig };
158
416
  /** Scheduled jobs. Each needs a handler in the worker. */
159
417
  crons?: { readonly [name: string]: CronConfig };
160
- /** Named file stores. */
161
- storage?: readonly string[];
418
+ /**
419
+ * Named file stores: `{ uploads: {}, snapshots: { public: true, expireAfterDays: 7 } }`.
420
+ * A list of names (`['uploads']`) declares private stores. Keys are 1-20
421
+ * chars of a-z, 0-9 and hyphens. A store can't switch between public and
422
+ * private once it has files: declare a new one instead.
423
+ */
424
+ storage?: readonly string[] | { readonly [name: string]: StoreConfig };
162
425
  /** Secret names like `STRIPE_KEY`; values are set with `plat secrets set`. */
163
426
  secrets?: readonly string[];
164
427
  /** Plain, non-secret configuration exposed as environment variables. */
165
428
  env?: { readonly [name: string]: string };
429
+ /** Live updates pushed to browsers on typed channels. */
430
+ realtime?: RealtimeConfig;
431
+ /** Send email with the SDK's `Email` service: `true`, or `{ name, dailyLimit }`. */
432
+ email?: boolean | EmailConfig;
433
+ /** Long-running processes, e.g. stream ingest. Keys are 1-20 chars of a-z, 0-9 and hyphens. */
434
+ services?: { readonly [name: string]: ServiceConfig };
166
435
  }
167
436
 
168
437
  /**
@@ -189,34 +458,68 @@ export function defineApp<const T extends AppConfig>(config: T & Exact<T, AppCon
189
458
  return config;
190
459
  }
191
460
 
192
- /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ batchSize: 5 }) }`. */
461
+ /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ maxAttempts: 3 }) }`. */
193
462
  export function queue<Body>(options: QueueConfig = {}): QueueConfig<Body> {
194
463
  return options as QueueConfig<Body>;
195
464
  }
196
465
 
197
466
  /** An event subscription whose detail is `Detail`: `events: { 'todo.created': event<TodoCreated>() }`. */
198
- export function event<Detail>(): EventConfig<Detail> {
467
+ export function event<Detail>(options: EventOptions = {}): EventConfig<Detail> {
468
+ return options;
469
+ }
470
+
471
+ /** A realtime channel whose events are `Event`: `realtime: { channels: { board: channel<BoardEvent>() } }`. */
472
+ export function channel<Event>(): ChannelConfig<Event> {
199
473
  return {};
200
474
  }
201
475
 
202
476
  // ---------------------------------------------------------------------------
203
477
 
204
- /** Manifest with defaults applied and derived fields normalized. */
205
- export interface ResolvedManifest {
206
- name: string;
207
- description?: string;
208
- web?: z.output<typeof WebSchema>;
478
+ /**
479
+ * Manifest with defaults applied and derived fields normalized: what
480
+ * deployments store. Decoding fills defaults for fields added since a stored
481
+ * manifest was written, so earlier deployments keep decoding.
482
+ */
483
+ export const ResolvedManifest = Schema.Struct({
484
+ name: Schema.String,
485
+ description: Schema.optional(Schema.String),
486
+ web: Schema.optional(WebSchema),
209
487
  /** Present when any queue, event subscription or cron exists. */
210
- worker?: z.output<typeof WorkerSchema>;
211
- auth: { enabled: boolean; required: boolean };
212
- db: boolean;
213
- queues: Record<string, z.output<typeof QueueSchema> & { visibilityTimeoutSeconds: number }>;
214
- events: string[];
215
- crons: Record<string, { schedule: string; timezone?: string }>;
216
- storage: string[];
217
- secrets: string[];
218
- env: Record<string, string>;
219
- }
488
+ worker: Schema.optional(WorkerSchema),
489
+ auth: Schema.Struct({ enabled: Schema.Boolean, required: Schema.Boolean }),
490
+ db: Schema.Boolean,
491
+ queues: Schema.Record(Schema.String, Schema.Struct(QueueFields)),
492
+ events: Schema.Array(Schema.String),
493
+ /**
494
+ * Each event handler's own settings, by type. Absent from deployments
495
+ * recorded before handlers had any. A field of its own, so clients that
496
+ * know only `events` keep decoding manifests.
497
+ */
498
+ eventOptions: Schema.Record(Schema.String, HandlerSchema).pipe(orElse({})),
499
+ crons: Schema.Record(Schema.String, CronScheduleSchema),
500
+ /** Every store's name. */
501
+ storage: Schema.Array(Schema.String),
502
+ /**
503
+ * Each store's options, by name. Absent from deployments recorded before
504
+ * stores had any: those stores are private and kept until deleted. A field
505
+ * of its own, so clients that know only `storage` keep decoding manifests.
506
+ */
507
+ storageOptions: Schema.Record(
508
+ Schema.String,
509
+ Schema.Struct({ public: Schema.Boolean, expireAfterDays: Schema.optional(Schema.Finite) }),
510
+ ).pipe(orElse({})),
511
+ secrets: Schema.Array(Schema.String),
512
+ env: Schema.Record(Schema.String, Schema.String),
513
+ /** Present when the stage has a channel namespace. `channels` are the declared patterns. */
514
+ realtime: Schema.optional(
515
+ Schema.Struct({ subscribe: RealtimeSubscribeSchema, channels: Schema.Array(Schema.String) }),
516
+ ),
517
+ /** Present when the stage sends email. `dailyLimit` is the declared one (prod's). */
518
+ email: Schema.optional(Schema.Struct({ name: Schema.optional(Schema.String), dailyLimit: Schema.Finite })),
519
+ /** Long-running services, with defaults applied. */
520
+ services: Schema.Record(Schema.String, ServiceSchema).pipe(orElse({})),
521
+ });
522
+ export type ResolvedManifest = typeof ResolvedManifest.Type;
220
523
 
221
524
  export class ManifestError extends Error {
222
525
  readonly issues: string[];
@@ -226,32 +529,62 @@ export class ManifestError extends Error {
226
529
  }
227
530
  }
228
531
 
532
+ const validateManifest = Schema.toStandardSchemaV1(ManifestSchema, { parseOptions: { errors: 'all' } })[
533
+ '~standard'
534
+ ].validate;
535
+
229
536
  export function parseManifest(input: unknown): ResolvedManifest {
230
- const parsed = ManifestSchema.safeParse(input);
231
- if (!parsed.success) {
232
- throw new ManifestError(parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`));
537
+ const result = validateManifest(input);
538
+ // The schema has no asynchronous checks, so validation is synchronous.
539
+ if (result instanceof Promise) throw new Error('manifest validation must be synchronous');
540
+ if (result.issues) {
541
+ throw new ManifestError(
542
+ result.issues.map((i) => {
543
+ const path = (i.path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
544
+ return `${path || '(root)'}: ${i.message}`;
545
+ }),
546
+ );
233
547
  }
234
- return resolveManifest(parsed.data);
548
+ return resolveManifest(result.value);
235
549
  }
236
550
 
237
551
  export function resolveManifest(m: Manifest): ResolvedManifest {
238
- const events = Array.isArray(m.events) ? m.events : Object.keys(m.events);
552
+ const eventOptions: ResolvedManifest['eventOptions'] = isEventList(m.events)
553
+ ? Object.fromEntries(m.events.map((type) => [type, {}]))
554
+ : m.events;
555
+ const events = Object.keys(eventOptions);
239
556
  const needsWorker =
240
557
  Object.keys(m.queues).length > 0 || events.length > 0 || Object.keys(m.crons).length > 0;
241
- const worker = m.worker ?? (needsWorker ? WorkerSchema.parse({}) : undefined);
558
+ const worker = m.worker ?? (needsWorker ? Schema.decodeUnknownSync(WorkerSchema)({}) : undefined);
242
559
  const auth =
243
560
  typeof m.auth === 'boolean'
244
561
  ? { enabled: m.auth, required: false }
245
562
  : { enabled: true, required: m.auth.required };
246
- const queues: ResolvedManifest['queues'] = {};
247
- for (const [key, q] of Object.entries(m.queues)) {
248
- queues[key] = {
249
- ...q,
250
- visibilityTimeoutSeconds: q.visibilityTimeoutSeconds ?? (worker?.timeoutSeconds ?? 60) * 6,
251
- };
252
- }
253
- const crons: ResolvedManifest['crons'] = {};
254
- for (const [key, c] of Object.entries(m.crons)) crons[key] = typeof c === 'string' ? { schedule: c } : c;
563
+ // Validation refused the removed queue settings, so only the current ones remain.
564
+ const queues: ResolvedManifest['queues'] = Object.fromEntries(
565
+ Object.entries(m.queues).map(([key, q]) => [
566
+ key,
567
+ {
568
+ maxAttempts: q.maxAttempts,
569
+ ...(q.concurrency !== undefined ? { concurrency: q.concurrency } : {}),
570
+ ...(q.timeoutSeconds !== undefined ? { timeoutSeconds: q.timeoutSeconds } : {}),
571
+ ...(q.memoryMb !== undefined ? { memoryMb: q.memoryMb } : {}),
572
+ },
573
+ ]),
574
+ );
575
+ const email: ResolvedManifest['email'] =
576
+ m.email === false
577
+ ? undefined
578
+ : {
579
+ ...(m.email !== true && m.email.name ? { name: m.email.name } : {}),
580
+ dailyLimit: (m.email !== true && m.email.dailyLimit) || EMAIL_DEFAULT_DAILY_LIMIT,
581
+ };
582
+ const crons: ResolvedManifest['crons'] = Object.fromEntries(
583
+ Object.entries(m.crons).map(([key, c]) => [key, typeof c === 'string' ? { schedule: c } : c]),
584
+ );
585
+ const stores: Record<string, typeof StoreSchema.Type> = isStoreList(m.storage)
586
+ ? Object.fromEntries(m.storage.map((name) => [name, { public: false }]))
587
+ : m.storage;
255
588
  return {
256
589
  name: m.name,
257
590
  ...(m.description ? { description: m.description } : {}),
@@ -260,10 +593,105 @@ export function resolveManifest(m: Manifest): ResolvedManifest {
260
593
  auth,
261
594
  db: m.db,
262
595
  queues,
263
- events: [...new Set(events)],
596
+ events,
597
+ eventOptions,
264
598
  crons,
265
- storage: [...new Set(m.storage)],
599
+ storage: Object.keys(stores),
600
+ storageOptions: stores,
266
601
  secrets: [...new Set(m.secrets)],
267
602
  env: m.env,
603
+ ...(m.realtime
604
+ ? { realtime: { subscribe: m.realtime.subscribe, channels: Object.keys(m.realtime.channels) } }
605
+ : {}),
606
+ ...(email ? { email } : {}),
607
+ services: m.services,
608
+ };
609
+ }
610
+
611
+ const isStoreList = (storage: Manifest['storage']): storage is readonly string[] => Array.isArray(storage);
612
+ const isEventList = (events: Manifest['events']): events is readonly string[] => Array.isArray(events);
613
+
614
+ /** The stores the edge serves (`public: true`). */
615
+ export function publicStores(m: Pick<ResolvedManifest, 'storage' | 'storageOptions'>): string[] {
616
+ return m.storage.filter((name) => m.storageOptions[name]?.public === true);
617
+ }
618
+
619
+ // ---------------------------------------------------------------------------
620
+ // Worker functions
621
+
622
+ const HANDLER_KINDS = ['queue', 'event', 'cron'] as const;
623
+ export type HandlerKind = (typeof HANDLER_KINDS)[number];
624
+
625
+ /** A queue, event or cron handler and the settings it runs with. */
626
+ export interface HandlerSettings {
627
+ kind: HandlerKind;
628
+ /** The queue or cron key, or the event type. */
629
+ name: string;
630
+ timeoutSeconds: number;
631
+ memoryMb: number;
632
+ /** Runs before its job is dead-lettered. */
633
+ maxAttempts: number;
634
+ /** Reserved concurrency of its function (queues that set `concurrency`). */
635
+ concurrency?: number;
636
+ /**
637
+ * It sets its own memory, timeout or (a queue) concurrency, so it runs in a
638
+ * function of its own (`names.handlerFunction`).
639
+ */
640
+ own: boolean;
641
+ }
642
+
643
+ type WorkerManifest = Pick<ResolvedManifest, 'worker' | 'queues' | 'eventOptions' | 'crons'>;
644
+
645
+ /** Each kind's handlers, by name, with what they set. */
646
+ const declaredHandlers = (
647
+ m: WorkerManifest,
648
+ ): Record<
649
+ HandlerKind,
650
+ { readonly [name: string]: HandlerConfig & { maxAttempts?: number; concurrency?: number } }
651
+ > => ({
652
+ queue: m.queues,
653
+ event: m.eventOptions,
654
+ cron: m.crons,
655
+ });
656
+
657
+ /** A handler's settings: its own, and the worker's for any it doesn't set. */
658
+ export function handlerSettings(m: WorkerManifest, kind: HandlerKind, name: string): HandlerSettings {
659
+ const own = declaredHandlers(m)[kind][name] ?? {};
660
+ // Reserved concurrency is per function, so a queue that caps it needs one to itself.
661
+ const concurrency = kind === 'queue' ? own.concurrency : undefined;
662
+ return {
663
+ kind,
664
+ name,
665
+ timeoutSeconds: own.timeoutSeconds ?? m.worker?.timeoutSeconds ?? WORKER_TIMEOUT_SECONDS,
666
+ memoryMb: own.memoryMb ?? m.worker?.memoryMb ?? WORKER_MEMORY_MB,
667
+ maxAttempts: own.maxAttempts ?? DEFAULT_ATTEMPTS[kind],
668
+ ...(concurrency !== undefined ? { concurrency } : {}),
669
+ own: own.timeoutSeconds !== undefined || own.memoryMb !== undefined || concurrency !== undefined,
268
670
  };
269
671
  }
672
+
673
+ /** Every queue, event and cron handler with its settings. */
674
+ export function workerHandlers(m: WorkerManifest): HandlerSettings[] {
675
+ const declared = declaredHandlers(m);
676
+ return HANDLER_KINDS.flatMap((kind) =>
677
+ Object.keys(declared[kind]).map((name) => handlerSettings(m, kind, name)),
678
+ );
679
+ }
680
+
681
+ /** The handlers that run in functions of their own. The worker's function runs the rest. */
682
+ export function ownFunctionHandlers(m: WorkerManifest): HandlerSettings[] {
683
+ return workerHandlers(m).filter((h) => h.own);
684
+ }
685
+
686
+ /** The Lambda function a handler runs in: its own, or the worker's. */
687
+ export function handlerFunctionName(
688
+ app: string,
689
+ stage: string,
690
+ m: WorkerManifest,
691
+ kind: HandlerKind,
692
+ name: string,
693
+ ): string {
694
+ return handlerSettings(m, kind, name).own
695
+ ? names.handlerFunction(app, stage, kind, name)
696
+ : names.workerFunction(app, stage);
697
+ }