@greenmind/cli 0.0.0-stage → 0.9.40

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.
@@ -0,0 +1,274 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { functionRequest, type Json, parserOf, s } from '@greenmind/ext-schema'
3
+ import {
4
+ checkProject,
5
+ type CompiledDefinition,
6
+ type DefinitionBase,
7
+ type FunctionAnswer,
8
+ type FunctionDef,
9
+ type FunctionRequest,
10
+ } from '@greenmind/ext-sdk'
11
+ import { buildBundle, RUNTIME } from './bundle'
12
+ import type { PlatformClient } from './client'
13
+ import { loadDefinitions, loadModule, LoadError } from './load'
14
+ import type { CheckIssue, SourceRef } from './protocol'
15
+
16
+ /**
17
+ * What each command does, apart from reading arguments and the environment: each takes what it
18
+ * needs and a `print`, and answers whether it went well, so a test drives it without a terminal.
19
+ */
20
+
21
+ export type Print = (line: string) => void
22
+
23
+ const short = (hash: string) => hash.slice(0, 12)
24
+
25
+ function describe(definition: CompiledDefinition): string {
26
+ return `${definition.kind.padEnd(10)} ${definition.key} ${short(definition.contentHash)}`
27
+ }
28
+
29
+ /** An environment's issue or one the SDK found, which name their definition the same way. */
30
+ type Issue = Pick<CheckIssue, 'key' | 'step' | 'message'> & { readonly kind: string }
31
+
32
+ function printIssues(issues: readonly Issue[], print: Print): void {
33
+ for (const issue of issues) {
34
+ const step = issue.step ? ` (step ${issue.step})` : ''
35
+ print(` ${issue.kind} ${issue.key}${step}: ${issue.message}`)
36
+ }
37
+ }
38
+
39
+ /**
40
+ * The gateway rules the files can be held to without an environment, printed when broken. What
41
+ * `wraps` may name is the environment's to say, so only its check holds that one.
42
+ */
43
+ function passesRules(definitions: readonly CompiledDefinition[], print: Print): boolean {
44
+ const issues = checkProject(definitions)
45
+ if (issues.length === 0) return true
46
+ print(`${issues.length} rule${issues.length === 1 ? ' is' : 's are'} broken:`)
47
+ printIssues(issues, print)
48
+ return false
49
+ }
50
+
51
+ export interface CheckOptions {
52
+ readonly paths: readonly string[]
53
+ /** With a client the environment's own validation runs too; without, only what the SDK can say. */
54
+ readonly client?: PlatformClient
55
+ /** The environment checked against; the client's own when left out. */
56
+ readonly appKey?: string
57
+ }
58
+
59
+ /** Compiles the files, so everything the SDK and the stored form refuse is refused, then asks the environment. */
60
+ export async function runCheck(options: CheckOptions, print: Print): Promise<boolean> {
61
+ const definitions = await loadDefinitions(options.paths)
62
+ for (const definition of definitions) print(describe(definition))
63
+ if (!passesRules(definitions, print)) return false
64
+ if (!options.client) {
65
+ print(
66
+ `${definitions.length} definitions compile. Give a platform address and key to check them against an environment.`,
67
+ )
68
+ return true
69
+ }
70
+ const answer = await options.client.check(definitions, options.appKey)
71
+ if (answer.issues.length > 0) {
72
+ print(
73
+ `${answer.environment.appKey} refuses ${answer.issues.length} issue${answer.issues.length === 1 ? '' : 's'}:`,
74
+ )
75
+ printIssues(answer.issues, print)
76
+ return false
77
+ }
78
+ print(`${answer.environment.appKey} accepts all ${definitions.length}.`)
79
+ return true
80
+ }
81
+
82
+ export interface PushOptions {
83
+ readonly paths: readonly string[]
84
+ readonly client: PlatformClient
85
+ readonly source?: SourceRef
86
+ /** Also make each pushed version live. */
87
+ readonly live?: boolean
88
+ /** With `live`, take the flows and schedules the files no longer hold off the live set. */
89
+ readonly retire?: boolean
90
+ /** The environment pushed to; the client's own when left out. */
91
+ readonly appKey?: string
92
+ }
93
+
94
+ /**
95
+ * Checks the files against the environment, and only if it accepts them pushes them, and with
96
+ * `live` makes them live. Whether the caller may is the platform's to say: `edit_config` there.
97
+ */
98
+ export async function runPush(options: PushOptions, print: Print): Promise<boolean> {
99
+ const definitions = await loadDefinitions(options.paths)
100
+ if (!passesRules(definitions, print)) return false
101
+ const checked = await options.client.check(definitions, options.appKey)
102
+ if (checked.issues.length > 0) {
103
+ print(
104
+ `${checked.environment.appKey} refuses ${checked.issues.length} issue${checked.issues.length === 1 ? '' : 's'}, so nothing was pushed:`,
105
+ )
106
+ printIssues(checked.issues, print)
107
+ return false
108
+ }
109
+ const pushed = await options.client.push(
110
+ definitions,
111
+ options.source,
112
+ options.live,
113
+ options.appKey,
114
+ options.retire,
115
+ )
116
+ for (const result of pushed.results) {
117
+ print(
118
+ `${result.created ? 'new version' : 'unchanged '} ${result.kind.padEnd(10)} ${result.key} ${short(result.contentHash)}`,
119
+ )
120
+ }
121
+ for (const each of pushed.retired ?? []) print(`retired ${each.kind.padEnd(10)} ${each.key}`)
122
+ const made = pushed.results.filter((result) => result.created).length
123
+ const retired = pushed.retired?.length ? ` ${pushed.retired.length} retired.` : ''
124
+ print(
125
+ `${pushed.environment.appKey}: ${made} new, ${pushed.results.length - made} unchanged.${pushed.live ? ' All made live.' : ''}${retired}`,
126
+ )
127
+ const landing = landingLine(pushed.landing)
128
+ if (landing) print(landing)
129
+ return true
130
+ }
131
+
132
+ /** What a live push's landing means for the game database; nothing where there was none to land. */
133
+ function landingLine(landing: 'landed' | 'pending' | undefined): string | null {
134
+ switch (landing) {
135
+ case 'landed':
136
+ return 'Landed in the game database.'
137
+ case 'pending':
138
+ return 'Landing in the game database is pending; it is retried automatically until the engine takes it.'
139
+ case undefined:
140
+ return null
141
+ }
142
+ }
143
+
144
+ export interface UploadOptions {
145
+ readonly paths: readonly string[]
146
+ readonly client: PlatformClient
147
+ readonly source?: SourceRef
148
+ /** Bun build plugins the bundle's sources need to compile. */
149
+ readonly plugins?: readonly import('bun').BunPlugin[]
150
+ /** The environment uploaded to; the client's own when left out. */
151
+ readonly appKey?: string
152
+ }
153
+
154
+ /**
155
+ * Builds the functions the files define into one bundle and uploads it to the environment, with
156
+ * the functions as versions naming it. Like a push, it asks the environment to check them first.
157
+ */
158
+ export async function runUpload(options: UploadOptions, print: Print): Promise<boolean> {
159
+ const bundle = await buildBundle(options.paths, options.plugins)
160
+ print(`bundle ${short(bundle.contentHash)} ${bundle.bytes.length} bytes`)
161
+ const checked = await options.client.check(bundle.definitions, options.appKey)
162
+ if (checked.issues.length > 0) {
163
+ print(
164
+ `${checked.environment.appKey} refuses ${checked.issues.length} issue${checked.issues.length === 1 ? '' : 's'}, so nothing was uploaded:`,
165
+ )
166
+ printIssues(checked.issues, print)
167
+ return false
168
+ }
169
+ const answer = await options.client.upload(
170
+ {
171
+ bundle: Buffer.from(bundle.bytes).toString('base64'),
172
+ contentHash: bundle.contentHash,
173
+ runtime: RUNTIME,
174
+ definitions: bundle.definitions,
175
+ source: options.source,
176
+ },
177
+ options.appKey,
178
+ )
179
+ for (const result of answer.results) {
180
+ print(
181
+ `${result.created ? 'new version' : 'unchanged '} ${result.kind.padEnd(10)} ${result.key} ${short(result.contentHash)}`,
182
+ )
183
+ }
184
+ const where =
185
+ answer.deployment.target === 'lambda'
186
+ ? `Lambda function ${answer.deployment.functionName ?? ''}`.trim()
187
+ : 'the local host'
188
+ print(
189
+ `${answer.environment.appKey}: bundle ${answer.artifact.created ? 'stored' : 'already held'}, runs on ${where}.`,
190
+ )
191
+ return true
192
+ }
193
+
194
+ /** The compiled definitions as JSON, as they would be pushed. */
195
+ export async function runCompile(paths: readonly string[], print: Print): Promise<void> {
196
+ print(JSON.stringify(await loadDefinitions(paths), null, 2))
197
+ }
198
+
199
+ /** A recorded event for a local run: what the engine would have handed the function. */
200
+ const recordedRequest = s.object({
201
+ input: s.json(),
202
+ /** Each read's result by name, as the engine would have read them. */
203
+ data: s.optional(s.record(s.json())),
204
+ player: s.optional(s.object({ playerId: s.id() })),
205
+ appKey: s.optional(s.string({ maxLength: 64 })),
206
+ seed: s.optional(s.string({ pattern: '^[0-9a-f]{64}$' })),
207
+ now: s.optional(s.timestamp()),
208
+ })
209
+
210
+ export interface RunOptions {
211
+ readonly file: string
212
+ readonly functionKey: string
213
+ /** A JSON file with the recorded `input` and, if the function reads, the `data` to give it. */
214
+ readonly recordedFile: string
215
+ readonly seed?: string
216
+ readonly now?: string
217
+ }
218
+
219
+ function isFunction(
220
+ definition: DefinitionBase,
221
+ ): definition is FunctionDef<string, object, unknown> {
222
+ return definition.kind === 'function' && 'invoke' in definition
223
+ }
224
+
225
+ /** Builds the request the engine would send for a recorded event. */
226
+ export function requestFor(options: RunOptions, recorded: Json): FunctionRequest {
227
+ const parsed = parserOf(recordedRequest).safeParse(recorded)
228
+ if (!parsed.success) {
229
+ const issue = parsed.error.issues[0]
230
+ const where = issue?.path.length ? ` at ${issue.path.join('.')}` : ''
231
+ throw new LoadError(`The recorded event is not valid${where}: ${issue?.message ?? 'invalid'}.`)
232
+ }
233
+ const event = parsed.data
234
+ const request = {
235
+ protocol: 1,
236
+ handler: options.functionKey,
237
+ phase: 'run',
238
+ runId: 'local',
239
+ stepId: options.functionKey.replaceAll('.', '-').replaceAll('_', '-'),
240
+ attempt: 1,
241
+ appKey: event.appKey ?? 'local',
242
+ player: event.player,
243
+ input: event.input,
244
+ data: event.data ?? {},
245
+ seed: options.seed ?? event.seed ?? '00'.repeat(32),
246
+ now: options.now ?? event.now ?? new Date().toISOString(),
247
+ deadlineMs: 30_000,
248
+ }
249
+ const checked = parserOf(functionRequest).safeParse(request)
250
+ if (!checked.success) {
251
+ throw new LoadError(
252
+ `The request is not valid: ${checked.error.issues[0]?.message ?? 'invalid'}.`,
253
+ )
254
+ }
255
+ return checked.data
256
+ }
257
+
258
+ /** Runs one function on a recorded event, in process, with no engine and no network. */
259
+ export async function runFunction(options: RunOptions, print: Print): Promise<FunctionAnswer> {
260
+ const definitions = await loadModule(options.file)
261
+ const found = definitions
262
+ .filter(isFunction)
263
+ .find((definition) => definition.key === options.functionKey)
264
+ if (!found) {
265
+ const known = definitions.filter(isFunction).map((definition) => definition.key)
266
+ throw new LoadError(
267
+ `${options.file} exports no function called "${options.functionKey}"${known.length > 0 ? `; it exports ${known.join(', ')}` : ''}.`,
268
+ )
269
+ }
270
+ const recorded: Json = JSON.parse(readFileSync(options.recordedFile, 'utf8'))
271
+ const answer = found.invoke(requestFor(options, recorded))
272
+ print(JSON.stringify(answer, null, 2))
273
+ return answer
274
+ }
@@ -0,0 +1,39 @@
1
+ import pkg from '../package.json'
2
+
3
+ /**
4
+ * The few values this tool knows before it has asked a platform anything. Where to sign in, and
5
+ * with which client and scopes, are the platform's to say (`GET /cli` on the developer API);
6
+ * `gm login` reads them from the platform it signs in to, and a flag overrides each.
7
+ */
8
+
9
+ /** The developer API a command calls when neither `--url` nor `GM_DEVELOPER_URL` names one. */
10
+ export const DEFAULT_PLATFORM_URL = 'https://developer.publishing.greenmindmedia.com'
11
+
12
+ /**
13
+ * The command line's client at GreenMind's identity server: the same on every stage, and what the
14
+ * platform's answer names unless a stage says otherwise.
15
+ */
16
+ export const CLIENT_ID = 'greenmind-cli'
17
+
18
+ /**
19
+ * What a sign-in asks for when the platform's answer cannot be read and an issuer was given by
20
+ * hand. `offline_access` is what makes the server issue a refresh token.
21
+ */
22
+ export const BASE_SCOPES = ['openid', 'offline_access', 'ext:read', 'ext:manage'] as const
23
+
24
+ export const DISCOVERY_PATH = '/.well-known/openid-configuration'
25
+
26
+ /** Carries the tool's version on every request, so the platform can ask for a newer one. */
27
+ export const VERSION_HEADER = 'x-gm-cli-version'
28
+
29
+ export const CLI_VERSION: string = pkg.version
30
+
31
+ export const ENV_URL = 'GM_DEVELOPER_URL'
32
+ /** The handle of the org whose environments a command names, when `--org` does not. */
33
+ export const ENV_ORG = 'GM_ORG'
34
+ /** An org key a build calls with, when `--key` gives none. */
35
+ export const ENV_KEY = 'GM_PUBLISH_KEY'
36
+ export const ENV_ISSUER = 'GM_IDENTITY_URL'
37
+
38
+ /** Names the directory the credentials file lives in, in place of the user's config directory. */
39
+ export const ENV_CONFIG_DIR = 'GM_CONFIG_DIR'
@@ -0,0 +1,159 @@
1
+ import {
2
+ chmodSync,
3
+ closeSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ openSync,
7
+ readFileSync,
8
+ renameSync,
9
+ rmSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import { type Infer, type Json, parserOf, s } from '@greenmind/ext-schema'
16
+ import { ENV_CONFIG_DIR } from './constants'
17
+
18
+ /**
19
+ * Where a signed-in person's tokens are kept: one file in the user's own configuration directory,
20
+ * keyed by platform address, holding the tokens and nothing that works without signing in (never an
21
+ * org key). Changes to it go through `withLock`, because a refresh token is
22
+ * spent by one use and two processes must not both spend it.
23
+ */
24
+
25
+ const storedLogin = s.object({
26
+ /** The identity server that issued the tokens; its discovery document names the endpoints. */
27
+ issuer: s.string(),
28
+ clientId: s.string(),
29
+ accessToken: s.string(),
30
+ /** Absent where the server issued none, which leaves a sign-in good until the access token ends. */
31
+ refreshToken: s.optional(s.string()),
32
+ /** When the access token stops being accepted, as an instant. */
33
+ expiresAt: s.timestamp(),
34
+ scope: s.string(),
35
+ user: s.object({
36
+ subject: s.optional(s.string()),
37
+ name: s.optional(s.string()),
38
+ email: s.optional(s.string()),
39
+ }),
40
+ })
41
+
42
+ const credentialsFile = s.object({
43
+ version: s.int({ min: 1, max: 1 }),
44
+ logins: s.record(storedLogin),
45
+ })
46
+
47
+ export type StoredLogin = Infer<typeof storedLogin>
48
+ type CredentialsFile = Infer<typeof credentialsFile>
49
+
50
+ const LOCK_FILE = 'credentials.lock'
51
+ const LOCK_WAIT_MS = 15_000
52
+ /** A lock older than this was left by a process that died, since a refresh takes seconds. */
53
+ const LOCK_STALE_MS = 45_000
54
+
55
+ export function credentialsDir(env: NodeJS.ProcessEnv = process.env): string {
56
+ const named = env[ENV_CONFIG_DIR]
57
+ if (named) return named
58
+ if (process.platform === 'win32') {
59
+ return join(env['APPDATA'] ?? join(homedir(), 'AppData', 'Roaming'), 'greenmind')
60
+ }
61
+ return join(homedir(), '.config', 'greenmind')
62
+ }
63
+
64
+ /** One address however it was typed: no trailing slash. */
65
+ export function loginKey(platformUrl: string): string {
66
+ return platformUrl.trim().replace(/\/+$/, '')
67
+ }
68
+
69
+ function fileIn(dir: string): string {
70
+ return join(dir, 'credentials.json')
71
+ }
72
+
73
+ function readFile(dir: string): CredentialsFile {
74
+ const path = fileIn(dir)
75
+ if (!existsSync(path)) return { version: 1, logins: {} }
76
+ let body: Json
77
+ try {
78
+ body = JSON.parse(readFileSync(path, 'utf8'))
79
+ } catch {
80
+ throw new Error(`${path} is not valid JSON. Delete it and run \`gm login\` again.`)
81
+ }
82
+ const parsed = parserOf(credentialsFile).safeParse(body)
83
+ if (!parsed.success) {
84
+ throw new Error(
85
+ `${path} is not a credentials file this version reads. Delete it and run \`gm login\` again.`,
86
+ )
87
+ }
88
+ return parsed.data
89
+ }
90
+
91
+ function ensureDir(dir: string): void {
92
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
93
+ // mkdir leaves an existing directory as it was, and the mode is masked by the umask.
94
+ if (process.platform !== 'win32') chmodSync(dir, 0o700)
95
+ }
96
+
97
+ function writeFile(dir: string, file: CredentialsFile): void {
98
+ ensureDir(dir)
99
+ const path = fileIn(dir)
100
+ const staged = `${path}.${process.pid}.tmp`
101
+ writeFileSync(staged, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 })
102
+ if (process.platform !== 'win32') chmodSync(staged, 0o600)
103
+ renameSync(staged, path)
104
+ }
105
+
106
+ export function readLogin(dir: string, platformUrl: string): StoredLogin | undefined {
107
+ return readFile(dir).logins[loginKey(platformUrl)]
108
+ }
109
+
110
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
111
+
112
+ /**
113
+ * Runs `body` holding the credentials lock: a file made exclusively, taken over only when it is
114
+ * older than any refresh could take.
115
+ */
116
+ export async function withLock<T>(dir: string, body: () => Promise<T>): Promise<T> {
117
+ ensureDir(dir)
118
+ const lock = join(dir, LOCK_FILE)
119
+ const giveUpAt = Date.now() + LOCK_WAIT_MS
120
+ for (;;) {
121
+ try {
122
+ closeSync(openSync(lock, 'wx', 0o600))
123
+ break
124
+ } catch (error) {
125
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error
126
+ try {
127
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
128
+ rmSync(lock, { force: true })
129
+ continue
130
+ }
131
+ } catch {
132
+ continue
133
+ }
134
+ if (Date.now() > giveUpAt) {
135
+ throw new Error(`Another \`ext\` process holds ${lock}. Try again, or delete the file.`)
136
+ }
137
+ await sleep(25)
138
+ }
139
+ }
140
+ try {
141
+ return await body()
142
+ } finally {
143
+ rmSync(lock, { force: true })
144
+ }
145
+ }
146
+
147
+ /** Replaces or removes one platform's login; the caller holds the lock where it read first. */
148
+ export function writeLogin(dir: string, platformUrl: string, login: StoredLogin | undefined): void {
149
+ const file = readFile(dir)
150
+ const logins = { ...file.logins }
151
+ if (login) logins[loginKey(platformUrl)] = login
152
+ else delete logins[loginKey(platformUrl)]
153
+ writeFile(dir, { version: 1, logins })
154
+ }
155
+
156
+ /** Every platform address with a stored login, for a command that was given none. */
157
+ export function storedPlatforms(dir: string): string[] {
158
+ return Object.keys(readFile(dir).logins)
159
+ }