@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,470 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import {
3
+ type CollectionStorageAnswer,
4
+ type CollectionStorageName,
5
+ type CollectionStorageUnavailable,
6
+ type ConnectorCheckAnswer,
7
+ configDefaultsRequest,
8
+ type EnvironmentStatus,
9
+ type FunctionRuntimeAnswer,
10
+ type FunctionRuntimeEffect,
11
+ type FunctionRuntimeName,
12
+ parserOf,
13
+ SETUP_ITEMS_MAX,
14
+ type SeededValue,
15
+ } from '@greenmind/ext-schema'
16
+ import type { PlatformClient } from './client'
17
+ import { type Print, runPush, runUpload } from './commands'
18
+ import type { LoadedExtConfig } from './ext-config'
19
+ import { loadDefinitions, LoadError } from './load'
20
+ import type { SourceRef } from './protocol'
21
+
22
+ /**
23
+ * What each environment-setup command does once it has a client: ask the platform, print what it
24
+ * said in a readable layout, answer whether it went well.
25
+ */
26
+
27
+ /** Rows laid out in columns two spaces apart, the last cell of each left as long as it is. */
28
+ export function columns(rows: readonly (readonly string[])[], indent = ''): string[] {
29
+ const widths = rows.reduce<number[]>((all, row) => {
30
+ row.forEach((cell, at) => {
31
+ all[at] = Math.max(all[at] ?? 0, cell.length)
32
+ })
33
+ return all
34
+ }, [])
35
+ return rows.map(
36
+ (row) =>
37
+ indent +
38
+ row
39
+ .map((cell, at) => (at === row.length - 1 ? cell : cell.padEnd(widths[at] ?? 0)))
40
+ .join(' ')
41
+ .trimEnd(),
42
+ )
43
+ }
44
+
45
+ const when = (instant: string | null) => instant ?? 'never'
46
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`
47
+
48
+ export async function runEnvironmentList(
49
+ client: PlatformClient,
50
+ project: string,
51
+ print: Print,
52
+ ): Promise<boolean> {
53
+ const { environments } = await client.listEnvironments(project)
54
+ if (environments.length === 0) {
55
+ print(`You can read no environments of ${project}.`)
56
+ return true
57
+ }
58
+ const rows = environments.map((each) => [
59
+ each.appKey,
60
+ each.environment,
61
+ `${each.org.name} / ${each.project.name}`,
62
+ each.level ? `can ${each.level}` : '',
63
+ ])
64
+ for (const line of columns([
65
+ ['APP KEY', 'ENVIRONMENT', 'ORGANISATION / PROJECT', 'ACCESS'],
66
+ ...rows,
67
+ ])) {
68
+ print(line)
69
+ }
70
+ return true
71
+ }
72
+
73
+ function runtimeLine(effect: FunctionRuntimeEffect | null): string[] {
74
+ if (!effect) return ['Runtime nothing was ever asked of it']
75
+ const lines = [
76
+ `Runtime wanted ${effect.wanted}, in effect ${effect.inEffect ?? 'not yet'} (${effect.status})`,
77
+ ` asked ${effect.requestedAt}, applied ${when(effect.appliedAt)}`,
78
+ ]
79
+ if (effect.problem) lines.push(` problem: ${effect.problem}`)
80
+ return lines
81
+ }
82
+
83
+ /** Every field of an environment's status, grouped the way somebody reads it. */
84
+ export function describeStatus(status: EnvironmentStatus): string[] {
85
+ const lines: string[] = [
86
+ `${status.appKey} ${status.name} (${status.environment})`,
87
+ `Project ${status.project.name} (${status.project.key})`,
88
+ status.gameDatabaseKey
89
+ ? `Database ${status.gameDatabaseKey}`
90
+ : 'Database none: its functions and flows run nowhere yet',
91
+ ]
92
+ const { writer } = status
93
+ lines.push(
94
+ `Writer ${writer.writer}${writer.switchedAt ? `, switched ${writer.switchedAt} by ${writer.switchedBy ?? 'unknown'}` : ', never switched'}`,
95
+ )
96
+ if (writer.waitMs !== null) {
97
+ lines.push(` paused: the engine may start in ${Math.ceil(writer.waitMs / 1000)} s`)
98
+ }
99
+ lines.push(...runtimeLine(status.runtime))
100
+ lines.push(`Flows ${status.flows.on} of ${status.flows.total} on`)
101
+ lines.push('Definitions')
102
+ if (status.definitions.length === 0) lines.push(' none')
103
+ for (const kind of status.definitions) {
104
+ lines.push(` ${kind.kind}: ${kind.total} total, ${kind.live} live`)
105
+ lines.push(
106
+ ...columns(
107
+ kind.definitions.map((each) => [
108
+ each.key,
109
+ each.liveVersion === null ? 'no live version' : `v${each.liveVersion}`,
110
+ each.contentHash?.slice(0, 12) ?? '',
111
+ ]),
112
+ ' ',
113
+ ),
114
+ )
115
+ }
116
+ const landing = status.lastLanding
117
+ if (landing) {
118
+ lines.push(
119
+ `Last landing ${landing.landingId} on ${landing.gameDatabaseKey}: ${landing.status} (${landing.scope}, ${plural(landing.attempts, 'attempt')})`,
120
+ ` queued ${landing.queuedAt}, landed ${when(landing.landedAt)}`,
121
+ )
122
+ if (landing.lastError) lines.push(` error: ${landing.lastError}`)
123
+ } else {
124
+ lines.push('Last landing nothing was ever landed or queued')
125
+ }
126
+ const { actAsServer, editConfig } = status.keys
127
+ lines.push(
128
+ `Org keys ${actAsServer.live} live acting as a server, ${actAsServer.revoked} revoked`,
129
+ ` ${editConfig.live} live holding edit_config, ${editConfig.revoked} revoked`,
130
+ )
131
+ return lines
132
+ }
133
+
134
+ export async function runEnvironmentStatus(
135
+ client: PlatformClient,
136
+ appKey: string,
137
+ print: Print,
138
+ ): Promise<boolean> {
139
+ for (const line of describeStatus(await client.environmentStatus(appKey))) print(line)
140
+ return true
141
+ }
142
+
143
+ /** The values in a file: `{ values: [...] }` as the route takes them, or the list alone. */
144
+ export function readSeedFile(file: string): readonly SeededValue[] {
145
+ let body: object | null
146
+ try {
147
+ body = JSON.parse(readFileSync(file, 'utf8'))
148
+ } catch (error) {
149
+ throw new LoadError(
150
+ `${file} is not valid JSON: ${error instanceof Error ? error.message : error}.`,
151
+ )
152
+ }
153
+ const parsed = parserOf(configDefaultsRequest).safeParse(
154
+ Array.isArray(body) ? { values: body } : body,
155
+ )
156
+ if (!parsed.success) {
157
+ const issue = parsed.error.issues[0]
158
+ throw new LoadError(
159
+ `${file} is not a list of config values${issue?.path.length ? ` (at ${issue.path.join('.')})` : ''}: ${issue?.message ?? 'invalid'}.`,
160
+ )
161
+ }
162
+ return parsed.data.values
163
+ }
164
+
165
+ function chunks<T>(items: readonly T[]): T[][] {
166
+ const out: T[][] = []
167
+ for (let at = 0; at < items.length; at += SETUP_ITEMS_MAX) {
168
+ out.push(items.slice(at, at + SETUP_ITEMS_MAX))
169
+ }
170
+ return out
171
+ }
172
+
173
+ export async function runConfigSeed(
174
+ client: PlatformClient,
175
+ values: readonly SeededValue[],
176
+ print: Print,
177
+ appKey?: string,
178
+ ): Promise<boolean> {
179
+ if (values.length === 0) {
180
+ print('There are no config values to seed.')
181
+ return true
182
+ }
183
+ const seeded: string[] = []
184
+ for (const part of chunks(values)) {
185
+ seeded.push(...(await client.seedConfigDefaults(part, appKey)).seeded)
186
+ }
187
+ for (const name of seeded) print(`seeded ${name}`)
188
+ print(
189
+ `${seeded.length} of ${plural(values.length, 'value')} seeded; the rest the environment already holds and are left as they are.`,
190
+ )
191
+ return true
192
+ }
193
+
194
+ export async function runFlowSwitch(
195
+ client: PlatformClient,
196
+ keys: readonly string[],
197
+ enabled: boolean,
198
+ print: Print,
199
+ appKey?: string,
200
+ ): Promise<boolean> {
201
+ if (keys.length === 0) {
202
+ print('There are no flows to switch.')
203
+ return true
204
+ }
205
+ for (const part of chunks(keys)) {
206
+ const answer = await client.switchFlows(
207
+ part.map((key) => ({ key, enabled })),
208
+ appKey,
209
+ )
210
+ for (const flow of answer.flows) print(`${flow.enabled ? 'on ' : 'off'} ${flow.key}`)
211
+ }
212
+ print(`${plural(keys.length, 'flow')} switched ${enabled ? 'on' : 'off'}.`)
213
+ return true
214
+ }
215
+
216
+ /**
217
+ * Replays the kept events of a window into one flow, call after call until the window is done, so
218
+ * one command covers a window of any size. A repeat starts nothing the first did.
219
+ */
220
+ export async function runEventsReplay(
221
+ client: Pick<PlatformClient, 'replayEvents'>,
222
+ window: { flow: string; from?: string; to?: string },
223
+ print: Print,
224
+ appKey?: string,
225
+ ): Promise<boolean> {
226
+ let events = 0
227
+ let queued = 0
228
+ let after: string | undefined
229
+ let span = ''
230
+ for (;;) {
231
+ const answer = await client.replayEvents(
232
+ after === undefined ? window : { ...window, after },
233
+ appKey,
234
+ )
235
+ events += answer.events
236
+ queued += answer.queued
237
+ span = `${answer.from} to ${answer.to} (the plan keeps ${plural(answer.windowDays, 'day')})`
238
+ if (answer.next === null) break
239
+ after = answer.next
240
+ }
241
+ print(`${window.flow}: ${plural(events, 'kept event')} from ${span}.`)
242
+ print(
243
+ `${plural(queued, 'run')} started; the other events the flow had already run, or its filter turned away.`,
244
+ )
245
+ return true
246
+ }
247
+
248
+ /** Every flow the given paths define, by key. */
249
+ export async function flowKeysOf(paths: readonly string[]): Promise<string[]> {
250
+ const definitions = await loadDefinitions(paths)
251
+ return definitions.filter((definition) => definition.kind === 'flow').map((each) => each.key)
252
+ }
253
+
254
+ export function describeRuntime(answer: FunctionRuntimeAnswer): string[] {
255
+ const lines = [
256
+ `${answer.appKey}`,
257
+ `Options ${answer.options.join(', ')} (its organisation may use these)`,
258
+ `Own choice ${answer.own ?? 'none, it follows the stage default'}`,
259
+ `Stage ${answer.stageDefault ?? 'no default'}`,
260
+ `Wanted ${answer.wanted}`,
261
+ ]
262
+ if (answer.refused) {
263
+ lines.push(
264
+ `Refused its config holds ${answer.refused}, which its organisation may not use, so it runs on Lambda`,
265
+ )
266
+ }
267
+ lines.push(...runtimeLine(answer.effect))
268
+ return lines
269
+ }
270
+
271
+ export async function runRuntimeGet(
272
+ client: PlatformClient,
273
+ appKey: string,
274
+ print: Print,
275
+ ): Promise<boolean> {
276
+ for (const line of describeRuntime(await client.functionRuntime(appKey))) print(line)
277
+ return true
278
+ }
279
+
280
+ export async function runRuntimeSet(
281
+ client: PlatformClient,
282
+ appKey: string,
283
+ runtime: FunctionRuntimeName | null,
284
+ print: Print,
285
+ ): Promise<boolean> {
286
+ for (const line of describeRuntime(await client.setFunctionRuntime(appKey, runtime))) print(line)
287
+ return true
288
+ }
289
+
290
+ /** Why a mode is not available, said for a person reading a terminal. */
291
+ const UNAVAILABLE_WORDS = {
292
+ 'not-granted': 'its organisation has not been given it',
293
+ 'not-placed': 'the environment is on no game database yet',
294
+ 'shared-database':
295
+ "its game database is shared; a table of a collection's own needs the organisation's own database",
296
+ 'not-served': 'the engine it runs on does not offer it yet',
297
+ 'needs-connection': 'no data connection of the environment has passed the connector check',
298
+ } as const satisfies Record<CollectionStorageUnavailable, string>
299
+
300
+ /** What each mode is, in a line. */
301
+ const STORAGE_WORDS = {
302
+ collection: 'shared rows, in the same transaction as platform data',
303
+ dedicated:
304
+ "a table of the collection's own in the organisation's game database; every index is paid for by every write",
305
+ 'self-hosted': 'your own database behind a data connection; not atomic with platform data',
306
+ } as const satisfies Record<CollectionStorageName, string>
307
+
308
+ export function describeCollectionStorage(answer: CollectionStorageAnswer): string[] {
309
+ const lines = [`${answer.appKey}`, 'Modes']
310
+ lines.push(
311
+ ...columns(
312
+ answer.modes.map((each) => [
313
+ each.mode,
314
+ each.available ? 'available' : 'not available',
315
+ each.unavailable
316
+ ? UNAVAILABLE_WORDS[each.unavailable]
317
+ : STORAGE_WORDS[each.mode] + (each.canBeDefault ? '' : '; named per collection only'),
318
+ ]),
319
+ ' ',
320
+ ),
321
+ )
322
+ lines.push(
323
+ `Default ${answer.default} for new collections that name no mode`,
324
+ ` own ${answer.own ?? 'none, it follows its organisation'}, organisation ${answer.orgDefault}`,
325
+ )
326
+ if (answer.own !== null && answer.own !== answer.default) {
327
+ lines.push(
328
+ ` its own ${answer.own} cannot be had here now, so ${answer.default} is used`,
329
+ )
330
+ }
331
+ if (answer.collections === null) {
332
+ lines.push('Collections the engine could not be asked from here')
333
+ } else if (answer.collections.length === 0) {
334
+ lines.push('Collections none released')
335
+ } else {
336
+ lines.push('Collections')
337
+ lines.push(
338
+ ...columns(
339
+ [
340
+ ['KEY', 'KEPT IN', 'DEFINITION NAMES'],
341
+ ...answer.collections.map((each) => [
342
+ each.key,
343
+ each.mode ?? 'nothing yet',
344
+ each.wanted ?? 'no mode',
345
+ ]),
346
+ ],
347
+ ' ',
348
+ ),
349
+ )
350
+ }
351
+ return lines
352
+ }
353
+
354
+ export async function runStorageGet(
355
+ client: PlatformClient,
356
+ appKey: string,
357
+ print: Print,
358
+ ): Promise<boolean> {
359
+ for (const line of describeCollectionStorage(await client.collectionStorage(appKey))) print(line)
360
+ return true
361
+ }
362
+
363
+ export async function runStorageSetDefault(
364
+ client: PlatformClient,
365
+ appKey: string,
366
+ mode: CollectionStorageName | null,
367
+ print: Print,
368
+ ): Promise<boolean> {
369
+ const answer = await client.setCollectionStorageDefault(appKey, mode)
370
+ for (const line of describeCollectionStorage(answer)) print(line)
371
+ return true
372
+ }
373
+
374
+ /** A connector check's result, each rule on a line, the first failure's detail beside it. */
375
+ export function describeConnectorCheck(answer: ConnectorCheckAnswer): string[] {
376
+ const lines = [
377
+ `${answer.appKey} ${answer.connection}: protocol ${answer.protocol} ${answer.ok ? 'passed' : 'failed'}`,
378
+ ]
379
+ lines.push(
380
+ ...columns(
381
+ answer.checks.map((each) => [each.rule, each.ok ? 'ok' : 'FAILED', each.detail ?? '']),
382
+ ' ',
383
+ ),
384
+ )
385
+ lines.push(`Calls ${answer.calls}, the slowest ${answer.slowestMs} ms`)
386
+ lines.push(
387
+ answer.freshUntil
388
+ ? `A collection may name ${answer.connection} as its self-hosted storage until ${answer.freshUntil}.`
389
+ : `No collection may name ${answer.connection} as its self-hosted storage until a check passes.`,
390
+ )
391
+ return lines
392
+ }
393
+
394
+ export async function runConnectorCheck(
395
+ client: PlatformClient,
396
+ appKey: string,
397
+ connection: string,
398
+ print: Print,
399
+ ): Promise<boolean> {
400
+ const answer = await client.checkConnector(appKey, connection)
401
+ for (const line of describeConnectorCheck(answer)) print(line)
402
+ return answer.ok
403
+ }
404
+
405
+ export interface DeployOptions {
406
+ readonly client: PlatformClient
407
+ readonly config: LoadedExtConfig
408
+ readonly source?: SourceRef
409
+ /** The environment deployed to; the client's own when left out. */
410
+ readonly appKey?: string
411
+ /** Take the flows and schedules the files no longer define off the live set as it pushes. */
412
+ readonly retire?: boolean
413
+ }
414
+
415
+ /**
416
+ * Upload, push live, seed config, switch flows on, in that order from the config file, stopping at
417
+ * the first step that fails and saying which. Each step is one the commands of the same names
418
+ * take alone, so a failure can be mended and the step run again.
419
+ */
420
+ export async function runDeploy(options: DeployOptions, print: Print): Promise<boolean> {
421
+ const { client, config, source, appKey, retire } = options
422
+ const steps: { name: string; run: () => Promise<boolean> }[] = [
423
+ {
424
+ name: 'upload',
425
+ run: () =>
426
+ runUpload({ paths: config.paths, client, source, plugins: config.plugins, appKey }, print),
427
+ },
428
+ {
429
+ name: 'push',
430
+ run: () =>
431
+ runPush({ paths: config.paths, client, source, live: true, retire, appKey }, print),
432
+ },
433
+ ]
434
+ if (config.configDefaults.length > 0) {
435
+ steps.push({
436
+ name: 'seed',
437
+ run: () => runConfigSeed(client, config.configDefaults, print, appKey),
438
+ })
439
+ }
440
+ if (config.flowsOn !== undefined) {
441
+ const wanted = config.flowsOn
442
+ steps.push({
443
+ name: 'flows',
444
+ run: async () =>
445
+ runFlowSwitch(
446
+ client,
447
+ wanted === 'all' ? await flowKeysOf(config.paths) : wanted,
448
+ true,
449
+ print,
450
+ appKey,
451
+ ),
452
+ })
453
+ }
454
+ for (const step of steps) {
455
+ print(`== ${step.name}`)
456
+ let ok: boolean
457
+ try {
458
+ ok = await step.run()
459
+ } catch (error) {
460
+ print(`The ${step.name} step failed: ${error instanceof Error ? error.message : error}`)
461
+ return false
462
+ }
463
+ if (!ok) {
464
+ print(`The ${step.name} step failed, so nothing after it was done.`)
465
+ return false
466
+ }
467
+ }
468
+ print(`Deployed ${steps.map((step) => step.name).join(', ')}.`)
469
+ return true
470
+ }
@@ -0,0 +1,107 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { configDefaultsRequest, parserOf, s, type SeededValue } from '@greenmind/ext-schema'
5
+ import type { BunPlugin } from 'bun'
6
+
7
+ /**
8
+ * `ext.config.ts`, the file a project keeps in its root so one command (`gm pub deploy`) knows where
9
+ * its definitions are and what its environment needs. It lives in this package rather than in
10
+ * the SDK because only the command reads it, it names Bun build plugins, and the SDK is also
11
+ * bundled into functions that run on Node.
12
+ */
13
+
14
+ export interface ExtConfig {
15
+ /** Modules or directories holding the project's definitions, relative to the config file. */
16
+ readonly paths: readonly string[]
17
+ /**
18
+ * Bun build plugins the functions' sources need to compile (a macro, say). A studio's plain
19
+ * TypeScript needs none.
20
+ */
21
+ readonly plugins?: readonly BunPlugin[]
22
+ /** Config values the functions need, given to an environment that lacks them and never over a retune. */
23
+ readonly configDefaults?: readonly SeededValue[]
24
+ /** Flows `gm pub deploy` switches on: every flow the paths define, or these keys. Left out, none. */
25
+ readonly flowsOn?: 'all' | readonly string[]
26
+ }
27
+
28
+ /** Gives a config file its type, so what it names is checked as it is written. */
29
+ export function defineExtConfig(config: ExtConfig): ExtConfig {
30
+ return config
31
+ }
32
+
33
+ export interface LoadedExtConfig {
34
+ readonly file: string
35
+ /** `paths`, made absolute against the directory the config file is in. */
36
+ readonly paths: readonly string[]
37
+ readonly plugins: readonly BunPlugin[]
38
+ readonly configDefaults: readonly SeededValue[]
39
+ readonly flowsOn: 'all' | readonly string[] | undefined
40
+ }
41
+
42
+ export class ExtConfigError extends Error {
43
+ override readonly name = 'ExtConfigError'
44
+ }
45
+
46
+ const FILE_NAMES = ['ext.config.ts', 'ext.config.mts', 'ext.config.js', 'ext.config.mjs']
47
+
48
+ /** The config file a command was told of, or the one in the working directory. */
49
+ export function findExtConfig(explicit: string | undefined, cwd = process.cwd()): string {
50
+ if (explicit) {
51
+ const file = resolve(cwd, explicit)
52
+ if (!existsSync(file)) throw new ExtConfigError(`${file} does not exist.`)
53
+ return file
54
+ }
55
+ for (const name of FILE_NAMES) {
56
+ const file = resolve(cwd, name)
57
+ if (existsSync(file)) return file
58
+ }
59
+ throw new ExtConfigError(
60
+ `There is no ext.config.ts in ${cwd}. Create one with defineExtConfig, or name it with --config.`,
61
+ )
62
+ }
63
+
64
+ const stringList = parserOf(s.array(s.string({ minLength: 1 }), { maxItems: 1000 }))
65
+
66
+ /** Loads and checks the config file. Its default export is what `defineExtConfig` returned. */
67
+ export async function loadExtConfig(
68
+ explicit?: string,
69
+ cwd = process.cwd(),
70
+ ): Promise<LoadedExtConfig> {
71
+ const file = findExtConfig(explicit, cwd)
72
+ const module: { default?: Partial<ExtConfig> } = await import(pathToFileURL(file).href)
73
+ const config = module.default
74
+ if (!config || !(config instanceof Object)) {
75
+ throw new ExtConfigError(
76
+ `${file} must export a config as its default: export default defineExtConfig({ ... }).`,
77
+ )
78
+ }
79
+ const paths = stringList.safeParse(config.paths)
80
+ if (!paths.success || paths.data.length === 0) {
81
+ throw new ExtConfigError(`${file}: paths must list at least one module or directory.`)
82
+ }
83
+ const plugins = config.plugins ?? []
84
+ if (!Array.isArray(plugins)) throw new ExtConfigError(`${file}: plugins must be a list.`)
85
+ const defaults = parserOf(configDefaultsRequest).safeParse({
86
+ values: config.configDefaults ?? [],
87
+ })
88
+ if (!defaults.success) {
89
+ const issue = defaults.error.issues[0]
90
+ throw new ExtConfigError(
91
+ `${file}: configDefaults is not valid${issue?.path.length ? ` at ${issue.path.join('.')}` : ''}: ${issue?.message ?? 'invalid'}.`,
92
+ )
93
+ }
94
+ const flows = stringList.safeParse(config.flowsOn)
95
+ if (config.flowsOn !== undefined && config.flowsOn !== 'all' && !flows.success) {
96
+ throw new ExtConfigError(`${file}: flowsOn must be 'all' or a list of flow keys.`)
97
+ }
98
+ const flowsOn = flows.success ? flows.data : config.flowsOn
99
+ const root = dirname(file)
100
+ return {
101
+ file,
102
+ paths: paths.data.map((path) => resolve(root, path)),
103
+ plugins,
104
+ configDefaults: defaults.data.values,
105
+ flowsOn,
106
+ }
107
+ }