-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.js
244 lines (190 loc) · 6.04 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import fs from 'node:fs'
import path from 'node:path'
import debug from 'debug'
import faunadb from 'faunadb'
import readline from 'node:readline'
import { globby } from 'globby'
import { execaSync } from 'execa'
import { performance } from 'node:perf_hooks'
import { fileURLToPath } from 'node:url'
import { temporaryFile } from 'tempy'
import fetch, { Headers } from './fetch-ponyfill.cjs'
import { inspect, promisify } from 'node:util'
export { default as locateCache } from './locateCache.cjs'
// Default file extension patterns
export const patterns = {
TS: '**/*.(ts|tsx)',
UDF: '**/*.udf',
SCHEMA: '**/[A-Z]*.(gql|graphql)',
INDEX: '**/*.index',
UDR: '**/*.role',
DOCUMENTS: '**/[a-z]*.(gql|graphql)',
}
const { Client } = faunadb
const errors = {
CACHE_TIMEOUT:
'Value is cached. Please wait at least 60 seconds after creating or renaming a collection or index before reusing its name.',
}
export const ignored = process.env.BRAINYDUCK_IGNORE
? process.env.BRAINYDUCK_IGNORE.split(',')
: ['**/node_modules/**', '**/.git/**']
export const graphqlEndpoint = (() => {
const {
FAUNA_GRAPHQL_DOMAIN = 'graphql.fauna.com',
FAUNA_SCHEME = 'https',
FAUNA_GRAPHQL_PORT,
} = process.env
const base = `${FAUNA_SCHEME}://${FAUNA_GRAPHQL_DOMAIN}${
FAUNA_GRAPHQL_PORT ? `:${FAUNA_GRAPHQL_PORT}` : ``
}`
return {
server: `${base}/graphql`,
import: `${base}/import`,
puke: `https://duckpuke.brainy.sh/`,
}
})()
export const findBin = (name, relative = '.') => {
const local = fileURLToPath(
new URL(path.join(relative, `./node_modules/.bin`, name), import.meta.url)
)
if (fs.existsSync(local)) {
return local
}
if (path.resolve(relative) !== path.resolve('/')) {
return findBin(name, path.join(relative, '..'))
}
throw new Error(`Binary for '${name}' could not be found.`)
}
export const question = (...args) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const q = promisify(rl.question).bind(rl)(...args)
return q.finally(() => rl.close())
}
export const loadSecret = () => {
const secret = process.env.FAUNA_SECRET
if (!secret) {
console.error(
`The fauna secret is missing! 🤷🥚\n\nPlease define a secret to get started. 💁🐣\n ↳ read more on https://github.com/zvictor/brainyduck/wiki/Fauna-secret\n`
)
throw new Error(`missing fauna's secret`)
}
return secret
}
let _faunaClient
export const faunaClient = (options) => {
const { FAUNA_DOMAIN, FAUNA_SCHEME, FAUNA_PORT } = process.env
if (!options && _faunaClient && !_faunaClient._http._adapter._closed) {
return _faunaClient
}
options = options || {}
if (!options.secret) {
options.secret = loadSecret()
}
if (!options.domain && FAUNA_DOMAIN) {
options.domain = process.env.FAUNA_DOMAIN
}
if (!options.scheme && FAUNA_SCHEME) {
options.scheme = process.env.FAUNA_SCHEME
}
if (!options.port && FAUNA_PORT) {
options.port = process.env.FAUNA_PORT
}
_faunaClient = new Client(options)
return _faunaClient
}
export const patternMatch = async (pattern, cwd = process.cwd()) =>
(await globby(pattern, { cwd, ignore: ignored })).map((x) =>
x.startsWith('/') ? x : path.join(cwd, x)
)
export const runFQL = (query, secret) => {
debug('brainyduck:runFQL')(`Executing query:\n${query}`)
const { FAUNA_DOMAIN, FAUNA_PORT, FAUNA_SCHEME } = process.env
const tmpFile = temporaryFile()
fs.writeFileSync(tmpFile, query, 'utf8')
const args = [`eval`, `--secret=${secret || loadSecret()}`, `--file=${tmpFile}`]
if (FAUNA_DOMAIN) {
args.push('--domain')
args.push(FAUNA_DOMAIN)
}
if (FAUNA_PORT) {
args.push('--port')
args.push(FAUNA_PORT)
}
if (FAUNA_SCHEME) {
args.push('--scheme')
args.push(FAUNA_SCHEME)
}
const { stdout, stderr, exitCode } = execaSync(findBin(`fauna`), args, {
cwd: path.dirname(fileURLToPath(import.meta.url)),
})
if (exitCode) {
debug('brainyduck:runFQL')(`The query has failed to execute.`)
console.error(stderr)
throw new Error(`runFQL failed with exit code ${exitCode}`)
}
debug('brainyduck:runFQL')(`The query has been executed`)
return JSON.parse(stdout)
}
export const importSchema = async (schema, { secret, override, puke } = {}) => {
const url = puke ? graphqlEndpoint.puke : graphqlEndpoint.import
debug('brainyduck:importSchema')(
`Pushing the schema to ${url} in ${override ? 'OVERRIDE' : 'NORMAL'} mode`
)
const t0 = performance.now()
const response = await fetch(`${url}${override ? '?mode=override' : ''}`, {
method: 'POST',
body: schema,
headers: puke
? {}
: new Headers({
Authorization: `Bearer ${secret || loadSecret()}`,
}),
})
debug('brainyduck:importSchema')(
`The call to remote took ${performance.now() - t0} milliseconds.`
)
const message = await response.text()
if (response.status !== 200) {
if (!message.endsWith(errors.CACHE_TIMEOUT)) {
throw new Error(message)
}
console.log(`Wiped data still found in fauna's cache.\nCooling down for 30s...`)
await sleep(30000)
console.log(`Retrying now...`)
return await importSchema(schema, { override, puke })
}
debug('brainyduck:importSchema')(`The returned schema is:`, message)
return message
}
const _representData = (data) => {
if (typeof data.map === 'function') {
return data.map(_representData)
}
const deeper = data && (data.name || data.ref || data['@ref'])
if (deeper) {
return _representData(deeper)
}
return data
}
export const representData = (data) =>
inspect(_representData(data), {
depth: 5,
colors: process.stdout.hasColors ? process.stdout.hasColors() : false,
})
export const sleep = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout))
export const pipeData = new Promise((resolve, reject) => {
const stdin = process.openStdin()
let data = ''
stdin.on('data', function (chunk) {
data += chunk
})
stdin.on('error', function (e) {
reject(e)
})
stdin.on('end', function () {
resolve(data)
})
})