-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
385 lines (326 loc) · 9.5 KB
/
index.js
File metadata and controls
385 lines (326 loc) · 9.5 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/env node
/**
* @license
* Copyright(c) 2021-2024 Selectfromuser Inc.
* All rights reserved.
* https://www.selectfromuser.com
* {team, support, jhlee}@selectfromuser.com, eces92@gmail.com
* Commercial Licensed. Grant use for paid permitted user only.
*/
console.log('[openselect] selectfromuser.com')
const inquirer = require('inquirer');
const chalk = require('chalk')
const axios = require('axios')
const path = require('path')
const fs = require('fs')
const os = require('os')
const {glob} = require('glob')
const YAML = require('js-yaml')
/**
* endpoint, configuration
*/
API_BASE_URL = process.env.TEST ? 'http://localhost:9500' : 'https://api.selectfromuser.com'
WEB_BASE_URL = process.env.TEST ? 'http://localhost:5173' : 'https://app.selectfromuser.com'
/**
* global var
*/
global.API_BASE_URL = API_BASE_URL
const Package = require('./package.json')
let CONFIG = {}
async function validate(token) {
const tokens = String(token).split('.')
// if (tokens.length != 2) {
// throw new Error(`인증 실패: 알수없는 토큰 형식 (로그아웃 후 다시 시도해주세요. "slt logout")`)
// }
const r = await axios.get(`${API_BASE_URL}/api/team/${tokens[0]}/config/openselect/whoami`, {
headers: {
Authorization: token,
}
})
if (r?.data?.message != 'ok') {
throw new Error(`인증 실패: ${r?.data?.message}`)
}
console.log(chalk.blue('[INFO]'), '로그인된 상태입니다.')
}
async function link(options) {
const check_config_path = path.join(process.env.CWD || process.cwd(), '.select', 'project.json')
if (fs.existsSync(check_config_path)) {
const check_config = require(check_config_path)
CONFIG = check_config
console.log(chalk.blue('[INFO]'), 'Using editorId at .select/project.json')
await validate(CONFIG.editorId)
return
}
console.log(chalk.blue('[INFO]'), '편집할 어드민을 입력해주세요. [가이드주소]')
if (options.token) {
TOKEN = options.token
} else {
const answer = await inquirer.prompt([
{
name: 'token',
message: 'Project Editor ID',
default: 'Enter your editor ID',
}
])
TOKEN = answer.token
}
// validate
await validate(TOKEN)
const config_path = path.join(process.env.CWD || process.cwd(), '.select')
if (!fs.existsSync(config_path)) {
fs.mkdirSync(config_path)
}
CONFIG = {
editorId: TOKEN,
}
fs.writeFileSync(path.join(config_path, 'project.json'),
JSON.stringify(CONFIG, null, ' ')
)
// console.log('')
// console.log(chalk.blue('[INFO]'), 'Sign in completed.')
const gitignore = path.join(process.env.CWD || process.cwd(), '.gitignore')
if (fs.existsSync(gitignore)) {
const data = fs.readFileSync(gitignore)
if (data.toString().split('\n').map(e => String(e).trim()).filter(e => e == '.select').length == 0) {
fs.appendFileSync(gitignore, '\n.select')
}
}
}
async function init() {
const files = await glob('**/*.{yml,yaml}', {
ignore: 'node_modules/**',
})
if (files && files.length) {
console.log(chalk.blue('[INFO]'), 'Files are located already in current directory.')
const answer = await inquirer.prompt([
{
name: 'overwrite',
message: 'Overwrite',
default: 'Enter Y to overwrite anyway',
}
])
if (answer.overwrite.toUpperCase() != 'Y') {
return console.log('User cancel')
}
}
const samples = require('./sample.js')
{
const p = path.join(process.env.CWD || process.cwd(), 'index.yml')
fs.writeFileSync(p, samples['index.yml'].trim())
console.log(chalk.blue('[INFO]'), 'File added: index.yml')
}
{
const p = path.join(process.env.CWD || process.cwd(), 'dashboard.yml')
fs.writeFileSync(p, samples['dashboard.yml'].trim())
console.log(chalk.blue('[INFO]'), 'File added: dashboard.yml')
}
{
const p = path.join(process.env.CWD || process.cwd(), 'users')
if (!fs.existsSync(p)) {
fs.mkdirSync(p)
}
}
{
const p = path.join(process.env.CWD || process.cwd(), 'users', 'index.yml')
fs.writeFileSync(p, samples['users/index.yml'].trim())
console.log(chalk.blue('[INFO]'), 'File added: users/index.yml')
}
{
const p = path.join(process.env.CWD || process.cwd(), 'users', 'payment.yml')
fs.writeFileSync(p, samples['users/payment.yml'].trim())
console.log(chalk.blue('[INFO]'), 'File added: users/payment.yml')
}
}
const build_v2_spec = (item) => {
let json = {
menus: [],
pages: [],
}
const docs = YAML.loadAll(item.json.yml) || []
const $$path = path.parse(item.name)
const $path = $$path.dir + '/' + $$path.name
for (const doc of docs) {
if ($$path.name == 'index') {
json = {
...json,
...doc,
}
} else {
json.pages.push({
path: $path,
...doc,
})
}
}
if ($$path.name != 'index' && !docs?.[0]?.path) {
json.menus.push({
path: $path,
default: true,
orderBy: $$path.name,
})
}
item.json.yml = YAML.dump(json)
}
async function draft(event, path) {
// TODO: json, js
const files = await glob('**/*.{yml,yaml}', {
ignore: 'node_modules/**',
})
const items = []
for (const file of files) {
if (file.startsWith('_')) {
continue
}
if (file.endsWith('.yml') || file.endsWith('.yaml')) {
const item = {
name: file,
json: {
yml: fs.readFileSync(file, 'utf8'),
}
}
if (file.startsWith('pages/')) {
build_v2_spec(item)
}
items.push(item)
}
// else if (file.endsWith('.json2')) {
// items.push({
// name: file,
// json: {
// json: fs.readFileSync(file, 'utf8'),
// }
// })
// }
}
// console.log(items)
try {
const tokens = CONFIG.editorId.split('.')
const r = await axios.post(`${API_BASE_URL}/api/team/${tokens[0]}/config/openselect/drafts`, {
items,
}, {
headers: {
Authorization: CONFIG.editorId,
}
})
console.log(chalk.green('[INFO]'), `저장했습니다.`)
} catch (error) {
console.log(error)
}
}
async function dev() {
try {
const files = await glob('**/*.{yml,yaml}', {
ignore: 'node_modules/**',
})
if (files && files.length === 0) {
const answer = await inquirer.prompt([
{
name: 'init',
message: '설정 파일이 비어있습니다. 샘플을 추가할까요? (y)',
default: 'no',
}
])
if (answer.init == 'y') {
await init()
}
}
const watch = () => {
const chokidar = require('chokidar')
chokidar.watch(path.join(process.env.CWD || process.cwd(), '**/*.(yml|yaml)'), {
ignored: 'node_modules/**',
ignoreInitial: true,
})
.on('all', (event, path) => {
console.log(chalk.blue('[INFO]'), `Reload from ${path} ${event}.`)
draft(event, path)
})
}
watch()
// at first, upload all
draft()
const tokens = CONFIG.editorId.split('.')
console.log('✨ Preview URL:\n ', chalk.underline(`${WEB_BASE_URL}/admin/${tokens[0]}#deployment-preview`))
} catch (error) {
console.error(chalk.red('[ERROR]'), error.message)
console.debug(error.stack)
}
}
/**
* check update
*/
setTimeout(async () => {
try {
const boxen = (await import('boxen')).default
const chalk = require('chalk')
const pj = (await import('package-json')).default
const latest = await pj('@selectfromuser/cli')
const semver = require('semver')
if (semver.lt(Package.version, latest.version)) {
console.log(boxen(`새로운 업데이트 가능 ${Package.version} -> ${ chalk.bold(latest.version)}\nRun ${ chalk.cyan('npm i -g @selectfromuser/cli') } to update`, {
padding: 1,
margin: 1,
borderColor: 'green',
title: 'NEW',
titleAlignment: 'center',
}))
}
} catch (error) {
console.error(error)
}
}, 0)
/**
* program
*/
if (process.argv.length == 2) {
process.argv.push('dev')
}
const { program } = require('commander');
program
.name('openselect')
.version(Package.version, '-v, --version, -version')
// .option('-w, --watch, -watch', 'watch config yaml files')
// .option('-f, --force, -force', 'force create config yaml')
program.command('logout').action(() => {
let config_path = path.join(process.env.CWD || process.cwd(), '.select')
if (!fs.existsSync(config_path)) {
fs.mkdirSync(config_path)
}
let config = {}
if (fs.existsSync(path.join(config_path, 'project.json'))) {
config = require(path.join(config_path, 'project.json'))
}
if (!config.editorId) {
return console.log(chalk.blue('[INFO]'), '이미 로그아웃 되어 있습니다.')
}
fs.unlinkSync(path.join(config_path, 'project.json'))
// config.editorId = undefined
// fs.writeFileSync(path.join(config_path, 'project.json'),
// JSON.stringify(config, null, ' ')
// )
console.log(chalk.blue('[INFO]'), '로그아웃 했습니다.')
})
program.command('login')
.option('-t, --token <TOKEN>', 'EditorId')
.action((options) => {
try {
link(options)
} catch (error) {
console.log(chalk.yellow('[ERROR]'), error.message)
}
})
// todo
// program.command('whoami').action(async () => {})
program.command('dev').action(async () => {
try {
await link()
dev()
} catch (error) {
console.log(chalk.yellow('[ERROR]'), error.message)
}
})
program.command('init').action(() => {
init()
})
const parsed = program.parse()
const commands = parsed.args
const opts = program.opts()