@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/src/commands.ts
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { functionRequest, type Json, parserOf, s } from '@greenmind/ext-schema'
|
|
3
|
+
import {
|
|
4
|
+
type CompiledDefinition,
|
|
5
|
+
type DefinitionBase,
|
|
6
|
+
type FunctionAnswer,
|
|
7
|
+
type FunctionDef,
|
|
8
|
+
type FunctionRequest,
|
|
9
|
+
} from '@greenmind/ext-sdk'
|
|
10
|
+
import { buildBundle, RUNTIME } from './bundle'
|
|
11
|
+
import type { PlatformClient } from './client'
|
|
12
|
+
import { loadDefinitions, loadModule, LoadError } from './load'
|
|
13
|
+
import type { CheckIssue, SourceRef } from './protocol'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What each command does, apart from reading arguments and the environment: each takes what it
|
|
17
|
+
* needs and a `print`, and answers whether it went well, so a test drives it without a terminal.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export type Print = (line: string) => void
|
|
21
|
+
|
|
22
|
+
const short = (hash: string) => hash.slice(0, 12)
|
|
23
|
+
|
|
24
|
+
function describe(definition: CompiledDefinition): string {
|
|
25
|
+
return `${definition.kind.padEnd(10)} ${definition.key} ${short(definition.contentHash)}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function printIssues(issues: readonly CheckIssue[], print: Print): void {
|
|
29
|
+
for (const issue of issues) {
|
|
30
|
+
const step = issue.step ? ` (step ${issue.step})` : ''
|
|
31
|
+
print(` ${issue.kind} ${issue.key}${step}: ${issue.message}`)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface CheckOptions {
|
|
36
|
+
readonly paths: readonly string[]
|
|
37
|
+
/** With a client the environment's own validation runs too; without, only what the SDK can say. */
|
|
38
|
+
readonly client?: PlatformClient
|
|
39
|
+
/** The environment a signed-in person checks against; a publish key's own needs no naming. */
|
|
40
|
+
readonly appKey?: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Compiles the files, so everything the SDK and the stored form refuse is refused, then asks the environment. */
|
|
44
|
+
export async function runCheck(options: CheckOptions, print: Print): Promise<boolean> {
|
|
45
|
+
const definitions = await loadDefinitions(options.paths)
|
|
46
|
+
for (const definition of definitions) print(describe(definition))
|
|
47
|
+
if (!options.client) {
|
|
48
|
+
print(
|
|
49
|
+
`${definitions.length} definitions compile. Give a platform address and key to check them against an environment.`,
|
|
50
|
+
)
|
|
51
|
+
return true
|
|
52
|
+
}
|
|
53
|
+
const answer = await options.client.check(definitions, options.appKey)
|
|
54
|
+
if (answer.issues.length > 0) {
|
|
55
|
+
print(
|
|
56
|
+
`${answer.environment.appKey} refuses ${answer.issues.length} issue${answer.issues.length === 1 ? '' : 's'}:`,
|
|
57
|
+
)
|
|
58
|
+
printIssues(answer.issues, print)
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
print(`${answer.environment.appKey} accepts all ${definitions.length}.`)
|
|
62
|
+
return true
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface PushOptions {
|
|
66
|
+
readonly paths: readonly string[]
|
|
67
|
+
readonly client: PlatformClient
|
|
68
|
+
readonly source?: SourceRef
|
|
69
|
+
/** Also make each pushed version live. Only a test environment takes it. */
|
|
70
|
+
readonly live?: boolean
|
|
71
|
+
/** The environment a signed-in person pushes to; a publish key's own needs no naming. */
|
|
72
|
+
readonly appKey?: string
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Checks the files against the environment the key belongs to, and only if it accepts them and is
|
|
77
|
+
* a test environment, pushes them, and with `live` makes them live. An environment a release owns
|
|
78
|
+
* is never pushed to.
|
|
79
|
+
*/
|
|
80
|
+
export async function runPush(options: PushOptions, print: Print): Promise<boolean> {
|
|
81
|
+
const definitions = await loadDefinitions(options.paths)
|
|
82
|
+
const checked = await options.client.check(definitions, options.appKey)
|
|
83
|
+
if (checked.environment.protected) {
|
|
84
|
+
print(
|
|
85
|
+
`${checked.environment.appKey} is changed by a release, not by a push. Push to a test environment and promote from there.`,
|
|
86
|
+
)
|
|
87
|
+
return false
|
|
88
|
+
}
|
|
89
|
+
if (checked.issues.length > 0) {
|
|
90
|
+
print(
|
|
91
|
+
`${checked.environment.appKey} refuses ${checked.issues.length} issue${checked.issues.length === 1 ? '' : 's'}, so nothing was pushed:`,
|
|
92
|
+
)
|
|
93
|
+
printIssues(checked.issues, print)
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
const pushed = await options.client.push(
|
|
97
|
+
definitions,
|
|
98
|
+
options.source,
|
|
99
|
+
options.live,
|
|
100
|
+
options.appKey,
|
|
101
|
+
)
|
|
102
|
+
for (const result of pushed.results) {
|
|
103
|
+
print(
|
|
104
|
+
`${result.created ? 'new version' : 'unchanged '} ${result.kind.padEnd(10)} ${result.key} ${short(result.contentHash)}`,
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
const made = pushed.results.filter((result) => result.created).length
|
|
108
|
+
print(
|
|
109
|
+
`${pushed.environment.appKey}: ${made} new, ${pushed.results.length - made} unchanged.${pushed.live ? ' All made live.' : ''}`,
|
|
110
|
+
)
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface UploadOptions {
|
|
115
|
+
readonly paths: readonly string[]
|
|
116
|
+
readonly client: PlatformClient
|
|
117
|
+
readonly source?: SourceRef
|
|
118
|
+
/** Bun build plugins the bundle's sources need to compile. */
|
|
119
|
+
readonly plugins?: readonly import('bun').BunPlugin[]
|
|
120
|
+
/** The environment a signed-in person uploads to; a publish key's own needs no naming. */
|
|
121
|
+
readonly appKey?: string
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Builds the functions the files define into one bundle and uploads it to the environment the key
|
|
126
|
+
* belongs to, with the functions as versions naming it. Like a push, it asks the environment first
|
|
127
|
+
* and never uploads to one a release owns.
|
|
128
|
+
*/
|
|
129
|
+
export async function runUpload(options: UploadOptions, print: Print): Promise<boolean> {
|
|
130
|
+
const bundle = await buildBundle(options.paths, options.plugins)
|
|
131
|
+
print(`bundle ${short(bundle.contentHash)} ${bundle.bytes.length} bytes`)
|
|
132
|
+
const checked = await options.client.check(bundle.definitions, options.appKey)
|
|
133
|
+
if (checked.environment.protected) {
|
|
134
|
+
print(
|
|
135
|
+
`${checked.environment.appKey} is changed by a release, not by an upload. Upload to a test environment and promote from there.`,
|
|
136
|
+
)
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
if (checked.issues.length > 0) {
|
|
140
|
+
print(
|
|
141
|
+
`${checked.environment.appKey} refuses ${checked.issues.length} issue${checked.issues.length === 1 ? '' : 's'}, so nothing was uploaded:`,
|
|
142
|
+
)
|
|
143
|
+
printIssues(checked.issues, print)
|
|
144
|
+
return false
|
|
145
|
+
}
|
|
146
|
+
const answer = await options.client.upload(
|
|
147
|
+
{
|
|
148
|
+
bundle: Buffer.from(bundle.bytes).toString('base64'),
|
|
149
|
+
contentHash: bundle.contentHash,
|
|
150
|
+
runtime: RUNTIME,
|
|
151
|
+
definitions: bundle.definitions,
|
|
152
|
+
source: options.source,
|
|
153
|
+
},
|
|
154
|
+
options.appKey,
|
|
155
|
+
)
|
|
156
|
+
for (const result of answer.results) {
|
|
157
|
+
print(
|
|
158
|
+
`${result.created ? 'new version' : 'unchanged '} ${result.kind.padEnd(10)} ${result.key} ${short(result.contentHash)}`,
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
const where =
|
|
162
|
+
answer.deployment.target === 'lambda'
|
|
163
|
+
? `Lambda function ${answer.deployment.functionName ?? ''}`.trim()
|
|
164
|
+
: 'the local host'
|
|
165
|
+
print(
|
|
166
|
+
`${answer.environment.appKey}: bundle ${answer.artifact.created ? 'stored' : 'already held'}, runs on ${where}.`,
|
|
167
|
+
)
|
|
168
|
+
return true
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The compiled definitions as JSON, as they would be pushed. */
|
|
172
|
+
export async function runCompile(paths: readonly string[], print: Print): Promise<void> {
|
|
173
|
+
print(JSON.stringify(await loadDefinitions(paths), null, 2))
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** A recorded event for a local run: what the engine would have handed the function. */
|
|
177
|
+
const recordedRequest = s.object({
|
|
178
|
+
input: s.json(),
|
|
179
|
+
/** Each read's result by name, as the engine would have read them. */
|
|
180
|
+
data: s.optional(s.record(s.json())),
|
|
181
|
+
player: s.optional(s.object({ playerId: s.id() })),
|
|
182
|
+
appKey: s.optional(s.string({ maxLength: 64 })),
|
|
183
|
+
seed: s.optional(s.string({ pattern: '^[0-9a-f]{64}$' })),
|
|
184
|
+
now: s.optional(s.timestamp()),
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
export interface RunOptions {
|
|
188
|
+
readonly file: string
|
|
189
|
+
readonly functionKey: string
|
|
190
|
+
/** A JSON file with the recorded `input` and, if the function reads, the `data` to give it. */
|
|
191
|
+
readonly recordedFile: string
|
|
192
|
+
readonly seed?: string
|
|
193
|
+
readonly now?: string
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function isFunction(
|
|
197
|
+
definition: DefinitionBase,
|
|
198
|
+
): definition is FunctionDef<string, object, unknown> {
|
|
199
|
+
return definition.kind === 'function' && 'invoke' in definition
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Builds the request the engine would send for a recorded event. */
|
|
203
|
+
export function requestFor(options: RunOptions, recorded: Json): FunctionRequest {
|
|
204
|
+
const parsed = parserOf(recordedRequest).safeParse(recorded)
|
|
205
|
+
if (!parsed.success) {
|
|
206
|
+
const issue = parsed.error.issues[0]
|
|
207
|
+
const where = issue?.path.length ? ` at ${issue.path.join('.')}` : ''
|
|
208
|
+
throw new LoadError(`The recorded event is not valid${where}: ${issue?.message ?? 'invalid'}.`)
|
|
209
|
+
}
|
|
210
|
+
const event = parsed.data
|
|
211
|
+
const request = {
|
|
212
|
+
protocol: 1,
|
|
213
|
+
handler: options.functionKey,
|
|
214
|
+
phase: 'run',
|
|
215
|
+
runId: 'local',
|
|
216
|
+
stepId: options.functionKey.replaceAll('.', '-').replaceAll('_', '-'),
|
|
217
|
+
attempt: 1,
|
|
218
|
+
appKey: event.appKey ?? 'local',
|
|
219
|
+
player: event.player,
|
|
220
|
+
input: event.input,
|
|
221
|
+
data: event.data ?? {},
|
|
222
|
+
seed: options.seed ?? event.seed ?? '00'.repeat(32),
|
|
223
|
+
now: options.now ?? event.now ?? new Date().toISOString(),
|
|
224
|
+
deadlineMs: 30_000,
|
|
225
|
+
}
|
|
226
|
+
const checked = parserOf(functionRequest).safeParse(request)
|
|
227
|
+
if (!checked.success) {
|
|
228
|
+
throw new LoadError(
|
|
229
|
+
`The request is not valid: ${checked.error.issues[0]?.message ?? 'invalid'}.`,
|
|
230
|
+
)
|
|
231
|
+
}
|
|
232
|
+
return checked.data
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Runs one function on a recorded event, in process, with no engine and no network. */
|
|
236
|
+
export async function runFunction(options: RunOptions, print: Print): Promise<FunctionAnswer> {
|
|
237
|
+
const definitions = await loadModule(options.file)
|
|
238
|
+
const found = definitions
|
|
239
|
+
.filter(isFunction)
|
|
240
|
+
.find((definition) => definition.key === options.functionKey)
|
|
241
|
+
if (!found) {
|
|
242
|
+
const known = definitions.filter(isFunction).map((definition) => definition.key)
|
|
243
|
+
throw new LoadError(
|
|
244
|
+
`${options.file} exports no function called "${options.functionKey}"${known.length > 0 ? `; it exports ${known.join(', ')}` : ''}.`,
|
|
245
|
+
)
|
|
246
|
+
}
|
|
247
|
+
const recorded: Json = JSON.parse(readFileSync(options.recordedFile, 'utf8'))
|
|
248
|
+
const answer = found.invoke(requestFor(options, recorded))
|
|
249
|
+
print(JSON.stringify(answer, null, 2))
|
|
250
|
+
return answer
|
|
251
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
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
|
|
6
|
+
* (`GET /api/platform/v1/ext/tool`); `gm login` reads them from the platform it signs in to, and a
|
|
7
|
+
* flag overrides each.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** The platform API a command talks to when neither `--url` nor `GM_PLATFORM_URL` names one. */
|
|
11
|
+
export const DEFAULT_PLATFORM_URL = 'https://api.greenmindmedia.com'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The command line's client at GreenMind's identity server: the same on every stage, and what the
|
|
15
|
+
* platform's answer names unless a stage says otherwise.
|
|
16
|
+
*/
|
|
17
|
+
export const CLIENT_ID = 'greenmind-cli'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* What a sign-in asks for when the platform's answer cannot be read and an issuer was given by
|
|
21
|
+
* hand. `offline_access` is what makes the server issue a refresh token.
|
|
22
|
+
*/
|
|
23
|
+
export const BASE_SCOPES = ['openid', 'offline_access', 'ext:read', 'ext:manage'] as const
|
|
24
|
+
|
|
25
|
+
export const DISCOVERY_PATH = '/.well-known/openid-configuration'
|
|
26
|
+
|
|
27
|
+
/** Carries the tool's version on every request, so the platform can ask for a newer one. */
|
|
28
|
+
export const VERSION_HEADER = 'x-gm-cli-version'
|
|
29
|
+
|
|
30
|
+
export const CLI_VERSION: string = pkg.version
|
|
31
|
+
|
|
32
|
+
export const ENV_URL = 'GM_PLATFORM_URL'
|
|
33
|
+
export const ENV_KEY = 'GM_PUBLISH_KEY'
|
|
34
|
+
export const ENV_ISSUER = 'GM_IDENTITY_URL'
|
|
35
|
+
|
|
36
|
+
/** Names the directory the credentials file lives in, in place of the user's config directory. */
|
|
37
|
+
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 a
|
|
21
|
+
* publish key or a server 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
|
+
}
|