adapt-cli 3.0.0 → 3.0.7

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.
Files changed (79) hide show
  1. package/.bowerrc +2 -2
  2. package/.eslintignore +1 -1
  3. package/.eslintrc.json +14 -14
  4. package/.github/CONTRIBUTING.md +8 -0
  5. package/.github/ISSUE_TEMPLATE.md +17 -0
  6. package/.github/pull_request_template.md +25 -0
  7. package/.github/workflows/addtomainproject.yml +19 -0
  8. package/.github/workflows/releases.yml +25 -0
  9. package/.travis.yml +46 -46
  10. package/README.md +266 -266
  11. package/bin/adapt.js +3 -3
  12. package/json/help-create/component.json +9 -9
  13. package/json/help-create/course.json +9 -9
  14. package/json/help-create/question.json +9 -9
  15. package/json/help-create.json +12 -12
  16. package/json/help-devinstall.json +9 -9
  17. package/json/help-install.json +10 -10
  18. package/json/help-ls.json +7 -7
  19. package/json/help-register.json +7 -7
  20. package/json/help-rename.json +7 -7
  21. package/json/help-search.json +8 -8
  22. package/json/help-uninstall.json +7 -7
  23. package/json/help-unregister.json +8 -8
  24. package/json/help-update.json +12 -12
  25. package/json/help-version.json +7 -7
  26. package/json/help.json +19 -19
  27. package/lib/api.js +273 -260
  28. package/lib/cli.js +70 -69
  29. package/lib/commands/authenticate.js +18 -18
  30. package/lib/commands/create/component.js +64 -64
  31. package/lib/commands/create/course.js +26 -26
  32. package/lib/commands/create/question.js +18 -18
  33. package/lib/commands/create.js +94 -85
  34. package/lib/commands/devinstall.js +35 -35
  35. package/lib/commands/help.js +31 -31
  36. package/lib/commands/install.js +16 -16
  37. package/lib/commands/ls.js +35 -9
  38. package/lib/commands/register.js +11 -11
  39. package/lib/commands/rename.js +14 -14
  40. package/lib/commands/search.js +11 -11
  41. package/lib/commands/uninstall.js +9 -9
  42. package/lib/commands/unregister.js +12 -12
  43. package/lib/commands/update.js +12 -12
  44. package/lib/commands/version.js +13 -13
  45. package/lib/econnreset.js +8 -0
  46. package/lib/integration/AdaptFramework/build.js +42 -39
  47. package/lib/integration/AdaptFramework/clone.js +27 -27
  48. package/lib/integration/AdaptFramework/deleteSrcCore.js +9 -9
  49. package/lib/integration/AdaptFramework/deleteSrcCourse.js +9 -9
  50. package/lib/integration/AdaptFramework/download.js +21 -21
  51. package/lib/integration/AdaptFramework/erase.js +34 -34
  52. package/lib/integration/AdaptFramework/getLatestVersion.js +74 -79
  53. package/lib/integration/AdaptFramework/npmInstall.js +21 -21
  54. package/lib/integration/AdaptFramework.js +19 -19
  55. package/lib/integration/Plugin.js +404 -403
  56. package/lib/integration/PluginManagement/autenticate.js +47 -56
  57. package/lib/integration/PluginManagement/install.js +224 -222
  58. package/lib/integration/PluginManagement/print.js +52 -52
  59. package/lib/integration/PluginManagement/register.js +130 -130
  60. package/lib/integration/PluginManagement/rename.js +95 -101
  61. package/lib/integration/PluginManagement/schemas.js +8 -8
  62. package/lib/integration/PluginManagement/search.js +37 -46
  63. package/lib/integration/PluginManagement/uninstall.js +141 -141
  64. package/lib/integration/PluginManagement/unregister.js +91 -101
  65. package/lib/integration/PluginManagement/update.js +224 -224
  66. package/lib/integration/PluginManagement.js +21 -21
  67. package/lib/integration/Project.js +146 -146
  68. package/lib/integration/Target.js +299 -296
  69. package/lib/integration/getBowerRegistryConfig.js +34 -34
  70. package/lib/logger.js +28 -28
  71. package/lib/util/JSONReadValidate.js +34 -34
  72. package/lib/util/constants.js +38 -38
  73. package/lib/util/createPromptTask.js +7 -7
  74. package/lib/util/download.js +45 -45
  75. package/lib/util/errors.js +58 -58
  76. package/lib/util/extract.js +24 -24
  77. package/lib/util/getDirNameFromImportMeta.js +6 -6
  78. package/lib/util/promises.js +36 -36
  79. package/package.json +74 -40
@@ -1,46 +1,37 @@
1
- import getBowerRegistryConfig from '../getBowerRegistryConfig.js'
2
- import chalk from 'chalk'
3
- import request from 'request'
4
- import path from 'path'
5
-
6
- export default async function search ({
7
- logger,
8
- searchTerm,
9
- cwd = process.cwd()
10
- } = {}) {
11
- cwd = path.resolve(process.cwd(), cwd)
12
- const BOWER_REGISTRY_CONFIG = getBowerRegistryConfig({ cwd })
13
- try {
14
- const uniqueResults = {}
15
- for (const serverURI of BOWER_REGISTRY_CONFIG.search) {
16
- try {
17
- const immediateResults = await new Promise((resolve, reject) => {
18
- request({
19
- uri: `${serverURI}packages/search/${searchTerm}`,
20
- method: 'GET',
21
- headers: { 'User-Agent': 'adapt-cli' },
22
- followRedirect: false
23
- }, (err, res, body) => {
24
- if (err) return reject(err)
25
- if (res.statusCode !== 200) reject(new Error(`The server responded with ${res.statusCode}`))
26
- try {
27
- resolve(JSON.parse(body))
28
- } catch (err) {
29
- reject(err)
30
- }
31
- })
32
- })
33
- immediateResults?.forEach(result => (uniqueResults[result.name] = uniqueResults[result.name] ?? result))
34
- } catch (err) {}
35
- }
36
- const results = Object.values(uniqueResults)
37
- if (!results.length) {
38
- logger?.warn(`no plugins found containing: ${searchTerm}`)
39
- }
40
- results.forEach(function (result) {
41
- logger?.log(chalk.cyan(result.name) + ' ' + result.url)
42
- })
43
- } catch (err) {
44
- logger?.error("Oh dear, something went wrong. I'm terribly sorry.", err)
45
- }
46
- }
1
+ import getBowerRegistryConfig from '../getBowerRegistryConfig.js'
2
+ import chalk from 'chalk'
3
+ import fetch from 'node-fetch'
4
+ import path from 'path'
5
+
6
+ export default async function search ({
7
+ logger,
8
+ searchTerm,
9
+ cwd = process.cwd()
10
+ } = {}) {
11
+ cwd = path.resolve(process.cwd(), cwd)
12
+ const BOWER_REGISTRY_CONFIG = getBowerRegistryConfig({ cwd })
13
+ try {
14
+ const uniqueResults = {}
15
+ for (const serverURI of BOWER_REGISTRY_CONFIG.search) {
16
+ try {
17
+ const response = await fetch(`${serverURI}packages/search/${searchTerm}`, {
18
+ method: 'GET',
19
+ headers: { 'User-Agent': 'adapt-cli' },
20
+ followRedirect: false
21
+ })
22
+ if (response.status !== 200) throw new Error(`The server responded with ${response.status}`)
23
+ const immediateResults = await response.json()
24
+ immediateResults?.forEach(result => (uniqueResults[result.name] = uniqueResults[result.name] ?? result))
25
+ } catch (err) {}
26
+ }
27
+ const results = Object.values(uniqueResults)
28
+ if (!results.length) {
29
+ logger?.warn(`no plugins found containing: ${searchTerm}`)
30
+ }
31
+ results.forEach(function (result) {
32
+ logger?.log(chalk.cyan(result.name) + ' ' + result.url)
33
+ })
34
+ } catch (err) {
35
+ logger?.error("Oh dear, something went wrong. I'm terribly sorry.", err)
36
+ }
37
+ }
@@ -1,141 +1,141 @@
1
-
2
- import chalk from 'chalk'
3
- import Project from '../Project.js'
4
- import Target from '../Target.js'
5
- import { eachOfLimitProgress } from '../../util/promises.js'
6
- import { createPromptTask } from '../../util/createPromptTask.js'
7
- import { errorPrinter, packageNamePrinter } from './print.js'
8
- import { intersection } from 'lodash-es'
9
- import path from 'path'
10
-
11
- export default async function uninstall ({
12
- plugins,
13
- isInteractive = true,
14
- cwd = process.cwd(),
15
- logger = null
16
- }) {
17
- cwd = path.resolve(process.cwd(), cwd)
18
- const project = new Project({ cwd, logger })
19
- project.tryThrowInvalidPath()
20
-
21
- logger?.log(chalk.cyan('uninstalling adapt dependencies...'))
22
-
23
- const targets = await getUninstallTargets({ logger, project, plugins, isInteractive })
24
- if (!targets?.length) return targets
25
-
26
- await loadPluginData({ logger, targets })
27
- await eachOfLimitProgress(
28
- targets.filter(target => target.isToBeUninstalled),
29
- target => target.uninstall(),
30
- percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Uninstalling plugins ${percentage}% complete`)
31
- )
32
- logger?.log(`${chalk.bold.cyan('<info>')} Uninstalling plugins 100% complete`)
33
- const installedDependencies = await project.getInstalledDependencies()
34
- await updateManifest({ project, targets, installedDependencies, isInteractive })
35
- await summariseUninstallation({ logger, targets })
36
- return targets
37
- }
38
-
39
- /**
40
- * @param {Object} options
41
- * @param {Project} options.project
42
- * @param {[Target]} options.targets
43
- */
44
- async function getUninstallTargets ({ logger, project, plugins, isInteractive }) {
45
- if (typeof plugins === 'string') plugins = [plugins]
46
- /** whether adapt.json is being used to compile the list of targets to install */
47
- const isEmpty = !plugins?.length
48
- if (isEmpty && isInteractive) {
49
- const shouldContinue = await createPromptTask({
50
- message: chalk.reset('This command will attempt to uninstall all installed plugins. Do you wish to continue?'),
51
- type: 'confirm'
52
- })
53
- if (!shouldContinue) return
54
- }
55
-
56
- /** a list of plugin name/version pairs */
57
- const itinerary = isEmpty
58
- ? await project.getInstalledDependencies()
59
- : plugins.reduce((itinerary, arg) => {
60
- const [name, version = '*'] = arg.split(/[#@]/)
61
- // Duplicates are removed by assigning to object properties
62
- itinerary[name] = version
63
- return itinerary
64
- }, {})
65
- const pluginNames = Object.entries(itinerary).map(([name, version]) => `${name}@${version}`)
66
-
67
- /** @type {[Target]} */
68
- const targets = pluginNames
69
- ? pluginNames.map(nameVersion => {
70
- const [name] = nameVersion.split(/[#@]/)
71
- return new Target({ name, project, logger })
72
- })
73
- : await project.getUninstallTargets()
74
- return targets
75
- }
76
-
77
- /**
78
- * @param {Object} options
79
- * @param {Project} options.project
80
- * @param {[Target]} options.targets
81
- */
82
- async function loadPluginData ({ logger, targets }) {
83
- await eachOfLimitProgress(
84
- targets,
85
- target => target.fetchProjectInfo(),
86
- percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Getting plugin info ${percentage}% complete`)
87
- )
88
- logger?.log(`${chalk.bold.cyan('<info>')} Getting plugin info 100% complete`)
89
- await eachOfLimitProgress(
90
- targets,
91
- target => target.markUninstallable(),
92
- percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Marking uninstallable ${percentage}% complete`)
93
- )
94
- logger?.log(`${chalk.bold.cyan('<info>')} Marking uninstallable 100% complete`)
95
- }
96
-
97
- /**
98
- * @param {Object} options
99
- * @param {Project} options.project
100
- * @param {[Target]} options.targets
101
- * @returns
102
- */
103
- async function updateManifest ({ project, targets, installedDependencies, isInteractive }) {
104
- if (targets.filter(target => target.isToBeUninstalled).length === 0) return
105
- if (intersection(Object.keys(installedDependencies), targets.map(target => target.packageName)).length) return
106
- if (isInteractive) {
107
- const shouldUpdate = await createPromptTask({
108
- message: chalk.white('Update the manifest (adapt.json)?'),
109
- type: 'confirm',
110
- default: true
111
- })
112
- if (!shouldUpdate) return
113
- }
114
- targets.forEach(target => target.isToBeUninstalled && project.remove(target))
115
- }
116
-
117
- /**
118
- * @param {Object} options
119
- * @param {[Target]} options.targets
120
- */
121
- function summariseUninstallation ({ logger, targets }) {
122
- const uninstallSucceeded = targets.filter(target => target.isUninstallSuccessful)
123
- const uninstallSkipped = targets.filter(target => !target.isToBeUninstalled || target.isSkipped)
124
- const uninstallErrored = targets.filter(target => target.isUninstallFailure)
125
- const missing = targets.filter(target => target.isMissing)
126
- const noneUninstalled = (uninstallSucceeded.length === 0)
127
- const allUninstalledSuccessfully = (uninstallErrored.length === 0 && missing.length === 0)
128
- const someUninstalledSuccessfully = (!noneUninstalled && !allUninstalledSuccessfully)
129
- summarise(logger, uninstallSkipped, packageNamePrinter, 'The following plugins were skipped:')
130
- summarise(logger, missing, packageNamePrinter, 'There was a problem locating the following plugins:')
131
- summarise(logger, uninstallErrored, errorPrinter, 'The following plugins could not be uninstalled:')
132
- if (noneUninstalled) logger?.log(chalk.cyanBright('None of the requested plugins could be uninstalled'))
133
- else if (allUninstalledSuccessfully) summarise(logger, uninstallSucceeded, packageNamePrinter, 'All requested plugins were successfully uninstalled. Summary of uninstallation:')
134
- else if (someUninstalledSuccessfully) summarise(logger, uninstallSucceeded, packageNamePrinter, 'The following plugins were successfully uninstalled:')
135
- }
136
-
137
- function summarise (logger, list, iterator, header) {
138
- if (!list || !iterator || list.length === 0) return
139
- logger?.log(chalk.cyanBright(header))
140
- list.forEach(item => iterator(item, logger))
141
- }
1
+
2
+ import chalk from 'chalk'
3
+ import Project from '../Project.js'
4
+ import Target from '../Target.js'
5
+ import { eachOfLimitProgress } from '../../util/promises.js'
6
+ import { createPromptTask } from '../../util/createPromptTask.js'
7
+ import { errorPrinter, packageNamePrinter } from './print.js'
8
+ import { intersection } from 'lodash-es'
9
+ import path from 'path'
10
+
11
+ export default async function uninstall ({
12
+ plugins,
13
+ isInteractive = true,
14
+ cwd = process.cwd(),
15
+ logger = null
16
+ }) {
17
+ cwd = path.resolve(process.cwd(), cwd)
18
+ const project = new Project({ cwd, logger })
19
+ project.tryThrowInvalidPath()
20
+
21
+ logger?.log(chalk.cyan('uninstalling adapt dependencies...'))
22
+
23
+ const targets = await getUninstallTargets({ logger, project, plugins, isInteractive })
24
+ if (!targets?.length) return targets
25
+
26
+ await loadPluginData({ logger, targets })
27
+ await eachOfLimitProgress(
28
+ targets.filter(target => target.isToBeUninstalled),
29
+ target => target.uninstall(),
30
+ percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Uninstalling plugins ${percentage}% complete`)
31
+ )
32
+ logger?.log(`${chalk.bold.cyan('<info>')} Uninstalling plugins 100% complete`)
33
+ const installedDependencies = await project.getInstalledDependencies()
34
+ await updateManifest({ project, targets, installedDependencies, isInteractive })
35
+ await summariseUninstallation({ logger, targets })
36
+ return targets
37
+ }
38
+
39
+ /**
40
+ * @param {Object} options
41
+ * @param {Project} options.project
42
+ * @param {[Target]} options.targets
43
+ */
44
+ async function getUninstallTargets ({ logger, project, plugins, isInteractive }) {
45
+ if (typeof plugins === 'string') plugins = [plugins]
46
+ /** whether adapt.json is being used to compile the list of targets to install */
47
+ const isEmpty = !plugins?.length
48
+ if (isEmpty && isInteractive) {
49
+ const shouldContinue = await createPromptTask({
50
+ message: chalk.reset('This command will attempt to uninstall all installed plugins. Do you wish to continue?'),
51
+ type: 'confirm'
52
+ })
53
+ if (!shouldContinue) return
54
+ }
55
+
56
+ /** a list of plugin name/version pairs */
57
+ const itinerary = isEmpty
58
+ ? await project.getInstalledDependencies()
59
+ : plugins.reduce((itinerary, arg) => {
60
+ const [name, version = '*'] = arg.split(/[#@]/)
61
+ // Duplicates are removed by assigning to object properties
62
+ itinerary[name] = version
63
+ return itinerary
64
+ }, {})
65
+ const pluginNames = Object.entries(itinerary).map(([name, version]) => `${name}@${version}`)
66
+
67
+ /** @type {[Target]} */
68
+ const targets = pluginNames
69
+ ? pluginNames.map(nameVersion => {
70
+ const [name] = nameVersion.split(/[#@]/)
71
+ return new Target({ name, project, logger })
72
+ })
73
+ : await project.getUninstallTargets()
74
+ return targets
75
+ }
76
+
77
+ /**
78
+ * @param {Object} options
79
+ * @param {Project} options.project
80
+ * @param {[Target]} options.targets
81
+ */
82
+ async function loadPluginData ({ logger, targets }) {
83
+ await eachOfLimitProgress(
84
+ targets,
85
+ target => target.fetchProjectInfo(),
86
+ percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Getting plugin info ${percentage}% complete`)
87
+ )
88
+ logger?.log(`${chalk.bold.cyan('<info>')} Getting plugin info 100% complete`)
89
+ await eachOfLimitProgress(
90
+ targets,
91
+ target => target.markUninstallable(),
92
+ percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Marking uninstallable ${percentage}% complete`)
93
+ )
94
+ logger?.log(`${chalk.bold.cyan('<info>')} Marking uninstallable 100% complete`)
95
+ }
96
+
97
+ /**
98
+ * @param {Object} options
99
+ * @param {Project} options.project
100
+ * @param {[Target]} options.targets
101
+ * @returns
102
+ */
103
+ async function updateManifest ({ project, targets, installedDependencies, isInteractive }) {
104
+ if (targets.filter(target => target.isToBeUninstalled).length === 0) return
105
+ if (intersection(Object.keys(installedDependencies), targets.map(target => target.packageName)).length) return
106
+ if (isInteractive) {
107
+ const shouldUpdate = await createPromptTask({
108
+ message: chalk.white('Update the manifest (adapt.json)?'),
109
+ type: 'confirm',
110
+ default: true
111
+ })
112
+ if (!shouldUpdate) return
113
+ }
114
+ targets.forEach(target => target.isToBeUninstalled && project.remove(target))
115
+ }
116
+
117
+ /**
118
+ * @param {Object} options
119
+ * @param {[Target]} options.targets
120
+ */
121
+ function summariseUninstallation ({ logger, targets }) {
122
+ const uninstallSucceeded = targets.filter(target => target.isUninstallSuccessful)
123
+ const uninstallSkipped = targets.filter(target => !target.isToBeUninstalled || target.isSkipped)
124
+ const uninstallErrored = targets.filter(target => target.isUninstallFailure)
125
+ const missing = targets.filter(target => target.isMissing)
126
+ const noneUninstalled = (uninstallSucceeded.length === 0)
127
+ const allUninstalledSuccessfully = (uninstallErrored.length === 0 && missing.length === 0)
128
+ const someUninstalledSuccessfully = (!noneUninstalled && !allUninstalledSuccessfully)
129
+ summarise(logger, uninstallSkipped, packageNamePrinter, 'The following plugins were skipped:')
130
+ summarise(logger, missing, packageNamePrinter, 'There was a problem locating the following plugins:')
131
+ summarise(logger, uninstallErrored, errorPrinter, 'The following plugins could not be uninstalled:')
132
+ if (noneUninstalled) logger?.log(chalk.cyanBright('None of the requested plugins could be uninstalled'))
133
+ else if (allUninstalledSuccessfully) summarise(logger, uninstallSucceeded, packageNamePrinter, 'All requested plugins were successfully uninstalled. Summary of uninstallation:')
134
+ else if (someUninstalledSuccessfully) summarise(logger, uninstallSucceeded, packageNamePrinter, 'The following plugins were successfully uninstalled:')
135
+ }
136
+
137
+ function summarise (logger, list, iterator, header) {
138
+ if (!list || !iterator || list.length === 0) return
139
+ logger?.log(chalk.cyanBright(header))
140
+ list.forEach(item => iterator(item, logger))
141
+ }
@@ -1,101 +1,91 @@
1
- import getBowerRegistryConfig from '../getBowerRegistryConfig.js'
2
- import authenticate from './autenticate.js'
3
- import fs from 'fs-extra'
4
- import path from 'path'
5
- import chalk from 'chalk'
6
- import inquirer from 'inquirer'
7
- import { readValidateJSON } from '../../util/JSONReadValidate.js'
8
- import Plugin from '../Plugin.js'
9
- import request from 'request'
10
-
11
- export default async function unregister ({
12
- logger,
13
- cwd = process.cwd(),
14
- pluginName
15
- } = {}) {
16
- cwd = path.resolve(process.cwd(), cwd)
17
- const BOWER_REGISTRY_CONFIG = getBowerRegistryConfig({ cwd })
18
- logger?.warn('Using registry at', BOWER_REGISTRY_CONFIG.register)
19
- try {
20
- const bowerJSONPath = path.join(cwd, 'bower.json')
21
- const hasBowerJSON = fs.existsSync(bowerJSONPath)
22
- const bowerJSON = hasBowerJSON ? await readValidateJSON(bowerJSONPath) : {}
23
- if (pluginName) bowerJSON.name = pluginName
24
- const props = await confirm(bowerJSON)
25
- pluginName = props.pluginName
26
- const repository = props.repository
27
- const { username, token, type } = await authenticate({ repository, pluginName })
28
- logger?.log(`${username} authenticated as ${type}`)
29
- await finalConfirm()
30
- await unregisterInBowerRepo({ pluginName, username, token, BOWER_REGISTRY_CONFIG })
31
- logger?.log(chalk.green('The plugin was successfully unregistered.'))
32
- } catch (err) {
33
- logger?.error(err)
34
- logger?.log('The plugin was not unregistered.')
35
- }
36
- }
37
-
38
- async function confirm (properties) {
39
- const plugin = new Plugin({ name: properties.name })
40
- const schema = [
41
- {
42
- name: 'pluginName',
43
- message: chalk.cyan('name'),
44
- validate: v => {
45
- return /^adapt-[\w|-]+?$/.test(v) ||
46
- 'Name must prefixed with \'adapt\' and each word separated with a hyphen(-)'
47
- },
48
- type: 'input',
49
- default: plugin.toString() || 'not specified'
50
- },
51
- {
52
- name: 'repository',
53
- message: chalk.cyan('repository URL'),
54
- validate: v => {
55
- return /https:\/\/([\w.@:/\-~]+)(\.git)(\/)?/.test(v) ||
56
- 'Please provide a repository URL of the form https://<domain><path>.git'
57
- },
58
- type: 'input',
59
- default: properties.repository ? properties.repository.url : undefined
60
- }
61
- ]
62
- return await inquirer.prompt(schema)
63
- }
64
-
65
- async function finalConfirm () {
66
- const schema = [
67
- {
68
- name: 'ready',
69
- message: chalk.cyan('Confirm Unregister now?'),
70
- type: 'confirm',
71
- default: true
72
- }
73
- ]
74
- const confirmation = await inquirer.prompt(schema)
75
- if (!confirmation.ready) throw new Error('Aborted. Nothing has been unregistered.')
76
- }
77
-
78
- async function unregisterInBowerRepo ({
79
- pluginName,
80
- username,
81
- token,
82
- BOWER_REGISTRY_CONFIG
83
- }) {
84
- const uri = `${BOWER_REGISTRY_CONFIG.register}packages/${username}/${pluginName}?access_token=${token}`
85
- return new Promise((resolve, reject) => {
86
- request({
87
- uri,
88
- method: 'DELETE',
89
- headers: { 'User-Agent': 'adapt-cli' },
90
- followRedirect: false
91
- }, (err, res, body) => {
92
- if (err) return reject(err)
93
- if (res.statusCode !== 204) reject(new Error(`The server responded with ${res.statusCode}`))
94
- try {
95
- resolve()
96
- } catch (err) {
97
- reject(err)
98
- }
99
- })
100
- })
101
- }
1
+ import getBowerRegistryConfig from '../getBowerRegistryConfig.js'
2
+ import authenticate from './autenticate.js'
3
+ import fs from 'fs-extra'
4
+ import path from 'path'
5
+ import chalk from 'chalk'
6
+ import inquirer from 'inquirer'
7
+ import { readValidateJSON } from '../../util/JSONReadValidate.js'
8
+ import Plugin from '../Plugin.js'
9
+ import fetch from 'node-fetch'
10
+
11
+ export default async function unregister ({
12
+ logger,
13
+ cwd = process.cwd(),
14
+ pluginName
15
+ } = {}) {
16
+ cwd = path.resolve(process.cwd(), cwd)
17
+ const BOWER_REGISTRY_CONFIG = getBowerRegistryConfig({ cwd })
18
+ logger?.warn('Using registry at', BOWER_REGISTRY_CONFIG.register)
19
+ try {
20
+ const bowerJSONPath = path.join(cwd, 'bower.json')
21
+ const hasBowerJSON = fs.existsSync(bowerJSONPath)
22
+ const bowerJSON = hasBowerJSON ? await readValidateJSON(bowerJSONPath) : {}
23
+ if (pluginName) bowerJSON.name = pluginName
24
+ const props = await confirm(bowerJSON)
25
+ pluginName = props.pluginName
26
+ const repository = props.repository
27
+ const { username, token, type } = await authenticate({ repository, pluginName })
28
+ logger?.log(`${username} authenticated as ${type}`)
29
+ await finalConfirm()
30
+ await unregisterInBowerRepo({ pluginName, username, token, BOWER_REGISTRY_CONFIG })
31
+ logger?.log(chalk.green('The plugin was successfully unregistered.'))
32
+ } catch (err) {
33
+ logger?.error(err)
34
+ logger?.log('The plugin was not unregistered.')
35
+ }
36
+ }
37
+
38
+ async function confirm (properties) {
39
+ const plugin = new Plugin({ name: properties.name })
40
+ const schema = [
41
+ {
42
+ name: 'pluginName',
43
+ message: chalk.cyan('name'),
44
+ validate: v => {
45
+ return /^adapt-[\w|-]+?$/.test(v) ||
46
+ 'Name must prefixed with \'adapt\' and each word separated with a hyphen(-)'
47
+ },
48
+ type: 'input',
49
+ default: plugin.toString() || 'not specified'
50
+ },
51
+ {
52
+ name: 'repository',
53
+ message: chalk.cyan('repository URL'),
54
+ validate: v => {
55
+ return /https:\/\/([\w.@:/\-~]+)(\.git)(\/)?/.test(v) ||
56
+ 'Please provide a repository URL of the form https://<domain><path>.git'
57
+ },
58
+ type: 'input',
59
+ default: properties.repository ? properties.repository.url : undefined
60
+ }
61
+ ]
62
+ return await inquirer.prompt(schema)
63
+ }
64
+
65
+ async function finalConfirm () {
66
+ const schema = [
67
+ {
68
+ name: 'ready',
69
+ message: chalk.cyan('Confirm Unregister now?'),
70
+ type: 'confirm',
71
+ default: true
72
+ }
73
+ ]
74
+ const confirmation = await inquirer.prompt(schema)
75
+ if (!confirmation.ready) throw new Error('Aborted. Nothing has been unregistered.')
76
+ }
77
+
78
+ async function unregisterInBowerRepo ({
79
+ pluginName,
80
+ username,
81
+ token,
82
+ BOWER_REGISTRY_CONFIG
83
+ }) {
84
+ const uri = `${BOWER_REGISTRY_CONFIG.register}packages/${username}/${pluginName}?access_token=${token}`
85
+ const response = await fetch(uri, {
86
+ method: 'DELETE',
87
+ headers: { 'User-Agent': 'adapt-cli' },
88
+ followRedirect: false
89
+ })
90
+ if (response.status !== 204) throw new Error(`The server responded with ${response.status}`)
91
+ }