@fabrika/provider-cloudflare 0.8.2 → 0.9.0-cloudflare.2

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 (45) hide show
  1. package/package.json +16 -15
  2. package/src/bounds.ts +142 -4
  3. package/src/cli.ts +14 -0
  4. package/src/command.ts +8 -4
  5. package/src/contract-support.ts +118 -0
  6. package/src/control.ts +37 -119
  7. package/src/index.ts +1 -1
  8. package/src/installation/init.ts +11 -18
  9. package/src/installation/templates/README.md +21 -4
  10. package/src/installation/templates/platform.yml +6 -0
  11. package/src/managed-secrets.ts +61 -0
  12. package/src/plan.ts +11 -3
  13. package/src/provider.ts +309 -54
  14. package/src/proxy-worker.ts +33 -13
  15. package/src/proxy.ts +48 -16
  16. package/src/runner-protocol.ts +16 -1
  17. package/src/spa-assets.ts +150 -0
  18. package/types/src/assets.d.ts +8 -0
  19. package/types/src/authoring.d.ts +17 -0
  20. package/types/src/bounds.d.ts +81 -0
  21. package/types/src/checkout.d.ts +7 -0
  22. package/types/src/cli-args.d.ts +25 -0
  23. package/types/src/cli.d.ts +8 -0
  24. package/types/src/codec.d.ts +8 -0
  25. package/types/src/collaborators.d.ts +52 -0
  26. package/types/src/command.d.ts +49 -0
  27. package/types/src/config-schema.d.ts +9 -0
  28. package/types/src/contract-support.d.ts +39 -0
  29. package/types/src/control.d.ts +468 -0
  30. package/types/src/index.d.ts +18 -0
  31. package/types/src/installation/cloudflare.d.ts +40 -0
  32. package/types/src/installation/envfile.d.ts +39 -0
  33. package/types/src/installation/index.d.ts +2 -0
  34. package/types/src/installation/init-options.d.ts +59 -0
  35. package/types/src/installation/init.d.ts +114 -0
  36. package/types/src/installation/installation.d.ts +2 -0
  37. package/types/src/installation/scaffold.d.ts +39 -0
  38. package/types/src/managed-secrets.d.ts +19 -0
  39. package/types/src/plan.d.ts +21 -0
  40. package/types/src/provider.d.ts +58 -0
  41. package/types/src/proxy-worker.d.ts +15 -0
  42. package/types/src/proxy.d.ts +72 -0
  43. package/types/src/runner-protocol.d.ts +121 -0
  44. package/types/src/schema.d.ts +17 -0
  45. package/types/src/spa-assets.d.ts +27 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-cloudflare",
3
- "version": "0.8.2",
3
+ "version": "0.9.0-cloudflare.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,27 +12,28 @@
12
12
  },
13
13
  "files": [
14
14
  "src",
15
- "!src/**/__tests__/**"
15
+ "!src/**/__tests__/**",
16
+ "types"
16
17
  ],
17
18
  "exports": {
18
19
  ".": {
19
20
  "bun": "./src/index.ts",
20
- "types": "./src/index.ts",
21
+ "types": "./types/src/index.d.ts",
21
22
  "default": "./src/index.ts"
22
23
  },
23
24
  "./cli": {
24
25
  "bun": "./src/cli.ts",
25
- "types": "./src/cli.ts",
26
+ "types": "./types/src/cli.d.ts",
26
27
  "default": "./src/cli.ts"
27
28
  },
28
29
  "./runner": {
29
30
  "bun": "./src/control.ts",
30
- "types": "./src/control.ts",
31
+ "types": "./types/src/control.d.ts",
31
32
  "default": "./src/control.ts"
32
33
  },
33
34
  "./installation": {
34
35
  "bun": "./src/installation/index.ts",
35
- "types": "./src/installation/index.ts",
36
+ "types": "./types/src/installation/index.d.ts",
36
37
  "default": "./src/installation/index.ts"
37
38
  }
38
39
  },
@@ -42,15 +43,15 @@
42
43
  },
43
44
  "dependencies": {
44
45
  "zod": "^3.25.76",
45
- "@fabrika/app": "0.8.2",
46
- "@fabrika/auth": "0.8.2",
47
- "@fabrika/auth-core": "0.8.2",
48
- "@fabrika/check": "0.8.2",
49
- "@fabrika/email": "0.8.2",
50
- "@fabrika/iam-contract": "0.8.2",
51
- "@fabrika/installation-init": "0.8.2",
52
- "@fabrika/proxy-core": "0.8.2",
53
- "@fabrika/provider-contract": "0.8.2",
46
+ "@fabrika/app": "0.9.0-cloudflare.2",
47
+ "@fabrika/auth": "0.9.0-cloudflare.2",
48
+ "@fabrika/auth-core": "0.9.0-cloudflare.2",
49
+ "@fabrika/check": "0.9.0-cloudflare.2",
50
+ "@fabrika/email": "0.9.0-cloudflare.2",
51
+ "@fabrika/iam-contract": "0.9.0-cloudflare.2",
52
+ "@fabrika/installation-init": "0.9.0-cloudflare.2",
53
+ "@fabrika/proxy-core": "0.9.0-cloudflare.2",
54
+ "@fabrika/provider-contract": "0.9.0-cloudflare.2",
54
55
  "oblaka-iac": "^0.0.18"
55
56
  }
56
57
  }
package/src/bounds.ts CHANGED
@@ -1,11 +1,12 @@
1
- import { type AppEnvironment, FRAMEWORK_VARIABLE_NAMES, isFrameworkVariableName, parseAppEnvironmentId } from '@fabrika/auth-core'
1
+ import { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_FILES_BINDING, GENERATED_ENTRY_FILE } from '@fabrika/app/build'
2
+ import { type AppEnvironment, appEnvironmentId, FRAMEWORK_VARIABLE_NAMES, isFrameworkVariableName, parseAppEnvironmentId } from '@fabrika/auth-core'
2
3
  import { isProxyHost } from '@fabrika/proxy-core/manifest'
3
- import { resolve } from 'node:path'
4
+ import { dirname, resolve } from 'node:path'
4
5
  import type { GeneratedConfig, Worker } from 'oblaka-iac'
5
6
  import { CloudflareClient } from 'oblaka-iac/src/client'
6
7
  import { ResourceProcessor } from 'oblaka-iac/src/commands/resource-processor'
7
8
  import { PLATFORM_RESOURCE_NAMES } from './plan'
8
- import { CLOUDFLARE_PROXY_WORKER_DIR, IAM_APPLICATION_ENTRYPOINT, IAM_SERVICE } from './proxy'
9
+ import { CLOUDFLARE_PROXY_WORKER_DIR, IAM_APPLICATION_ENTRYPOINT, IAM_SERVICE, PROXY_MANIFEST_DEFINE } from './proxy'
9
10
 
10
11
  type WranglerConfig = GeneratedConfig['config']
11
12
 
@@ -38,8 +39,31 @@ export interface DeploymentBounds {
38
39
  readonly application: Readonly<Record<string, string>>
39
40
  readonly proxy: Readonly<Record<string, string>> | null
40
41
  }
42
+ /** The `define` literal of the manifest the deployer baked into its proxy Worker, or null when it built none. */
43
+ readonly proxyManifest: string | null
44
+ /** What the platform gives a contract application's Worker (ADR-0065), or null outside one. */
45
+ readonly application: ApplicationRuntime | null
41
46
  }
42
47
 
48
+ /** The Durable Object, files bucket and minute tick of a contract application's Worker; the application authors none of them. */
49
+ export interface ApplicationRuntime {
50
+ /** The remote name of the environment's files bucket. */
51
+ readonly filesBucket: string
52
+ /** The cron triggers the Worker carries: the minute tick when the contract has a job or a file kind, else an empty list. */
53
+ readonly crons: readonly string[]
54
+ /**
55
+ * The absolute path of the entry the deploy regenerates, which the Worker's `main` must name (`pinsGeneratedEntry`), or
56
+ * null for a release whose Worker keeps its authored `main`.
57
+ */
58
+ readonly entry: string | null
59
+ }
60
+
61
+ /**
62
+ * The one migration of the application's object. Its tag is fixed: Cloudflare records the last tag a script applied, so
63
+ * a tag that moved would migrate the class twice. The deployer binds the object first, so oblaka numbers it `v0001`.
64
+ */
65
+ const APPLICATION_OBJECT_MIGRATION = { tag: 'v0001', new_sqlite_classes: [CLOUDFLARE_APPLICATION_CLASS] } as const
66
+
43
67
  /** The framework variables among a Worker's `vars`, as the deployer wrote them. */
44
68
  export const frameworkValues = (vars: Readonly<Record<string, unknown>> | undefined): Record<string, string> => {
45
69
  const values: Record<string, string> = {}
@@ -79,6 +103,9 @@ const CONFIG_KEYS: ReadonlySet<string> = new Set([
79
103
  'workflows',
80
104
  ])
81
105
 
106
+ /** The platform proxy's config also carries the `define` that bakes its manifest into the bundle. */
107
+ const PROXY_CONFIG_KEYS: ReadonlySet<string> = new Set([...CONFIG_KEYS, 'define'])
108
+
82
109
  /** Everything wrangler reads out of `assets`. `directory` is the only one that names a path. */
83
110
  const ASSETS_KEYS: ReadonlySet<string> = new Set(['binding', 'directory', 'html_handling', 'not_found_handling', 'run_worker_first'])
84
111
 
@@ -226,12 +253,29 @@ const assertServices = (worker: string, config: WranglerConfig, names: Applicati
226
253
  `cloudflare: Worker \`${worker}\` binds \`${service}\` to ${bound}; an application binds \`${IAM_APPLICATION_ENTRYPOINT}\` (use \`iamServiceReference()\`)`,
227
254
  )
228
255
  }
256
+ assertIamIdentity(worker, binding, field(entry, 'props'), names)
229
257
  continue
230
258
  }
231
259
  assertOwnRemote(`Worker \`${worker}\` binds service`, service, names)
232
260
  }
233
261
  }
234
262
 
263
+ /**
264
+ * IAM reads a binding's `props.app` as the calling application (ADR-0067 §3), so an IAM binding names exactly this
265
+ * deployment's IAM application id and carries nothing else. The deployer writes the `IAM` binding that way.
266
+ */
267
+ const assertIamIdentity = (worker: string, binding: unknown, props: unknown, names: ApplicationNames): void => {
268
+ const app = appEnvironmentId(names.self.app, names.self.env)
269
+ const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []
270
+ if (keys.length !== 1 || field(props, 'app') !== app) {
271
+ throw new Error(
272
+ `cloudflare: Worker \`${worker}\` binds IAM as \`${
273
+ String(binding)
274
+ }\` without naming its own application \`${app}\`; only the deployer's \`IAM\` binding reaches IAM`,
275
+ )
276
+ }
277
+ }
278
+
235
279
  /** Every remote name a config's bindings carry, beside the services. */
236
280
  const assertResourceBindings = (worker: string, config: WranglerConfig, names: ApplicationNames): void => {
237
281
  const binds = (kind: string, remote: unknown): void => assertOwnRemote(`Worker \`${worker}\` binds ${kind}`, remote, names)
@@ -341,6 +385,95 @@ const assertFrameworkVariables = (worker: string, vars: unknown, expected: Reado
341
385
  }
342
386
  }
343
387
 
388
+ /** The proxy's `define` is exactly the manifest the deployer baked: nothing else is substituted into its bundle. */
389
+ const assertBakedManifest = (worker: string, define: unknown, expected: string | null): void => {
390
+ const names = typeof define === 'object' && define !== null && !Array.isArray(define) ? Object.keys(define) : null
391
+ const exact = expected === null
392
+ ? define === undefined
393
+ : names?.length === 1 && names[0] === PROXY_MANIFEST_DEFINE && field(define, PROXY_MANIFEST_DEFINE) === expected
394
+ if (!exact) {
395
+ throw new Error(`cloudflare: proxy Worker \`${worker}\` does not carry exactly the manifest Fabrika baked into it (\`define\`)`)
396
+ }
397
+ }
398
+
399
+ const isApplicationMigration = (migration: unknown): boolean => {
400
+ const keys = typeof migration === 'object' && migration !== null ? Object.keys(migration).sort() : []
401
+ const classes = field(migration, 'new_sqlite_classes')
402
+ return keys.join(',') === 'new_sqlite_classes,tag' && field(migration, 'tag') === APPLICATION_OBJECT_MIGRATION.tag
403
+ && Array.isArray(classes) && classes.length === 1 && classes[0] === CLOUDFLARE_APPLICATION_CLASS
404
+ }
405
+
406
+ const namesApplicationClass = (migration: unknown): boolean => JSON.stringify(migration).includes(JSON.stringify(CLOUDFLARE_APPLICATION_CLASS))
407
+
408
+ const isPlatformTriggers = (triggers: unknown, crons: readonly string[]): boolean => {
409
+ const keys = typeof triggers === 'object' && triggers !== null ? Object.keys(triggers) : []
410
+ const written = field(triggers, 'crons')
411
+ return keys.length === 1 && Array.isArray(written) && written.length === crons.length && crons.every((cron, index) => written[index] === cron)
412
+ }
413
+
414
+ /**
415
+ * A contract application's Worker binds its own object (`FABRIKA_APPLICATION`, the class the generated entry exports)
416
+ * under the one fixed migration, the environment's files bucket, and exactly the platform's cron triggers.
417
+ */
418
+ const assertApplicationRuntime = (worker: string, config: WranglerConfig, runtime: ApplicationRuntime): void => {
419
+ const objects = entries(config.durable_objects?.bindings, worker, 'durable_objects.bindings').filter((entry) =>
420
+ field(entry, 'name') === CLOUDFLARE_APPLICATION_BINDING || field(entry, 'class_name') === CLOUDFLARE_APPLICATION_CLASS
421
+ )
422
+ const object = objects[0]
423
+ if (
424
+ objects.length !== 1 || field(object, 'name') !== CLOUDFLARE_APPLICATION_BINDING || field(object, 'class_name') !== CLOUDFLARE_APPLICATION_CLASS
425
+ || field(object, 'script_name') !== undefined
426
+ ) {
427
+ throw new Error(
428
+ `cloudflare: application Worker \`${worker}\` must bind \`${CLOUDFLARE_APPLICATION_BINDING}\` once, to its own \`${CLOUDFLARE_APPLICATION_CLASS}\`; the platform writes that binding`,
429
+ )
430
+ }
431
+ const migrations = entries(config.migrations, worker, 'migrations')
432
+ if (!isApplicationMigration(migrations[0]) || migrations.slice(1).some(namesApplicationClass)) {
433
+ throw new Error(
434
+ `cloudflare: application Worker \`${worker}\` must open its migrations with \`${APPLICATION_OBJECT_MIGRATION.tag}\` creating \`${CLOUDFLARE_APPLICATION_CLASS}\` and name the class nowhere else; a committed \`wrangler.jsonc\` with a history of its own cannot be deployed`,
435
+ )
436
+ }
437
+ const files = entries(config.r2_buckets, worker, 'r2_buckets').filter((entry) => field(entry, 'binding') === CLOUDFLARE_FILES_BINDING)
438
+ if (files.length !== 1 || field(files[0], 'bucket_name') !== runtime.filesBucket) {
439
+ throw new Error(`cloudflare: application Worker \`${worker}\` must bind \`${CLOUDFLARE_FILES_BINDING}\` once, to \`${runtime.filesBucket}\``)
440
+ }
441
+ if (!isPlatformTriggers(config.triggers, runtime.crons)) {
442
+ throw new Error(`cloudflare: application Worker \`${worker}\` sets \`triggers\` the platform did not write; its cron triggers are the platform's`)
443
+ }
444
+ }
445
+
446
+ /**
447
+ * A pinned release's Worker runs the entry the deploy regenerates, and nothing that entry does not export: a hand-written
448
+ * `main` would skip the contract digest check, the hop secret and the framework's scheduling.
449
+ */
450
+ const assertGeneratedEntry = (worker: string, generated: GeneratedConfig, cwd: string, entry: string): void => {
451
+ const config = generated.config
452
+ const main: unknown = config.main
453
+ if (typeof main !== 'string' || resolve(dirname(resolve(cwd, generated.path)), main) !== entry) {
454
+ throw new Error(
455
+ `cloudflare: application Worker \`${worker}\` runs \`${
456
+ typeof main === 'string' ? main : '(not a string)'
457
+ }\`; on its framework release it runs \`${GENERATED_ENTRY_FILE}\` beside its config, which the deploy regenerates`,
458
+ )
459
+ }
460
+ for (const key of ['workflows', 'containers'] as const) {
461
+ if (entries(config[key], worker, key).length > 0) {
462
+ throw new Error(`cloudflare: application Worker \`${worker}\` declares \`${key}\`, which the generated entry does not export`)
463
+ }
464
+ }
465
+ const object = entries(config.durable_objects?.bindings, worker, 'durable_objects.bindings').find((binding) =>
466
+ field(binding, 'name') !== CLOUDFLARE_APPLICATION_BINDING
467
+ )
468
+ if (object !== undefined) {
469
+ throw new Error(
470
+ `cloudflare: application Worker \`${worker}\` binds the Durable Object \`${
471
+ String(field(object, 'name'))
472
+ }\`; the generated entry exports only \`${CLOUDFLARE_APPLICATION_CLASS}\``,
473
+ )
474
+ }
475
+ }
476
+
344
477
  const isPlatformProxy = (generated: GeneratedConfig, bounds: DeploymentBounds): boolean =>
345
478
  bounds.proxy !== null && generated.config.name === bounds.proxy && resolve(bounds.cwd, generated.path) === PROXY_CONFIG_PATH
346
479
 
@@ -366,8 +499,9 @@ export const assertGeneratedConfigs = (configs: readonly GeneratedConfig[], boun
366
499
  for (const generated of configs) {
367
500
  const config = generated.config
368
501
  const worker = config.name ?? generated.path
502
+ const keys = isPlatformProxy(generated, bounds) ? PROXY_CONFIG_KEYS : CONFIG_KEYS
369
503
  for (const key of Object.keys(config)) {
370
- if (!CONFIG_KEYS.has(key)) {
504
+ if (!keys.has(key)) {
371
505
  throw new Error(`cloudflare: Worker \`${worker}\` sets \`${key}\`, which an app may not configure; declare resources in \`bindings\``)
372
506
  }
373
507
  }
@@ -378,6 +512,7 @@ export const assertGeneratedConfigs = (configs: readonly GeneratedConfig[], boun
378
512
  if (isPlatformProxy(generated, bounds)) {
379
513
  assertRoutedHere(worker, config, bounds)
380
514
  assertFrameworkVariables(worker, config.vars, bounds.frameworkVariables.proxy ?? {})
515
+ assertBakedManifest(worker, config.define, bounds.proxyManifest)
381
516
  continue
382
517
  }
383
518
  if (resolve(bounds.cwd, generated.path) === PROXY_CONFIG_PATH) {
@@ -385,6 +520,9 @@ export const assertGeneratedConfigs = (configs: readonly GeneratedConfig[], boun
385
520
  }
386
521
  assertUnexposed(worker, config)
387
522
  assertFrameworkVariables(worker, config.vars, bounds.frameworkVariables.application)
523
+ if (bounds.application === null) continue
524
+ assertApplicationRuntime(worker, config, bounds.application)
525
+ if (bounds.application.entry !== null) assertGeneratedEntry(worker, generated, bounds.cwd, bounds.application.entry)
388
526
  }
389
527
  }
390
528
 
package/src/cli.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  import type { DeployStepResult } from '@fabrika/provider-contract'
4
+ import type { AppCli } from '@fabrika/provider-contract/app-cli'
4
5
  import { parseCloudflareArgs } from './cli-args'
5
6
  import { deployCloudflareConfig } from './command'
6
7
  import type { CloudflareDeployResult } from './provider'
@@ -76,6 +77,19 @@ export const runCloudflareCli = async (argv: readonly string[]): Promise<void> =
76
77
  )
77
78
  }
78
79
 
80
+ /**
81
+ * What `fabrika app build` and `app deploy` run for an application on Cloudflare. A contract application's build is its
82
+ * generated Worker entry, which the `fabrika` command writes; there is nothing else to build.
83
+ */
84
+ export const appCli: AppCli = {
85
+ provider: 'cloudflare',
86
+ entryRuntime: 'cloudflare',
87
+ build: async (_argv, { contract }) => {
88
+ if (!contract) throw new Error('Cloudflare app tooling does not support `app build` for an application without fabrika.contract.ts')
89
+ },
90
+ deploy: (argv) => runCloudflareCli(['deploy', ...argv]),
91
+ }
92
+
79
93
  if (import.meta.main) {
80
94
  await runCloudflareCli(process.argv.slice(2)).catch((error: unknown) => {
81
95
  console.error(`fabrika-cloudflare-executor: ${error instanceof Error ? error.message : 'unknown error'}`)
package/src/command.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AppEnvironment, parseAppEnvironmentId } from '@fabrika/auth-core'
1
+ import { type AppEnvironment, parseAppEnvironmentId, parseManagedEnvironment } from '@fabrika/auth-core'
2
2
  import { readFile } from 'node:fs/promises'
3
3
  import { z } from 'zod'
4
4
  import type { CloudflareAppConfig } from './authoring'
@@ -8,6 +8,7 @@ import {
8
8
  APPROVED_ACCESS_FILE_ENV,
9
9
  CROSS_ORIGINS_ENV,
10
10
  INSTALLATION_APPS_ENV,
11
+ OPERATIONS_ORIGIN_ENV,
11
12
  type RunnerApprovedAccess,
12
13
  runnerApprovedAccessSchema,
13
14
  } from './runner-protocol'
@@ -42,8 +43,8 @@ const requiredValues = (names: readonly string[] | undefined): Record<string, st
42
43
  }
43
44
 
44
45
  /**
45
- * Decode `FABRIKA_IAM_RETURN_ORIGINS`, the comma-separated set the control plane projects into the
46
- * deploy environment (ADR-0022). Undefined for an absent or empty value, so a deploy with nothing to
46
+ * Decode `FABRIKA_IAM_RETURN_ORIGINS`, the comma-separated set the installation's workflow hands the
47
+ * platform's own deploy (ADR-0022). Undefined for an absent or empty value, so a deploy with nothing to
47
48
  * project leaves IAM's registry alone rather than clearing it. Part of the executor's environment
48
49
  * contract, exported for the test that pins it; not part of the package's public surface.
49
50
  */
@@ -155,11 +156,13 @@ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOpt
155
156
  const returnOrigins = parseReturnOrigins(environmentValue('FABRIKA_IAM_RETURN_ORIGINS'))
156
157
  const installationApps = parseInstallationApps(environmentValue(INSTALLATION_APPS_ENV))
157
158
  const crossOrigins = parseCrossOrigins(environmentValue(CROSS_ORIGINS_ENV))
159
+ const operationsOrigin = environmentValue(OPERATIONS_ORIGIN_ENV)
158
160
  return deploy({
159
161
  appId: loaded.config.id,
160
162
  env: options.env,
161
163
  ...(domain === undefined ? {} : { domain }),
162
164
  ...(crossOrigins === undefined ? {} : { crossOrigins }),
165
+ ...(operationsOrigin === undefined ? {} : { operationsOrigin }),
163
166
  ...(returnOrigins === undefined ? {} : { returnOrigins }),
164
167
  ...(installationApps === undefined ? {} : { installationApps }),
165
168
  ...approved,
@@ -168,7 +171,8 @@ export const deployCloudflareConfig = async (options: CloudflareCommandDeployOpt
168
171
  ...(options.stateNamespace === undefined ? {} : { stateNamespace: options.stateNamespace }),
169
172
  secrets: declaredValues(loaded.config.pipeline?.secrets),
170
173
  vars: declaredValues(loaded.config.pipeline?.vars),
171
- managedEnvironment: requiredValues(options.managedVarNames),
174
+ // The runner hands what Control handed its job; parsed here, where it enters the executor.
175
+ managedEnvironment: parseManagedEnvironment(requiredValues(options.managedVarNames)),
172
176
  dryRun: options.dryRun ?? false,
173
177
  signal: options.signal ?? new AbortController().signal,
174
178
  log: options.log ?? ((line) => console.log(line)),
@@ -0,0 +1,118 @@
1
+ import {
2
+ type ContractArtifact,
3
+ FABRIKA_TOKEN_KEYS,
4
+ isEmailTransportVariable,
5
+ isPlatformTransportVariable,
6
+ isWorkloadKeyVariable,
7
+ managedValue,
8
+ } from '@fabrika/auth-core'
9
+ import type { ProviderManagedEnvironment } from '@fabrika/provider-contract'
10
+
11
+ // Imported by `./control` (the `./runner` entry), so it stays clear of `oblaka-iac`.
12
+
13
+ /**
14
+ * The longest a procedure's or a webhook's handler may run on Cloudflare. It runs inside the object's transaction, and
15
+ * workerd resets an object whose transaction runs about 30 s (docs/reference/cloudflare-platform.md).
16
+ */
17
+ export const CLOUDFLARE_MAX_HANDLER_MS = 25_000
18
+
19
+ /**
20
+ * Refuse what a contract declares that an application on Cloudflare cannot run yet (ADR-0065): a file kind that scans
21
+ * its uploads, raw SQL (`ctx.sql`), and a handler allowed to outlive the object's transaction limit.
22
+ */
23
+ export const assertCloudflareContract = (contract: ContractArtifact): void => {
24
+ const handlers: [string, number][] = [
25
+ ...Object.entries(contract.procedures ?? {}).map(([id, procedure]): [string, number] => [`procedure \`${id}\``, procedure.timeoutMs]),
26
+ ...Object.entries(contract.mounts).flatMap(([name, mount]): [string, number][] =>
27
+ mount.kind === 'webhook' ? [[`webhook \`${name}\``, mount.timeoutMs]] : []
28
+ ),
29
+ ]
30
+ for (const [subject, timeoutMs] of handlers) {
31
+ if (timeoutMs > CLOUDFLARE_MAX_HANDLER_MS) {
32
+ throw new Error(
33
+ `cloudflare: ${subject} runs up to ${timeoutMs} ms, and a handler on Cloudflare runs at most ${CLOUDFLARE_MAX_HANDLER_MS} ms: it holds its Durable Object's transaction`,
34
+ )
35
+ }
36
+ }
37
+ for (const [name, kind] of Object.entries(contract.fileKinds ?? {})) {
38
+ if (kind.scan === true) {
39
+ throw new Error(`cloudflare: file kind \`${name}\` scans its uploads (\`scan: true\`), and no scanner runs on Cloudflare yet`)
40
+ }
41
+ }
42
+ for (const [name, collection] of Object.entries(contract.files)) {
43
+ if (collection.scan === true) {
44
+ throw new Error(`cloudflare: file collection \`${name}\` scans its uploads (\`scan: true\`), and no scanner runs on Cloudflare yet`)
45
+ }
46
+ }
47
+ for (const [site, reach] of Object.entries(contract.declared ?? {})) {
48
+ if (reach.sql !== null) {
49
+ throw new Error(
50
+ `cloudflare: \`${site}\` declares raw SQL (\`ctx.sql\`), which an application on Cloudflare cannot run: its SQLite has no runtime role to bound it`,
51
+ )
52
+ }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The object runs due jobs and the file sweep of file kinds, a framework job, on the Worker's minute tick (ADR-0065 §5).
58
+ * Legacy `files` collections do not count: the object schedules no sweep of theirs.
59
+ */
60
+ export const needsMinuteTick = (contract: ContractArtifact): boolean =>
61
+ Object.keys(contract.jobs).length > 0 || Object.keys(contract.fileKinds ?? {}).length > 0
62
+
63
+ /**
64
+ * Whether framework release `release` is at least `since`. A prerelease counts as its `major.minor`; a release that
65
+ * does not start with `<major>.<minor>.` is never at least anything (ADR-0062).
66
+ */
67
+ export const releaseAtLeast = (release: string, since: { readonly major: number; readonly minor: number }): boolean => {
68
+ const match = /^(\d+)\.(\d+)\./.exec(release)
69
+ if (match === null) return false
70
+ const major = Number(match[1])
71
+ return major > since.major || (major === since.major && Number(match[2]) >= since.minor)
72
+ }
73
+
74
+ /** The first framework minor whose Cloudflare entry exports the application's Durable Object (ADR-0065). */
75
+ const OBJECT_RUNTIME_SINCE = { major: 0, minor: 9 }
76
+
77
+ /**
78
+ * Whether an application on framework release `release` runs in its Durable Object. An older release's entry is a
79
+ * stateless Worker, which the platform keeps deploying in its old shape (ADR-0062).
80
+ */
81
+ export const runsInObject = (release: string): boolean => releaseAtLeast(release, OBJECT_RUNTIME_SINCE)
82
+
83
+ /** The first framework minor whose Cloudflare deploy pins the generated entry. */
84
+ const PINNED_ENTRY_SINCE = { major: 0, minor: 9 }
85
+
86
+ /** Whether the Cloudflare deploy of release `release` accepts only the generated entry and regenerates it. */
87
+ export const pinsGeneratedEntry = (release: string): boolean => releaseAtLeast(release, PINNED_ENTRY_SINCE)
88
+
89
+ /** The first framework minor whose application object serves Control's ops row (ADR-0069). */
90
+ const SERVES_OPS_SINCE = { major: 0, minor: 9 }
91
+
92
+ /** Whether an environment on release `release` gets the ops row, the ops key digests and the object variables. */
93
+ export const servesOps = (release: string): boolean => releaseAtLeast(release, SERVES_OPS_SINCE)
94
+
95
+ /**
96
+ * Refuse what a stateless Worker of an older release cannot run: a job, a webhook, a public procedure, installation
97
+ * mail and token purposes all need the object's database or a Worker secret it never reads.
98
+ */
99
+ export const assertStatelessEnvironment = (managed: ProviderManagedEnvironment, release: string): void => {
100
+ const names = Object.keys(managed)
101
+ const workloadKey = names.find(isWorkloadKeyVariable)
102
+ if (workloadKey !== undefined) {
103
+ throw new Error(
104
+ `cloudflare: the contract declares a job, a webhook or a public procedure (${workloadKey}), which an application on framework ${release} cannot run on Cloudflare; upgrade its framework`,
105
+ )
106
+ }
107
+ const mailVariable = names.find((name) => isEmailTransportVariable(name) || isPlatformTransportVariable(name))
108
+ if (mailVariable !== undefined) {
109
+ throw new Error(
110
+ `cloudflare: the contract declares a job that sends mail through the installation (${mailVariable}), which an application on framework ${release} cannot run on Cloudflare; upgrade its framework`,
111
+ )
112
+ }
113
+ if (managedValue(managed, FABRIKA_TOKEN_KEYS) !== null) {
114
+ throw new Error(
115
+ `cloudflare: the contract declares token purposes, which an application on framework ${release} cannot sign on Cloudflare; upgrade its framework`,
116
+ )
117
+ }
118
+ }