oblaka-iac 0.0.18 → 0.0.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -11
- package/package.json +1 -1
- package/src/api.ts +5 -2
- package/src/auth.ts +65 -18
- package/src/client.ts +29 -10
- package/src/commands/configure.ts +1 -0
- package/src/commands/deploy.ts +7 -8
- package/src/commands/input.ts +11 -0
- package/src/commands/resource-processor.ts +24 -1
- package/src/commands/validate.ts +1 -0
package/README.md
CHANGED
|
@@ -70,6 +70,14 @@ Generates a `wrangler.jsonc` config inside each worker directory:
|
|
|
70
70
|
bunx oblaka oblaka.ts
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
To generate a second config next to the default one (for example for a test environment), pass `--config` with a file name. Unlike wrangler's `--config`, it is a bare file name ending in `.json` or `.jsonc`, not a path: the file is written into each worker's `dir`.
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
bunx oblaka oblaka.ts --env test --config wrangler.test.jsonc
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Durable Object migration history is read back from the generated file itself, so each config file name keeps its own history. Renaming the config of an already deployed worker starts the migrations from `v0001` again; rename the existing file first instead.
|
|
80
|
+
|
|
73
81
|
### Deploy to Cloudflare
|
|
74
82
|
|
|
75
83
|
Creates resources on Cloudflare and generates the config:
|
|
@@ -102,17 +110,17 @@ bunx oblaka oblaka.ts \
|
|
|
102
110
|
|
|
103
111
|
## CLI options
|
|
104
112
|
|
|
105
|
-
| Option | Env variable | Default | Description
|
|
106
|
-
| ------------------- | ----------------------- | ---------------- |
|
|
107
|
-
| `--env` | `CLOUDFLARE_ENV` | `local` | Environment name
|
|
108
|
-
| `--remote` | | `false` | Deploy resources to Cloudflare
|
|
109
|
-
| `--dry-run` | | `false` | Preview changes without applying
|
|
110
|
-
| `--account-id` | `CLOUDFLARE_ACCOUNT_ID` | | Cloudflare account ID
|
|
111
|
-
| `--api-token` | `CLOUDFLARE_API_TOKEN` | | Cloudflare API token
|
|
112
|
-
| `--config` | | `wrangler.jsonc` | Output config
|
|
113
|
-
| `--state-namespace` | | `cf-state` | KV namespace for state storage
|
|
114
|
-
| `--destroy` | | `false` | Destroy managed resources
|
|
115
|
-
| `--out-state` | | | Export state to a JSON file
|
|
113
|
+
| Option | Env variable | Default | Description |
|
|
114
|
+
| ------------------- | ----------------------- | ---------------- | ------------------------------------ |
|
|
115
|
+
| `--env` | `CLOUDFLARE_ENV` | `local` | Environment name |
|
|
116
|
+
| `--remote` | | `false` | Deploy resources to Cloudflare |
|
|
117
|
+
| `--dry-run` | | `false` | Preview changes without applying |
|
|
118
|
+
| `--account-id` | `CLOUDFLARE_ACCOUNT_ID` | | Cloudflare account ID |
|
|
119
|
+
| `--api-token` | `CLOUDFLARE_API_TOKEN` | | Cloudflare API token |
|
|
120
|
+
| `--config` | | `wrangler.jsonc` | Output config file name (not a path) |
|
|
121
|
+
| `--state-namespace` | | `cf-state` | KV namespace for state storage |
|
|
122
|
+
| `--destroy` | | `false` | Destroy managed resources |
|
|
123
|
+
| `--out-state` | | | Export state to a JSON file |
|
|
116
124
|
|
|
117
125
|
## State management
|
|
118
126
|
|
package/package.json
CHANGED
package/src/api.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from 'node:fs/promises'
|
|
|
2
2
|
import * as path from 'node:path'
|
|
3
3
|
import { CloudflareDeployExecutor } from './commands/deploy'
|
|
4
4
|
import type { Input } from './commands/input'
|
|
5
|
-
import type
|
|
5
|
+
import { type ConfigWriter, DEFAULT_CONFIG_FILE_NAME, type GeneratedConfig } from './commands/resource-processor'
|
|
6
6
|
import type { Worker } from './resources'
|
|
7
7
|
|
|
8
8
|
export type Definition = Worker
|
|
@@ -16,6 +16,8 @@ export interface DeployOptions {
|
|
|
16
16
|
dryRun?: boolean
|
|
17
17
|
remote?: boolean
|
|
18
18
|
cwd?: string
|
|
19
|
+
/** File name (not a path) of the generated wrangler config in each worker's `dir`. Defaults to `wrangler.jsonc`. */
|
|
20
|
+
configFileName?: string
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
export interface DeployResult {
|
|
@@ -28,7 +30,7 @@ export interface DeployResult {
|
|
|
28
30
|
* (the result of `define()` / `new Worker(...)`) against Cloudflare.
|
|
29
31
|
*
|
|
30
32
|
* Unlike the CLI, this skips loading the recipe file and works directly on the in-memory
|
|
31
|
-
* definition. It always returns the generated wrangler config(s); `wrangler.jsonc` is written
|
|
33
|
+
* definition. It always returns the generated wrangler config(s); the config (`wrangler.jsonc` by default) is written
|
|
32
34
|
* to disk only when `remote` is set and `dryRun` is not (mirroring the CLI deploy behavior).
|
|
33
35
|
*
|
|
34
36
|
* State is stored in the `cf-state` KV namespace under a per-env key (the `env` value).
|
|
@@ -57,6 +59,7 @@ export const deploy = async (definition: Definition | undefined, options: Deploy
|
|
|
57
59
|
// Programmatic deploy always supplies an explicit apiToken, so wrangler's
|
|
58
60
|
// OAuth token provider (and its persistence) is never exercised.
|
|
59
61
|
persistToken: false,
|
|
62
|
+
configFileName: options.configFileName || DEFAULT_CONFIG_FILE_NAME,
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
const shouldWrite = remote && !dryRun
|
package/src/auth.ts
CHANGED
|
@@ -113,8 +113,10 @@ interface TokenEndpointResponse {
|
|
|
113
113
|
refresh_token?: string
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
type FetchFn = (url: string, init: RequestInit) => Promise<Response>
|
|
117
|
+
|
|
116
118
|
interface RefreshDeps {
|
|
117
|
-
fetch?:
|
|
119
|
+
fetch?: FetchFn
|
|
118
120
|
tokenUrl?: string
|
|
119
121
|
clientId?: string
|
|
120
122
|
now?: () => number
|
|
@@ -140,7 +142,7 @@ export async function refreshAccessToken(
|
|
|
140
142
|
})
|
|
141
143
|
if (!response.ok) {
|
|
142
144
|
throw new Error(
|
|
143
|
-
`Failed to refresh Cloudflare OAuth token (${response.status}).
|
|
145
|
+
`Failed to refresh Cloudflare OAuth token (${response.status}): ${await response.text()}\nRun \`wrangler login\` to re-authenticate.`,
|
|
144
146
|
)
|
|
145
147
|
}
|
|
146
148
|
const data = (await response.json()) as TokenEndpointResponse
|
|
@@ -166,47 +168,92 @@ function tokenUrlFromEnv(): string {
|
|
|
166
168
|
export interface WranglerTokenProviderOptions {
|
|
167
169
|
configPath?: string
|
|
168
170
|
now?: () => number
|
|
169
|
-
fetch?:
|
|
171
|
+
fetch?: FetchFn
|
|
170
172
|
/** Persist the refreshed token back to default.toml (default true). */
|
|
171
173
|
persist?: boolean
|
|
172
174
|
}
|
|
173
175
|
|
|
176
|
+
export interface WranglerTokenProvider {
|
|
177
|
+
/** Returns a valid access token, refreshing it once it is within the expiry buffer. */
|
|
178
|
+
getToken(): Promise<string>
|
|
179
|
+
/** Returns a replacement for an access token the API rejected, even if its stored expiry still looks valid. */
|
|
180
|
+
refreshToken(rejected: string): Promise<string>
|
|
181
|
+
}
|
|
182
|
+
|
|
174
183
|
/**
|
|
175
|
-
* Returns a token provider backed by wrangler's stored OAuth credentials.
|
|
176
|
-
*
|
|
177
|
-
*
|
|
184
|
+
* Returns a token provider backed by wrangler's stored OAuth credentials. The
|
|
185
|
+
* current token is cached in memory for the process; refreshed tokens are
|
|
186
|
+
* persisted so wrangler and later runs pick them up.
|
|
178
187
|
*/
|
|
179
|
-
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}):
|
|
188
|
+
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}): WranglerTokenProvider {
|
|
180
189
|
const configPath = options.configPath ?? getWranglerConfigPath()
|
|
181
190
|
const now = options.now ?? Date.now
|
|
182
191
|
const persist = options.persist ?? true
|
|
183
|
-
|
|
192
|
+
// The newest credentials known to this process. With persist off (or a failed
|
|
193
|
+
// write) they are newer than the file, including a rotated refresh token.
|
|
194
|
+
let current: RefreshedCredentials & { expiresAt: number } | null = null
|
|
195
|
+
// The file's access token as of our last read or write; a different value
|
|
196
|
+
// means wrangler (or another run) updated the file since.
|
|
197
|
+
let lastFileToken: string | null = null
|
|
198
|
+
const rejectedTokens = new Set<string>()
|
|
199
|
+
// Shared so concurrent callers don't each spend the refresh token; Cloudflare
|
|
200
|
+
// may rotate it, which would make every refresh but the first fail.
|
|
201
|
+
let refreshing: Promise<string> | null = null
|
|
184
202
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
203
|
+
const usable = (creds: { oauthToken: string; expiresAt: number } | null) =>
|
|
204
|
+
creds !== null && !rejectedTokens.has(creds.oauthToken) && Number.isFinite(creds.expiresAt)
|
|
205
|
+
&& creds.expiresAt - EXPIRY_BUFFER_MS > now()
|
|
206
|
+
|
|
207
|
+
const syncFromFile = () => {
|
|
189
208
|
const creds = readWranglerCredentials(configPath)
|
|
190
209
|
if (!creds) {
|
|
191
210
|
throw new Error(
|
|
192
211
|
`No Cloudflare credentials found. Set CLOUDFLARE_API_TOKEN, or run \`wrangler login\` (looked in ${configPath}).`,
|
|
193
212
|
)
|
|
194
213
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
return creds.oauthToken
|
|
214
|
+
if (current === null || creds.oauthToken !== lastFileToken) {
|
|
215
|
+
lastFileToken = creds.oauthToken
|
|
216
|
+
current = { ...creds, expiresAt: Date.parse(creds.expirationTime) }
|
|
199
217
|
}
|
|
218
|
+
return current
|
|
219
|
+
}
|
|
200
220
|
|
|
201
|
-
|
|
221
|
+
const doRefresh = async (refreshToken: string): Promise<string> => {
|
|
222
|
+
const refreshed = await refreshAccessToken(refreshToken, { fetch: options.fetch, now })
|
|
223
|
+
current = { ...refreshed, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
202
224
|
if (persist) {
|
|
203
225
|
try {
|
|
204
226
|
writeWranglerCredentials(configPath, refreshed)
|
|
227
|
+
lastFileToken = refreshed.oauthToken
|
|
205
228
|
} catch (error) {
|
|
206
229
|
console.warn(`Warning: refreshed Cloudflare OAuth token but could not persist it to ${configPath}: ${error}`)
|
|
207
230
|
}
|
|
208
231
|
}
|
|
209
|
-
cached = { token: refreshed.oauthToken, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
210
232
|
return refreshed.oauthToken
|
|
211
233
|
}
|
|
234
|
+
|
|
235
|
+
const obtain = async (): Promise<string> => {
|
|
236
|
+
if (refreshing) {
|
|
237
|
+
return refreshing
|
|
238
|
+
}
|
|
239
|
+
if (current && usable(current)) {
|
|
240
|
+
return current.oauthToken
|
|
241
|
+
}
|
|
242
|
+
const latest = syncFromFile()
|
|
243
|
+
if (usable(latest)) {
|
|
244
|
+
return latest.oauthToken
|
|
245
|
+
}
|
|
246
|
+
refreshing = doRefresh(latest.refreshToken).finally(() => {
|
|
247
|
+
refreshing = null
|
|
248
|
+
})
|
|
249
|
+
return refreshing
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
getToken: obtain,
|
|
254
|
+
refreshToken(rejected) {
|
|
255
|
+
rejectedTokens.add(rejected)
|
|
256
|
+
return obtain()
|
|
257
|
+
},
|
|
258
|
+
}
|
|
212
259
|
}
|
package/src/client.ts
CHANGED
|
@@ -5,6 +5,8 @@ export class CloudflareClient {
|
|
|
5
5
|
private readonly config: {
|
|
6
6
|
accountId: string
|
|
7
7
|
getToken: () => Promise<string>
|
|
8
|
+
/** Returns a replacement for a token the API rejected with 401; the request is then retried once. */
|
|
9
|
+
refreshToken?: (rejected: string) => Promise<string>
|
|
8
10
|
},
|
|
9
11
|
) {
|
|
10
12
|
this.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}`
|
|
@@ -16,19 +18,36 @@ export class CloudflareClient {
|
|
|
16
18
|
body?: any
|
|
17
19
|
headers?: Record<string, string>
|
|
18
20
|
}): Promise<T> {
|
|
21
|
+
const send = (token: string) =>
|
|
22
|
+
fetch(`${this.baseUrl}${url}`, {
|
|
23
|
+
method,
|
|
24
|
+
headers: {
|
|
25
|
+
Authorization: `Bearer ${token}`,
|
|
26
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
27
|
+
...headers,
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify(body),
|
|
30
|
+
})
|
|
31
|
+
|
|
19
32
|
const token = await this.config.getToken()
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
33
|
+
let response = await send(token)
|
|
34
|
+
let refreshed = false
|
|
35
|
+
if (response.status === 401 && this.config.refreshToken) {
|
|
36
|
+
const rejectedBody = await response.text()
|
|
37
|
+
let replacement: string
|
|
38
|
+
try {
|
|
39
|
+
replacement = await this.config.refreshToken(token)
|
|
40
|
+
} catch (error) {
|
|
41
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
42
|
+
throw new Error(`Failed to fetch ${url}: ${response.statusText} ${rejectedBody}\nRefreshing the token failed: ${reason}`, { cause: error })
|
|
43
|
+
}
|
|
44
|
+
response = await send(replacement)
|
|
45
|
+
refreshed = true
|
|
46
|
+
}
|
|
29
47
|
|
|
30
48
|
if (!response.ok) {
|
|
31
|
-
|
|
49
|
+
const hint = refreshed && response.status === 401 ? '\nThe refreshed token was rejected too; run `wrangler login` to re-authenticate.' : ''
|
|
50
|
+
throw new Error(`Failed to fetch ${url}: ${response.statusText} ${await response.text()}${hint}`)
|
|
32
51
|
}
|
|
33
52
|
|
|
34
53
|
const res: any = await response.json()
|
package/src/commands/deploy.ts
CHANGED
|
@@ -20,13 +20,12 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
20
20
|
}): Promise<GeneratedConfig[]> {
|
|
21
21
|
// An explicit API token wins; otherwise fall back to wrangler's stored
|
|
22
22
|
// OAuth credentials (`wrangler login`).
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
})
|
|
23
|
+
const apiToken = input.apiToken
|
|
24
|
+
const cfClient = new CloudflareClient(
|
|
25
|
+
apiToken
|
|
26
|
+
? { accountId: input.accountId, getToken: async () => apiToken }
|
|
27
|
+
: { accountId: input.accountId, ...createWranglerTokenProvider({ persist: input.persistToken }) },
|
|
28
|
+
)
|
|
30
29
|
|
|
31
30
|
const stateStore = new KVStateStorage(cfClient, input.stateNamespace, input.stateNamespaceId)
|
|
32
31
|
const stateKey = { env: input.env }
|
|
@@ -71,7 +70,7 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
71
70
|
}
|
|
72
71
|
|
|
73
72
|
private async run(definition: Worker | undefined): Promise<GeneratedConfig[]> {
|
|
74
|
-
const resourceProcessor = new ResourceProcessor(this, this.configWriter)
|
|
73
|
+
const resourceProcessor = new ResourceProcessor(this, this.configWriter, this.input.configFileName)
|
|
75
74
|
const generated = await resourceProcessor.process({ definition, env: this.input.env })
|
|
76
75
|
|
|
77
76
|
this.log(`Changed ${this.totalChanged} resources`)
|
package/src/commands/input.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util'
|
|
2
|
+
import { DEFAULT_CONFIG_FILE_NAME, validateConfigFileName } from './resource-processor'
|
|
2
3
|
|
|
3
4
|
export const input = (() => {
|
|
4
5
|
const { values, positionals } = parseArgs({
|
|
@@ -16,6 +17,7 @@ export const input = (() => {
|
|
|
16
17
|
validate: { type: 'boolean' },
|
|
17
18
|
'out-state': { type: 'string' },
|
|
18
19
|
'no-persist-token': { type: 'boolean' },
|
|
20
|
+
config: { type: 'string' },
|
|
19
21
|
},
|
|
20
22
|
})
|
|
21
23
|
|
|
@@ -25,6 +27,13 @@ export const input = (() => {
|
|
|
25
27
|
process.exit(1)
|
|
26
28
|
}
|
|
27
29
|
|
|
30
|
+
const configFileName = values.config || DEFAULT_CONFIG_FILE_NAME
|
|
31
|
+
const configFileNameError = validateConfigFileName(configFileName)
|
|
32
|
+
if (configFileNameError) {
|
|
33
|
+
console.error(`Invalid --config: ${configFileNameError}`)
|
|
34
|
+
process.exit(1)
|
|
35
|
+
}
|
|
36
|
+
|
|
28
37
|
return {
|
|
29
38
|
main,
|
|
30
39
|
env: values.env || process.env.CLOUDFLARE_ENV || 'local',
|
|
@@ -40,6 +49,8 @@ export const input = (() => {
|
|
|
40
49
|
// When using OAuth, persist the refreshed token back to wrangler's config
|
|
41
50
|
// unless the user opts out (e.g. read-only credentials dir).
|
|
42
51
|
persistToken: !(values['no-persist-token'] ?? false),
|
|
52
|
+
// Name of the generated wrangler config, written into each worker's `dir`.
|
|
53
|
+
configFileName,
|
|
43
54
|
}
|
|
44
55
|
})()
|
|
45
56
|
|
|
@@ -6,13 +6,36 @@ import type { Config, DefineFn, Resource } from '../types'
|
|
|
6
6
|
import { getNextMigrationTag } from '../utils/migrations'
|
|
7
7
|
import { tryReadFile } from './utils/fs'
|
|
8
8
|
|
|
9
|
+
export const DEFAULT_CONFIG_FILE_NAME = 'wrangler.jsonc'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Returns an error message when `name` cannot be used as the generated config's file name.
|
|
13
|
+
* It is joined onto each worker's `dir`, so it must be a bare file name, and the generator
|
|
14
|
+
* always writes JSONC, so it must end in `.json` or `.jsonc`.
|
|
15
|
+
*/
|
|
16
|
+
export const validateConfigFileName = (name: string): string | undefined => {
|
|
17
|
+
if (!name || path.basename(name) !== name || name === '.' || name === '..') {
|
|
18
|
+
return `Config file name must be a bare file name without a directory, got '${name}'`
|
|
19
|
+
}
|
|
20
|
+
if (!/\.jsonc?$/.test(name)) {
|
|
21
|
+
return `Config file name must end with .json or .jsonc, got '${name}'`
|
|
22
|
+
}
|
|
23
|
+
return undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
export class ResourceProcessor {
|
|
10
27
|
private workers: Worker[] = []
|
|
11
28
|
|
|
12
29
|
constructor(
|
|
13
30
|
private readonly resourceHandler: ResourceApplier,
|
|
14
31
|
private readonly configWriter: ConfigWriter = defaultConfigWriter,
|
|
32
|
+
private readonly configFileName: string = DEFAULT_CONFIG_FILE_NAME,
|
|
15
33
|
) {
|
|
34
|
+
// Fail before any resource is applied, not when the config is written.
|
|
35
|
+
const error = validateConfigFileName(configFileName)
|
|
36
|
+
if (error) {
|
|
37
|
+
throw new Error(error)
|
|
38
|
+
}
|
|
16
39
|
}
|
|
17
40
|
|
|
18
41
|
public async run({ main, env }: {
|
|
@@ -49,7 +72,7 @@ export class ResourceProcessor {
|
|
|
49
72
|
if (!worker) {
|
|
50
73
|
return undefined
|
|
51
74
|
}
|
|
52
|
-
const configPath = path.join(worker.options.dir,
|
|
75
|
+
const configPath = path.join(worker.options.dir, this.configFileName)
|
|
53
76
|
const existingConfig = jsoncParser.parse((await tryReadFile(configPath)) || '{}') as Config
|
|
54
77
|
const { bindings, dir, deleteDurableObjectsOnRemoval, ...workerConfig } = worker.options
|
|
55
78
|
|
package/src/commands/validate.ts
CHANGED