couriercrow 0.0.0-stage → 0.1.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -2
  3. package/bin/couriercrow.js +5 -0
  4. package/bin/crow.js +14 -0
  5. package/bundle/migrations/0001_initial.sql +463 -0
  6. package/bundle/version.json +3 -0
  7. package/bundle/web/_headers +6 -0
  8. package/bundle/web/assets/index-Bim8rHvG.css +2 -0
  9. package/bundle/web/assets/index-YpJn_3e5.js +13 -0
  10. package/bundle/web/index.html +14 -0
  11. package/bundle/worker/README.md +1 -0
  12. package/bundle/worker/worker.js +57841 -0
  13. package/bundle/wrangler.jsonc +64 -0
  14. package/package.json +61 -4
  15. package/src/app-credentials.ts +413 -0
  16. package/src/bin.ts +578 -0
  17. package/src/build-config.ts +264 -0
  18. package/src/build-id.ts +39 -0
  19. package/src/cloudflare/cloudflare-client.ts +361 -0
  20. package/src/cloudflare/cloudflare-live-access.ts +454 -0
  21. package/src/cloudflare/cloudflare-live-account.ts +95 -0
  22. package/src/cloudflare/cloudflare-live-api.ts +87 -0
  23. package/src/cloudflare/cloudflare-live-checks.ts +151 -0
  24. package/src/cloudflare/cloudflare-live-zone.ts +363 -0
  25. package/src/cloudflare/cloudflare-live.ts +270 -0
  26. package/src/cloudflare/cloudflare-state.ts +152 -0
  27. package/src/cloudflare/first-run.ts +322 -0
  28. package/src/credentials-show.ts +49 -0
  29. package/src/deploy.ts +807 -0
  30. package/src/doctor.ts +504 -0
  31. package/src/environment.ts +141 -0
  32. package/src/index.ts +4 -0
  33. package/src/init.ts +332 -0
  34. package/src/load-config.ts +47 -0
  35. package/src/mailbox-api.ts +345 -0
  36. package/src/permissions.ts +133 -0
  37. package/src/plan.ts +517 -0
  38. package/src/printable.ts +8 -0
  39. package/src/product.ts +63 -0
  40. package/src/purge.ts +93 -0
  41. package/src/render.ts +406 -0
  42. package/src/rotate-app-secret.ts +53 -0
  43. package/src/runtime.ts +33 -0
  44. package/src/set-secret.ts +63 -0
  45. package/src/terminal.ts +163 -0
  46. package/src/wrangler.ts +168 -0
@@ -0,0 +1,163 @@
1
+ import { createInterface } from 'node:readline'
2
+
3
+ import { Context, Effect, Layer } from 'effect'
4
+
5
+ interface TerminalShape {
6
+ // Asks one question and returns the typed line. An empty string when the
7
+ // input ends.
8
+ ask: (question: string) => Effect.Effect<string>
9
+ // Like ask, but what is typed is not shown. For secrets.
10
+ askHidden: (question: string) => Effect.Effect<string>
11
+ // Everything piped in on stdin, at most maxInputCharacters and one more.
12
+ readInput: () => Effect.Effect<string>
13
+ print: (text: string) => Effect.Effect<void>
14
+ stdinIsTerminal: boolean
15
+ // A problem that does not stop the run. Goes to stderr at once.
16
+ warn: (text: string) => Effect.Effect<void>
17
+ stdoutIsTerminal: boolean
18
+ }
19
+
20
+ // What the person sees and types. Tests replace it.
21
+ export class Terminal extends Context.Service<Terminal, TerminalShape>()(
22
+ 'Terminal'
23
+ ) {}
24
+
25
+ // More than this is not a value anyone pastes.
26
+ export const maxInputCharacters = 10_000
27
+
28
+ export interface AskStreams {
29
+ input: NodeJS.ReadableStream
30
+ output: NodeJS.WritableStream
31
+ // Ctrl+C is a key, not a signal, only on a terminal.
32
+ terminal?: boolean
33
+ }
34
+
35
+ // Asks one question. A closed input and Ctrl+C answer with an empty string
36
+ // instead of waiting for ever.
37
+ export function askLine(
38
+ question: string,
39
+ streams: AskStreams = { input: process.stdin, output: process.stdout }
40
+ ): Promise<string> {
41
+ return new Promise<string>((resolve) => {
42
+ const lines = createInterface({
43
+ input: streams.input,
44
+ output: streams.output,
45
+ ...(streams.terminal === undefined ? {} : { terminal: streams.terminal })
46
+ })
47
+ let answered = false
48
+
49
+ const finish = (answer: string) => {
50
+ if (!answered) {
51
+ answered = true
52
+ resolve(answer)
53
+ }
54
+
55
+ lines.close()
56
+ }
57
+
58
+ lines.on('close', () => finish(''))
59
+ lines.on('SIGINT', () => finish(''))
60
+ lines.question(`${question} `, finish)
61
+ })
62
+ }
63
+
64
+ interface HiddenStreams {
65
+ input: NodeJS.ReadableStream & { isRaw?: boolean; setRawMode?: (mode: boolean) => unknown }
66
+ output: NodeJS.WritableStream
67
+ }
68
+
69
+ // Asks one question without showing what is typed. Enter or Ctrl+D ends the
70
+ // answer, Ctrl+C gives an empty one, backspace removes a character. A
71
+ // pasted value arrives in one piece and ends at its line break.
72
+ export function askHiddenLine(
73
+ question: string,
74
+ streams: HiddenStreams = { input: process.stdin, output: process.stdout }
75
+ ): Promise<string> {
76
+ return new Promise<string>((resolve) => {
77
+ const { input, output } = streams
78
+ const wasRaw = input.isRaw === true
79
+ let value = ''
80
+
81
+ output.write(`${question} `)
82
+ input.setRawMode?.(true)
83
+
84
+ const finish = (answer: string) => {
85
+ input.removeListener('data', onData)
86
+ input.removeListener('end', onEnd)
87
+ input.setRawMode?.(wasRaw)
88
+ input.pause()
89
+ output.write('\n')
90
+ resolve(answer)
91
+ }
92
+
93
+ const onEnd = () => finish(value)
94
+
95
+ function onData(chunk: Buffer | string) {
96
+ for (const character of chunk.toString()) {
97
+ if (character === '\r' || character === '\n' || character === '\u0004') {
98
+ finish(value)
99
+
100
+ return
101
+ }
102
+
103
+ if (character === '\u0003') {
104
+ finish('')
105
+
106
+ return
107
+ }
108
+
109
+ if (character === '\u007f' || character === '\b') {
110
+ value = value.slice(0, -1)
111
+ } else if (value.length <= maxInputCharacters) {
112
+ value += character
113
+ }
114
+ }
115
+ }
116
+
117
+ input.on('data', onData)
118
+ input.on('end', onEnd)
119
+ input.resume()
120
+ })
121
+ }
122
+
123
+ // Reads stdin to its end, stopping one character past the limit.
124
+ async function readStdin(): Promise<string> {
125
+ const reader = Bun.stdin.stream().getReader()
126
+ const decoder = new TextDecoder()
127
+ let text = ''
128
+
129
+ try {
130
+ while (text.length <= maxInputCharacters) {
131
+ const { done, value } = await reader.read()
132
+
133
+ if (done) {
134
+ break
135
+ }
136
+
137
+ text += decoder.decode(value, { stream: true })
138
+ }
139
+ } finally {
140
+ await reader.cancel().catch(() => undefined)
141
+ }
142
+
143
+ return text.slice(0, maxInputCharacters + 1)
144
+ }
145
+
146
+ export const TerminalLive: Layer.Layer<Terminal> = Layer.succeed(
147
+ Terminal,
148
+ Terminal.of({
149
+ ask: (question) => Effect.promise(() => askLine(question)),
150
+ askHidden: (question) => Effect.promise(() => askHiddenLine(question)),
151
+ readInput: () => Effect.promise(() => readStdin()),
152
+ print: (text) =>
153
+ Effect.sync(() => {
154
+ console.log(text)
155
+ }),
156
+ stdinIsTerminal: process.stdin.isTTY === true,
157
+ stdoutIsTerminal: process.stdout.isTTY === true,
158
+ warn: (text) =>
159
+ Effect.sync(() => {
160
+ console.error(text)
161
+ })
162
+ })
163
+ )
@@ -0,0 +1,168 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+
5
+ import { Context, Effect, Layer, Schema } from 'effect'
6
+
7
+ import { workerName } from './cloudflare/cloudflare-client'
8
+
9
+ export class WranglerError extends Schema.TaggedError<WranglerError>()(
10
+ 'WranglerError',
11
+ { message: Schema.String }
12
+ ) {}
13
+
14
+ interface WranglerShape {
15
+ // Applies the migrations in the config's migrations folder to the remote
16
+ // database. Safe to run again: applied migrations are skipped.
17
+ applyMigrations: (config: string) => Effect.Effect<void, WranglerError>
18
+ deploy: (config: string) => Effect.Effect<void, WranglerError>
19
+ // Stores a secret of the deployed Worker. The value goes to wrangler on
20
+ // its stdin only: never on the command line, in an environment or on disk.
21
+ putSecret: (name: string, value: string) => Effect.Effect<void, WranglerError>
22
+ }
23
+
24
+ // Runs the wrangler binary against a filled copy of the Worker config.
25
+ export class Wrangler extends Context.Service<Wrangler, WranglerShape>()(
26
+ 'Wrangler'
27
+ ) {}
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Live
31
+
32
+ // Five minutes per command.
33
+ export const commandTimeoutMilliseconds = 5 * 60 * 1000
34
+
35
+ export function wranglerArguments(
36
+ subcommand: 'd1 migrations apply' | 'deploy',
37
+ config: string
38
+ ): string[] {
39
+ return subcommand === 'deploy'
40
+ ? ['deploy', '--config', config]
41
+ : ['d1', 'migrations', 'apply', 'DATABASE', '--remote', '--config', config]
42
+ }
43
+
44
+ // The secret's name and the Worker's. The value is not an argument.
45
+ export function secretArguments(name: string): string[] {
46
+ return ['secret', 'put', name, '--name', workerName]
47
+ }
48
+
49
+ // The token and the account reach wrangler through the environment only, so
50
+ // they never show up in a process list.
51
+ export function wranglerEnvironment(
52
+ environment: Readonly<Record<string, string | undefined>>,
53
+ settings: { accountId: string; token: string }
54
+ ): Record<string, string | undefined> {
55
+ return {
56
+ ...environment,
57
+ CLOUDFLARE_ACCOUNT_ID: settings.accountId,
58
+ CLOUDFLARE_API_TOKEN: settings.token
59
+ }
60
+ }
61
+
62
+ export function wranglerFailedMessage(
63
+ subcommand: 'd1 migrations apply' | 'deploy' | 'secret put'
64
+ ): string {
65
+ return `wrangler ${subcommand} failed. See the output above.`
66
+ }
67
+
68
+ // The wrangler that is installed next to this package.
69
+ async function wranglerBinary(): Promise<string> {
70
+ const manifest = Bun.resolveSync('wrangler/package.json', import.meta.dir)
71
+ const parsed: unknown = await Bun.file(manifest).json()
72
+ const bin =
73
+ typeof parsed === 'object' && parsed !== null && 'bin' in parsed
74
+ ? parsed.bin
75
+ : undefined
76
+ const relative =
77
+ typeof bin === 'object' && bin !== null && 'wrangler' in bin
78
+ ? bin.wrangler
79
+ : undefined
80
+
81
+ if (typeof relative !== 'string') {
82
+ throw new Error('The installed wrangler has no wrangler binary.')
83
+ }
84
+
85
+ return join(dirname(manifest), relative)
86
+ }
87
+
88
+ export function WranglerLive(settings: {
89
+ accountId: string
90
+ token: string
91
+ }): Layer.Layer<Wrangler> {
92
+ const run = (subcommand: 'd1 migrations apply' | 'deploy', config: string) =>
93
+ Effect.tryPromise({
94
+ try: async (signal) => {
95
+ const child = Bun.spawn({
96
+ cmd: [
97
+ process.execPath,
98
+ await wranglerBinary(),
99
+ ...wranglerArguments(subcommand, config)
100
+ ],
101
+ env: wranglerEnvironment(Bun.env, settings),
102
+ killSignal: 'SIGKILL',
103
+ signal,
104
+ stderr: 'inherit',
105
+ // No prompts: wrangler runs as it would in a pipeline.
106
+ stdin: 'ignore',
107
+ stdout: 'inherit',
108
+ timeout: commandTimeoutMilliseconds
109
+ })
110
+
111
+ return await child.exited
112
+ },
113
+ catch: () =>
114
+ new WranglerError({ message: wranglerFailedMessage(subcommand) })
115
+ }).pipe(
116
+ Effect.flatMap((code) =>
117
+ code === 0
118
+ ? Effect.void
119
+ : Effect.fail(
120
+ new WranglerError({ message: wranglerFailedMessage(subcommand) })
121
+ )
122
+ )
123
+ )
124
+
125
+ // Runs in an empty temporary folder, so no wrangler config of the current
126
+ // folder is read; --name picks the Worker. Wrangler reads the value from
127
+ // stdin because stdin is not a terminal.
128
+ const putSecret = (name: string, value: string) =>
129
+ Effect.tryPromise({
130
+ try: async (signal) => {
131
+ const folder = await mkdtemp(join(tmpdir(), 'courier-crow-secret-'))
132
+
133
+ try {
134
+ const child = Bun.spawn({
135
+ cmd: [process.execPath, await wranglerBinary(), ...secretArguments(name)],
136
+ cwd: folder,
137
+ env: wranglerEnvironment(Bun.env, settings),
138
+ killSignal: 'SIGKILL',
139
+ signal,
140
+ stderr: 'inherit',
141
+ stdin: new Blob([value]),
142
+ stdout: 'inherit',
143
+ timeout: commandTimeoutMilliseconds
144
+ })
145
+
146
+ return await child.exited
147
+ } finally {
148
+ await rm(folder, { force: true, recursive: true })
149
+ }
150
+ },
151
+ catch: () => new WranglerError({ message: wranglerFailedMessage('secret put') })
152
+ }).pipe(
153
+ Effect.flatMap((code) =>
154
+ code === 0
155
+ ? Effect.void
156
+ : Effect.fail(new WranglerError({ message: wranglerFailedMessage('secret put') }))
157
+ )
158
+ )
159
+
160
+ return Layer.succeed(
161
+ Wrangler,
162
+ Wrangler.of({
163
+ applyMigrations: (config) => run('d1 migrations apply', config),
164
+ deploy: (config) => run('deploy', config),
165
+ putSecret
166
+ })
167
+ )
168
+ }