@greenmind/cli 0.0.0-stage → 0.9.31
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/package.json +39 -4
- package/src/bin.ts +15 -0
- package/src/bundle.ts +100 -0
- package/src/client.ts +515 -0
- package/src/command.ts +638 -0
- package/src/commands.ts +251 -0
- package/src/constants.ts +37 -0
- package/src/credentials.ts +159 -0
- package/src/environment-commands.ts +549 -0
- package/src/ext-config.ts +107 -0
- package/src/identity.ts +287 -0
- package/src/index.ts +58 -0
- package/src/json-read.ts +29 -0
- package/src/load.ts +123 -0
- package/src/protocol.ts +30 -0
- package/src/session.ts +265 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@greenmind/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.9.31",
|
|
4
|
+
"description": "GreenMind's command line, gm: sign in once, manage environments and keys, and check, push, upload and run extensions",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/GreenMind-Software/gm-core.git",
|
|
9
|
+
"directory": "packages/ext-cli"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"greenmind": "./src/bin.ts",
|
|
13
|
+
"gm": "./src/bin.ts"
|
|
14
|
+
},
|
|
15
|
+
"main": "./src/index.ts",
|
|
16
|
+
"types": "./src/index.ts",
|
|
17
|
+
"files": [
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"bun": ">=1.4.2"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@commander-js/extra-typings": "~15.0.0",
|
|
28
|
+
"@greenmind/ext-function-host": "0.9.31",
|
|
29
|
+
"@greenmind/ext-schema": "0.9.31",
|
|
30
|
+
"@greenmind/ext-sdk": "0.9.31",
|
|
31
|
+
"commander": "~15.0.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@types/bun": ">=1.4.2"
|
|
35
|
+
},
|
|
36
|
+
"peerDependenciesMeta": {
|
|
37
|
+
"@types/bun": {
|
|
38
|
+
"optional": true
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { gmCommand } from './command'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `gm` on its own, without the rest of this repository's command line: what a studio runs, and
|
|
6
|
+
* what our games' `push` scripts run, so a deploy needs no database address in its environment.
|
|
7
|
+
* The published package installs this file as both `greenmind` and `gm`.
|
|
8
|
+
*/
|
|
9
|
+
gmCommand.parseAsync(process.argv).then(
|
|
10
|
+
() => process.exit(process.exitCode ?? 0),
|
|
11
|
+
(error) => {
|
|
12
|
+
console.error(error instanceof Error ? error.message : error)
|
|
13
|
+
process.exit(1)
|
|
14
|
+
},
|
|
15
|
+
)
|
package/src/bundle.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { extname, join } from 'node:path'
|
|
5
|
+
import { type CompiledDefinition, compileProject, type DefinitionBase } from '@greenmind/ext-sdk'
|
|
6
|
+
import type { BunPlugin } from 'bun'
|
|
7
|
+
import { filesUnder, LoadError, loadModule } from './load'
|
|
8
|
+
import { FUNCTION_BUNDLE_MAX_BYTES } from './protocol'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Building a function bundle: one ESM file, `index.mjs`, for Node 24, holding every function the
|
|
12
|
+
* given modules define (exported or used by an exported flow), the handler module over them as
|
|
13
|
+
* `handle`, and the Lambda adapter over that same handle as `handler`. Its content hash is the
|
|
14
|
+
* SHA-256 of its bytes, which is what a version names and a release moves.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const CODE = new Set(['.ts', '.mts', '.js', '.mjs'])
|
|
18
|
+
|
|
19
|
+
/** The runtime every bundle is built for. */
|
|
20
|
+
export const RUNTIME = 'nodejs24.x'
|
|
21
|
+
|
|
22
|
+
export interface Bundle {
|
|
23
|
+
readonly bytes: Uint8Array
|
|
24
|
+
readonly contentHash: string
|
|
25
|
+
/** The functions it holds, compiled. */
|
|
26
|
+
readonly definitions: readonly CompiledDefinition[]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function sha256Hex(bytes: Uint8Array): string {
|
|
30
|
+
return createHash('sha256').update(bytes).digest('hex')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function hostEntry(): string {
|
|
34
|
+
return require.resolve('@greenmind/ext-function-host')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `plugins` are Bun build plugins for code that needs one to compile (a macro, say): a project's own
|
|
39
|
+
* build step passes them; the bundle is the same for the same plugins and sources.
|
|
40
|
+
*/
|
|
41
|
+
export async function buildBundle(
|
|
42
|
+
paths: readonly string[],
|
|
43
|
+
plugins: readonly BunPlugin[] = [],
|
|
44
|
+
): Promise<Bundle> {
|
|
45
|
+
const files = paths.flatMap(filesUnder).filter((file) => CODE.has(extname(file)))
|
|
46
|
+
if (files.length === 0) {
|
|
47
|
+
throw new LoadError('A bundle is built from .ts or .js modules; none was given.')
|
|
48
|
+
}
|
|
49
|
+
const loaded: DefinitionBase[] = []
|
|
50
|
+
for (const file of files) loaded.push(...(await loadModule(file)))
|
|
51
|
+
const definitions = compileProject(loaded).filter((each) => each.kind === 'function')
|
|
52
|
+
if (definitions.length === 0) {
|
|
53
|
+
throw new LoadError('The modules define no function, so there is nothing to bundle.')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The builder writes the entry's path into the output, so the same modules always build in the
|
|
57
|
+
// same place: otherwise one build's bytes, and so its hash, would differ from the next one's.
|
|
58
|
+
const dir = join(
|
|
59
|
+
tmpdir(),
|
|
60
|
+
`ext-bundle-${sha256Hex(new TextEncoder().encode(files.join('\n'))).slice(0, 16)}`,
|
|
61
|
+
)
|
|
62
|
+
mkdirSync(dir, { recursive: true })
|
|
63
|
+
try {
|
|
64
|
+
const entry = join(dir, 'index.ts')
|
|
65
|
+
const imports = files.map((file, i) => `import * as m${i} from ${JSON.stringify(file)}`)
|
|
66
|
+
writeFileSync(
|
|
67
|
+
entry,
|
|
68
|
+
[
|
|
69
|
+
`import { createHandler, functionsOf, lambdaHandler } from ${JSON.stringify(hostEntry())}`,
|
|
70
|
+
...imports,
|
|
71
|
+
`export const handle = createHandler(functionsOf(${files.map((_, i) => `m${i}`).join(', ')}))`,
|
|
72
|
+
'export const handler = lambdaHandler(handle)',
|
|
73
|
+
'',
|
|
74
|
+
].join('\n'),
|
|
75
|
+
)
|
|
76
|
+
const built = await Bun.build({
|
|
77
|
+
entrypoints: [entry],
|
|
78
|
+
target: 'node',
|
|
79
|
+
format: 'esm',
|
|
80
|
+
splitting: false,
|
|
81
|
+
sourcemap: 'none',
|
|
82
|
+
plugins: [...plugins],
|
|
83
|
+
})
|
|
84
|
+
if (!built.success || built.outputs.length !== 1) {
|
|
85
|
+
const why = built.logs.map((log) => String(log)).join('; ')
|
|
86
|
+
throw new LoadError(`The bundle did not build: ${why || 'no single output'}.`)
|
|
87
|
+
}
|
|
88
|
+
const [output] = built.outputs
|
|
89
|
+
if (!output) throw new LoadError('The bundle did not build: no output.')
|
|
90
|
+
const bytes = new Uint8Array(await output.arrayBuffer())
|
|
91
|
+
if (bytes.length > FUNCTION_BUNDLE_MAX_BYTES) {
|
|
92
|
+
throw new LoadError(
|
|
93
|
+
`The bundle is ${bytes.length} bytes; the most an upload takes is ${FUNCTION_BUNDLE_MAX_BYTES}.`,
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
return { bytes, contentHash: sha256Hex(bytes), definitions }
|
|
97
|
+
} finally {
|
|
98
|
+
rmSync(dir, { recursive: true, force: true })
|
|
99
|
+
}
|
|
100
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type CollectionStorageAnswer,
|
|
3
|
+
type CollectionStorageName,
|
|
4
|
+
type CollectionStorageSetRequest,
|
|
5
|
+
collectionStorageAnswer,
|
|
6
|
+
CONFIG_DEFAULTS_PATH,
|
|
7
|
+
type ConfigDefaultsAnswer,
|
|
8
|
+
type ConfigDefaultsRequest,
|
|
9
|
+
type ConnectorCheckAnswer,
|
|
10
|
+
configDefaultsAnswer,
|
|
11
|
+
connectorCheckAnswer,
|
|
12
|
+
type FlowSwitchRequest,
|
|
13
|
+
type FunctionRuntimeSetRequest,
|
|
14
|
+
type PublishKeyCreateRequest,
|
|
15
|
+
type ServerKeyCreateRequest,
|
|
16
|
+
s,
|
|
17
|
+
ENVIRONMENTS_PATH,
|
|
18
|
+
type EnvironmentListAnswer,
|
|
19
|
+
type EnvironmentStatus,
|
|
20
|
+
environmentListAnswer,
|
|
21
|
+
environmentPaths,
|
|
22
|
+
environmentStatus,
|
|
23
|
+
EXT_TOOL_PATH,
|
|
24
|
+
type ExtToolDiscovery,
|
|
25
|
+
extToolDiscovery,
|
|
26
|
+
FLOW_SWITCH_PATH,
|
|
27
|
+
type FlowSwitchAnswer,
|
|
28
|
+
type FunctionRuntimeAnswer,
|
|
29
|
+
type FunctionRuntimeName,
|
|
30
|
+
flowSwitchAnswer,
|
|
31
|
+
functionRuntimeAnswer,
|
|
32
|
+
type Json,
|
|
33
|
+
type PublishKeyCreated,
|
|
34
|
+
type PublishKeyListAnswer,
|
|
35
|
+
parserOf,
|
|
36
|
+
publishKeyCreated,
|
|
37
|
+
publishKeyListAnswer,
|
|
38
|
+
type Schema,
|
|
39
|
+
type SeededValue,
|
|
40
|
+
type ServerKeyCreated,
|
|
41
|
+
type ServerKeyListAnswer,
|
|
42
|
+
serverKeyCreated,
|
|
43
|
+
serverKeyListAnswer,
|
|
44
|
+
SETUP_APP_KEY_PARAM,
|
|
45
|
+
} from '@greenmind/ext-schema'
|
|
46
|
+
import type { CompiledDefinition } from '@greenmind/ext-sdk'
|
|
47
|
+
import { CLI_VERSION, VERSION_HEADER } from './constants'
|
|
48
|
+
import {
|
|
49
|
+
CHECK_PATH,
|
|
50
|
+
type CheckAnswer,
|
|
51
|
+
type CheckIssue,
|
|
52
|
+
checkAnswer,
|
|
53
|
+
checkIssues,
|
|
54
|
+
FUNCTION_UPLOAD_PATH,
|
|
55
|
+
type FunctionUploadAnswer,
|
|
56
|
+
type FunctionUploadRequest,
|
|
57
|
+
functionUploadAnswer,
|
|
58
|
+
type PlatformFailure,
|
|
59
|
+
PUSH_PATH,
|
|
60
|
+
platformFailure,
|
|
61
|
+
type PushAnswer,
|
|
62
|
+
pushAnswer,
|
|
63
|
+
type SourceRef,
|
|
64
|
+
} from './protocol'
|
|
65
|
+
|
|
66
|
+
/** The platform said no, or said something this tool does not understand. */
|
|
67
|
+
export class PlatformError extends Error {
|
|
68
|
+
override readonly name: string = 'PlatformError'
|
|
69
|
+
constructor(
|
|
70
|
+
message: string,
|
|
71
|
+
readonly status: number,
|
|
72
|
+
readonly failure?: PlatformFailure,
|
|
73
|
+
) {
|
|
74
|
+
super(message)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The refusal's code, such as `forbidden` or `protected-environment`. */
|
|
78
|
+
get code(): string | undefined {
|
|
79
|
+
return this.failure?.error
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The definitions' issues, when the platform refused them. */
|
|
83
|
+
get issues(): readonly CheckIssue[] {
|
|
84
|
+
const parsed = parserOf(checkIssues).safeParse(this.failure?.details?.issues)
|
|
85
|
+
return parsed.success ? parsed.data : []
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The platform needs a newer `gm` than this one, whatever code it said so with. */
|
|
90
|
+
export class UpgradeRequiredError extends PlatformError {
|
|
91
|
+
override readonly name = 'UpgradeRequiredError'
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Where a signed-in person's access token comes from. `refresh` is given the token a request was
|
|
96
|
+
* refused with and answers a new one, or nothing where the person has to sign in again.
|
|
97
|
+
*/
|
|
98
|
+
export interface TokenSource {
|
|
99
|
+
accessToken(): Promise<string>
|
|
100
|
+
refresh(rejected: string): Promise<string | undefined>
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface CommonOptions {
|
|
104
|
+
/** The platform API's address, such as `https://api.example.test`. */
|
|
105
|
+
readonly baseUrl: string
|
|
106
|
+
/** Replaced in tests; defaults to the global `fetch`. */
|
|
107
|
+
readonly fetch?: typeof fetch
|
|
108
|
+
/** Sent as `x-gm-cli-version`; the package's own version unless a test says otherwise. */
|
|
109
|
+
readonly cliVersion?: string
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type PlatformClientOptions = CommonOptions &
|
|
113
|
+
(
|
|
114
|
+
| {
|
|
115
|
+
/** A publish key, scoped by the platform to one test environment. */
|
|
116
|
+
readonly publishKey: string
|
|
117
|
+
readonly tokens?: undefined
|
|
118
|
+
}
|
|
119
|
+
| { readonly tokens: TokenSource; readonly publishKey?: undefined }
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
interface DefinitionsBody {
|
|
123
|
+
readonly definitions: readonly CompiledDefinition[]
|
|
124
|
+
readonly source?: SourceRef
|
|
125
|
+
readonly live?: boolean
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Everything this client's own calls send, and `RequestBody` for what a command outside this package
|
|
130
|
+
* sends through `request`: a request shape from `@greenmind/ext-schema`, never an arbitrary object.
|
|
131
|
+
*/
|
|
132
|
+
type Body =
|
|
133
|
+
| DefinitionsBody
|
|
134
|
+
| FunctionUploadRequest
|
|
135
|
+
| ConfigDefaultsRequest
|
|
136
|
+
| FlowSwitchRequest
|
|
137
|
+
| ServerKeyCreateRequest
|
|
138
|
+
| PublishKeyCreateRequest
|
|
139
|
+
| FunctionRuntimeSetRequest
|
|
140
|
+
| CollectionStorageSetRequest
|
|
141
|
+
| RequestBody
|
|
142
|
+
|
|
143
|
+
/** A body for `request`: one of the wire's request shapes, which are plain JSON. */
|
|
144
|
+
export type RequestBody = { readonly [field: string]: Json | readonly string[] }
|
|
145
|
+
|
|
146
|
+
const minimumVersion = parserOf(s.string({ minLength: 1, maxLength: 64 }))
|
|
147
|
+
|
|
148
|
+
interface Exchange {
|
|
149
|
+
readonly status: number
|
|
150
|
+
readonly json: Json | undefined
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function parseJson(text: string): Json | undefined {
|
|
154
|
+
try {
|
|
155
|
+
return JSON.parse(text)
|
|
156
|
+
} catch {
|
|
157
|
+
return undefined
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The code of a refusal in the platform's `{ error, message }` form, if it is one. */
|
|
162
|
+
function refusalCodeOf(got: Exchange): string | undefined {
|
|
163
|
+
const failure = parserOf(platformFailure).safeParse(got.json)
|
|
164
|
+
return failure.success ? failure.data.error : undefined
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** A setup route's path, naming the environment where a signed-in person sends it. */
|
|
168
|
+
function setupPath(path: string, appKey: string | undefined): string {
|
|
169
|
+
if (appKey === undefined) return path
|
|
170
|
+
return `${path}?${new URLSearchParams({ [SETUP_APP_KEY_PARAM]: appKey }).toString()}`
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* What a platform says about signing in to it (`EXT_TOOL_PATH`), asked with no credential before
|
|
175
|
+
* anybody has one. Throws a `PlatformError` where it answers anything else.
|
|
176
|
+
*/
|
|
177
|
+
export async function readToolDiscovery(
|
|
178
|
+
platformUrl: string,
|
|
179
|
+
send: typeof fetch = fetch,
|
|
180
|
+
): Promise<ExtToolDiscovery> {
|
|
181
|
+
const url = `${platformUrl.replace(/\/+$/, '')}${EXT_TOOL_PATH}`
|
|
182
|
+
let response: Response
|
|
183
|
+
try {
|
|
184
|
+
response = await send(url, {
|
|
185
|
+
headers: { accept: 'application/json', [VERSION_HEADER]: CLI_VERSION },
|
|
186
|
+
signal: AbortSignal.timeout(20_000),
|
|
187
|
+
})
|
|
188
|
+
} catch (error) {
|
|
189
|
+
throw new PlatformError(
|
|
190
|
+
`Could not reach the platform at ${platformUrl}: ${error instanceof Error ? error.message : error}.`,
|
|
191
|
+
0,
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
const parsed = parserOf(extToolDiscovery).safeParse(parseJson(await response.text()))
|
|
195
|
+
if (!response.ok || !parsed.success) {
|
|
196
|
+
throw new PlatformError(
|
|
197
|
+
`${url} did not say where to sign in (status ${response.status}). Give the identity server with --issuer.`,
|
|
198
|
+
response.status,
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
return parsed.data
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Calls the platform API as a publish key or as a signed-in person, and parses every answer with
|
|
206
|
+
* the shape `@greenmind/ext-schema` gives it. A refusal becomes a `PlatformError` naming its code.
|
|
207
|
+
*/
|
|
208
|
+
export class PlatformClient {
|
|
209
|
+
private readonly base: string
|
|
210
|
+
private readonly publishKey?: string
|
|
211
|
+
private readonly tokens?: TokenSource
|
|
212
|
+
private readonly send: typeof fetch
|
|
213
|
+
private readonly version: string
|
|
214
|
+
|
|
215
|
+
constructor(options: PlatformClientOptions) {
|
|
216
|
+
this.base = options.baseUrl.replace(/\/+$/, '')
|
|
217
|
+
this.publishKey = options.publishKey
|
|
218
|
+
this.tokens = options.tokens
|
|
219
|
+
this.send = options.fetch ?? fetch
|
|
220
|
+
this.version = options.cliVersion ?? CLI_VERSION
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A client with this one's credential for another GreenMind service, at `baseUrl`. */
|
|
224
|
+
at(baseUrl: string): PlatformClient {
|
|
225
|
+
const common = { baseUrl, fetch: this.send, cliVersion: this.version }
|
|
226
|
+
if (this.tokens) return new PlatformClient({ ...common, tokens: this.tokens })
|
|
227
|
+
return new PlatformClient({ ...common, publishKey: this.publishKey ?? '' })
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Any route, for commands this client has no method of its own for: the answer parsed with
|
|
232
|
+
* `answer`, a refusal a `PlatformError`, and a refused sign-in renewed once, as every call is.
|
|
233
|
+
*/
|
|
234
|
+
request<T>(method: string, path: string, body: RequestBody | undefined, answer: Schema<T>) {
|
|
235
|
+
return this.call(method, path, body, answer)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** As `request`, for a route answered 204 with nothing. */
|
|
239
|
+
requestNoContent(method: string, path: string, body?: RequestBody): Promise<void> {
|
|
240
|
+
return this.callNoContent(method, path, body)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The address this client calls, without a trailing slash. */
|
|
244
|
+
get address(): string {
|
|
245
|
+
return this.base
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* What the environment's validation says of these definitions, and which environment it is. A
|
|
250
|
+
* signed-in person names the environment, as for every build call; a publish key needs none.
|
|
251
|
+
*/
|
|
252
|
+
check(definitions: readonly CompiledDefinition[], appKey?: string): Promise<CheckAnswer> {
|
|
253
|
+
return this.call('POST', this.buildPath(CHECK_PATH, appKey), { definitions }, checkAnswer)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Makes each definition a new version in the environment, unless it already holds that hash; with
|
|
258
|
+
* `live`, then makes each pushed version live.
|
|
259
|
+
*/
|
|
260
|
+
push(
|
|
261
|
+
definitions: readonly CompiledDefinition[],
|
|
262
|
+
source?: SourceRef,
|
|
263
|
+
live?: boolean,
|
|
264
|
+
appKey?: string,
|
|
265
|
+
): Promise<PushAnswer> {
|
|
266
|
+
return this.call(
|
|
267
|
+
'POST',
|
|
268
|
+
this.buildPath(PUSH_PATH, appKey),
|
|
269
|
+
{ definitions, source, live },
|
|
270
|
+
pushAnswer,
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Stores a built bundle in the environment and saves its functions as versions naming it. */
|
|
275
|
+
upload(body: FunctionUploadRequest, appKey?: string): Promise<FunctionUploadAnswer> {
|
|
276
|
+
return this.call(
|
|
277
|
+
'POST',
|
|
278
|
+
this.buildPath(FUNCTION_UPLOAD_PATH, appKey),
|
|
279
|
+
body,
|
|
280
|
+
functionUploadAnswer,
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* A build route's path. A signed-in person's sign-in reaches several environments, so they have
|
|
286
|
+
* to name one; a publish key reaches its own, and one it names must be that one.
|
|
287
|
+
*/
|
|
288
|
+
private buildPath(path: string, appKey: string | undefined): string {
|
|
289
|
+
if (appKey === undefined && this.signedIn) {
|
|
290
|
+
throw new PlatformError(
|
|
291
|
+
'Signed in as a person, name the environment with --env <app key>; a publish key needs none.',
|
|
292
|
+
400,
|
|
293
|
+
)
|
|
294
|
+
}
|
|
295
|
+
return setupPath(path, appKey)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Every environment the person may read. */
|
|
299
|
+
listEnvironments(): Promise<EnvironmentListAnswer> {
|
|
300
|
+
return this.call('GET', ENVIRONMENTS_PATH, undefined, environmentListAnswer)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
environmentStatus(appKey: string): Promise<EnvironmentStatus> {
|
|
304
|
+
return this.call('GET', environmentPaths.status(appKey), undefined, environmentStatus)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
listServerKeys(appKey: string): Promise<ServerKeyListAnswer> {
|
|
308
|
+
return this.call('GET', environmentPaths.serverKeys(appKey), undefined, serverKeyListAnswer)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
createServerKey(appKey: string, name: string): Promise<ServerKeyCreated> {
|
|
312
|
+
return this.call('POST', environmentPaths.serverKeys(appKey), { name }, serverKeyCreated)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async revokeServerKey(appKey: string, keyId: string): Promise<void> {
|
|
316
|
+
await this.callNoContent('DELETE', environmentPaths.serverKey(appKey, keyId))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
listPublishKeys(appKey: string): Promise<PublishKeyListAnswer> {
|
|
320
|
+
return this.call('GET', environmentPaths.publishKeys(appKey), undefined, publishKeyListAnswer)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
createPublishKey(appKey: string, label: string): Promise<PublishKeyCreated> {
|
|
324
|
+
return this.call('POST', environmentPaths.publishKeys(appKey), { label }, publishKeyCreated)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async revokePublishKey(appKey: string, keyId: string): Promise<void> {
|
|
328
|
+
await this.callNoContent('DELETE', environmentPaths.publishKey(appKey, keyId))
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Gives the environment each value it lacks; one it holds is left as it is. A signed-in person
|
|
333
|
+
* names the environment; a publish key needs none, and one it names must be its own.
|
|
334
|
+
*/
|
|
335
|
+
seedConfigDefaults(
|
|
336
|
+
values: readonly SeededValue[],
|
|
337
|
+
appKey?: string,
|
|
338
|
+
): Promise<ConfigDefaultsAnswer> {
|
|
339
|
+
return this.call(
|
|
340
|
+
'POST',
|
|
341
|
+
setupPath(CONFIG_DEFAULTS_PATH, appKey),
|
|
342
|
+
{ values },
|
|
343
|
+
configDefaultsAnswer,
|
|
344
|
+
)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** As `seedConfigDefaults`, a signed-in person names the environment. */
|
|
348
|
+
switchFlows(
|
|
349
|
+
flows: readonly { readonly key: string; readonly enabled: boolean }[],
|
|
350
|
+
appKey?: string,
|
|
351
|
+
): Promise<FlowSwitchAnswer> {
|
|
352
|
+
return this.call('POST', setupPath(FLOW_SWITCH_PATH, appKey), { flows }, flowSwitchAnswer)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Whether this client acts as a signed-in person, who has to name the environment of a setup. */
|
|
356
|
+
get signedIn(): boolean {
|
|
357
|
+
return this.tokens !== undefined
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
functionRuntime(appKey: string): Promise<FunctionRuntimeAnswer> {
|
|
361
|
+
return this.call(
|
|
362
|
+
'GET',
|
|
363
|
+
environmentPaths.functionRuntime(appKey),
|
|
364
|
+
undefined,
|
|
365
|
+
functionRuntimeAnswer,
|
|
366
|
+
)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** `null` clears the environment's own choice, so it follows the stage default. */
|
|
370
|
+
setFunctionRuntime(
|
|
371
|
+
appKey: string,
|
|
372
|
+
runtime: FunctionRuntimeName | null,
|
|
373
|
+
): Promise<FunctionRuntimeAnswer> {
|
|
374
|
+
return this.call(
|
|
375
|
+
'PUT',
|
|
376
|
+
environmentPaths.functionRuntime(appKey),
|
|
377
|
+
{ runtime },
|
|
378
|
+
functionRuntimeAnswer,
|
|
379
|
+
)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
collectionStorage(appKey: string): Promise<CollectionStorageAnswer> {
|
|
383
|
+
return this.call(
|
|
384
|
+
'GET',
|
|
385
|
+
environmentPaths.collectionStorage(appKey),
|
|
386
|
+
undefined,
|
|
387
|
+
collectionStorageAnswer,
|
|
388
|
+
)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** `null` clears the environment's own default, so it follows its organisation's. */
|
|
392
|
+
setCollectionStorageDefault(
|
|
393
|
+
appKey: string,
|
|
394
|
+
mode: CollectionStorageName | null,
|
|
395
|
+
): Promise<CollectionStorageAnswer> {
|
|
396
|
+
return this.call(
|
|
397
|
+
'PUT',
|
|
398
|
+
environmentPaths.collectionStorage(appKey),
|
|
399
|
+
{ default: mode },
|
|
400
|
+
collectionStorageAnswer,
|
|
401
|
+
)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Runs the connector check of the data connection `connection` for self-hosted collections. */
|
|
405
|
+
checkConnector(appKey: string, connection: string): Promise<ConnectorCheckAnswer> {
|
|
406
|
+
return this.call(
|
|
407
|
+
'POST',
|
|
408
|
+
environmentPaths.connectorCheck(appKey, connection),
|
|
409
|
+
{},
|
|
410
|
+
connectorCheckAnswer,
|
|
411
|
+
)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private async call<T>(
|
|
415
|
+
method: string,
|
|
416
|
+
path: string,
|
|
417
|
+
body: Body | undefined,
|
|
418
|
+
answer: Schema<T>,
|
|
419
|
+
): Promise<T> {
|
|
420
|
+
const got = await this.exchange(method, path, body)
|
|
421
|
+
if (got.status >= 400) throw this.refusal(got)
|
|
422
|
+
const parsed = parserOf(answer).safeParse(got.json)
|
|
423
|
+
if (!parsed.success) {
|
|
424
|
+
const why = parsed.error.issues[0]?.message ?? 'invalid'
|
|
425
|
+
throw new PlatformError(
|
|
426
|
+
`The platform's answer to ${path} is not what this tool expects: ${why}.`,
|
|
427
|
+
got.status,
|
|
428
|
+
)
|
|
429
|
+
}
|
|
430
|
+
return parsed.data
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** For a route answered 204 with no body; any other success is not what this tool expects. */
|
|
434
|
+
private async callNoContent(method: string, path: string, body?: Body): Promise<void> {
|
|
435
|
+
const got = await this.exchange(method, path, body)
|
|
436
|
+
if (got.status >= 400) throw this.refusal(got)
|
|
437
|
+
if (got.status !== 204) {
|
|
438
|
+
throw new PlatformError(
|
|
439
|
+
`The answer to ${path} is not what this tool expects: status ${got.status}, not 204.`,
|
|
440
|
+
got.status,
|
|
441
|
+
)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* One request, and where a signed-in person's token was refused as `unauthorized`, one more with
|
|
447
|
+
* a fresh one: the refresh token is spent once and a second refusal is the answer, so this never
|
|
448
|
+
* loops. A 401 that is not the platform's refusal of the sign-in (a proxy's, say) spends nothing.
|
|
449
|
+
*/
|
|
450
|
+
private async exchange(method: string, path: string, body: Body | undefined): Promise<Exchange> {
|
|
451
|
+
const token = this.tokens ? await this.tokens.accessToken() : this.publishKey
|
|
452
|
+
const first = await this.once(method, path, body, token)
|
|
453
|
+
if (first.status !== 401 || !this.tokens || !token) return first
|
|
454
|
+
if (refusalCodeOf(first) !== 'unauthorized') return first
|
|
455
|
+
const renewed = await this.tokens.refresh(token)
|
|
456
|
+
return renewed ? this.once(method, path, body, renewed) : first
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
private async once(
|
|
460
|
+
method: string,
|
|
461
|
+
path: string,
|
|
462
|
+
body: Body | undefined,
|
|
463
|
+
token: string | undefined,
|
|
464
|
+
): Promise<Exchange> {
|
|
465
|
+
const headers = new Headers({
|
|
466
|
+
accept: 'application/json',
|
|
467
|
+
authorization: `Bearer ${token}`,
|
|
468
|
+
[VERSION_HEADER]: this.version,
|
|
469
|
+
})
|
|
470
|
+
if (body !== undefined) headers.set('content-type', 'application/json')
|
|
471
|
+
const response = await this.send(`${this.base}${path}`, {
|
|
472
|
+
method,
|
|
473
|
+
headers,
|
|
474
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
475
|
+
})
|
|
476
|
+
return { status: response.status, json: parseJson(await response.text()) }
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
private refusal(got: Exchange): PlatformError {
|
|
480
|
+
const failure = parserOf(platformFailure).safeParse(got.json)
|
|
481
|
+
const details = failure.success ? failure.data : undefined
|
|
482
|
+
// Only the platform's own refusal naming the version it needs: a 426 from anything in between
|
|
483
|
+
// (a proxy asking for another protocol) is not about this tool's version.
|
|
484
|
+
const minimum = minimumVersion.safeParse(details?.details?.['minimum'])
|
|
485
|
+
if (got.status === 426 && minimum.success) {
|
|
486
|
+
return new UpgradeRequiredError(
|
|
487
|
+
`This version of gm (${this.version}) is too old for the platform: ${minimum.data} or newer is needed. Update @greenmind/cli and the packages beside it, and run the command again.`,
|
|
488
|
+
got.status,
|
|
489
|
+
details,
|
|
490
|
+
)
|
|
491
|
+
}
|
|
492
|
+
if (got.status === 401 && this.tokens && details?.error === 'unauthorized') {
|
|
493
|
+
return new PlatformError(
|
|
494
|
+
'The platform did not accept your sign-in. Run `gm login` to sign in again.',
|
|
495
|
+
got.status,
|
|
496
|
+
details,
|
|
497
|
+
)
|
|
498
|
+
}
|
|
499
|
+
if (got.status === 503 && details?.error === 'unavailable') {
|
|
500
|
+
return new PlatformError(
|
|
501
|
+
'Your sign-in could not be checked with GreenMind just now, and nothing was changed. Try again in a moment.',
|
|
502
|
+
got.status,
|
|
503
|
+
details,
|
|
504
|
+
)
|
|
505
|
+
}
|
|
506
|
+
if (!failure.success) {
|
|
507
|
+
return new PlatformError(`The platform answered ${got.status}.`, got.status)
|
|
508
|
+
}
|
|
509
|
+
return new PlatformError(
|
|
510
|
+
`${failure.data.error}: ${failure.data.message}`,
|
|
511
|
+
got.status,
|
|
512
|
+
failure.data,
|
|
513
|
+
)
|
|
514
|
+
}
|
|
515
|
+
}
|