appium 2.0.0-beta.3 → 2.0.0-beta.30

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 (139) hide show
  1. package/README.md +10 -11
  2. package/build/lib/appium.d.ts +215 -0
  3. package/build/lib/appium.d.ts.map +1 -0
  4. package/build/lib/appium.js +238 -132
  5. package/build/lib/cli/args.d.ts +20 -0
  6. package/build/lib/cli/args.d.ts.map +1 -0
  7. package/build/lib/cli/args.js +96 -282
  8. package/build/lib/cli/driver-command.d.ts +36 -0
  9. package/build/lib/cli/driver-command.d.ts.map +1 -0
  10. package/build/lib/cli/driver-command.js +19 -12
  11. package/build/lib/cli/extension-command.d.ts +345 -0
  12. package/build/lib/cli/extension-command.d.ts.map +1 -0
  13. package/build/lib/cli/extension-command.js +171 -96
  14. package/build/lib/cli/extension.d.ts +14 -0
  15. package/build/lib/cli/extension.d.ts.map +1 -0
  16. package/build/lib/cli/extension.js +31 -16
  17. package/build/lib/cli/parser.d.ts +79 -0
  18. package/build/lib/cli/parser.d.ts.map +1 -0
  19. package/build/lib/cli/parser.js +152 -95
  20. package/build/lib/cli/plugin-command.d.ts +39 -0
  21. package/build/lib/cli/plugin-command.d.ts.map +1 -0
  22. package/build/lib/cli/plugin-command.js +18 -13
  23. package/build/lib/cli/utils.d.ts +29 -0
  24. package/build/lib/cli/utils.d.ts.map +1 -0
  25. package/build/lib/cli/utils.js +27 -3
  26. package/build/lib/config-file.d.ts +100 -0
  27. package/build/lib/config-file.d.ts.map +1 -0
  28. package/build/lib/config-file.js +136 -0
  29. package/build/lib/config.d.ts +40 -0
  30. package/build/lib/config.d.ts.map +1 -0
  31. package/build/lib/config.js +92 -67
  32. package/build/lib/constants.d.ts +48 -0
  33. package/build/lib/constants.d.ts.map +1 -0
  34. package/build/lib/constants.js +60 -0
  35. package/build/lib/extension/driver-config.d.ts +84 -0
  36. package/build/lib/extension/driver-config.d.ts.map +1 -0
  37. package/build/lib/extension/driver-config.js +190 -0
  38. package/build/lib/extension/extension-config.d.ts +170 -0
  39. package/build/lib/extension/extension-config.d.ts.map +1 -0
  40. package/build/lib/extension/extension-config.js +297 -0
  41. package/build/lib/extension/index.d.ts +39 -0
  42. package/build/lib/extension/index.d.ts.map +1 -0
  43. package/build/lib/extension/index.js +77 -0
  44. package/build/lib/extension/manifest.d.ts +174 -0
  45. package/build/lib/extension/manifest.d.ts.map +1 -0
  46. package/build/lib/extension/manifest.js +246 -0
  47. package/build/lib/extension/package-changed.d.ts +11 -0
  48. package/build/lib/extension/package-changed.d.ts.map +1 -0
  49. package/build/lib/extension/package-changed.js +68 -0
  50. package/build/lib/extension/plugin-config.d.ts +62 -0
  51. package/build/lib/extension/plugin-config.d.ts.map +1 -0
  52. package/build/lib/extension/plugin-config.js +87 -0
  53. package/build/lib/grid-register.d.ts +10 -0
  54. package/build/lib/grid-register.d.ts.map +1 -0
  55. package/build/lib/grid-register.js +21 -25
  56. package/build/lib/logger.d.ts +3 -0
  57. package/build/lib/logger.d.ts.map +1 -0
  58. package/build/lib/logger.js +4 -6
  59. package/build/lib/logsink.d.ts +4 -0
  60. package/build/lib/logsink.d.ts.map +1 -0
  61. package/build/lib/logsink.js +12 -16
  62. package/build/lib/main.d.ts +51 -0
  63. package/build/lib/main.d.ts.map +1 -0
  64. package/build/lib/main.js +174 -82
  65. package/build/lib/schema/arg-spec.d.ts +143 -0
  66. package/build/lib/schema/arg-spec.d.ts.map +1 -0
  67. package/build/lib/schema/arg-spec.js +119 -0
  68. package/build/lib/schema/cli-args.d.ts +19 -0
  69. package/build/lib/schema/cli-args.d.ts.map +1 -0
  70. package/build/lib/schema/cli-args.js +180 -0
  71. package/build/lib/schema/cli-transformers.d.ts +5 -0
  72. package/build/lib/schema/cli-transformers.d.ts.map +1 -0
  73. package/build/lib/schema/cli-transformers.js +74 -0
  74. package/build/lib/schema/index.d.ts +3 -0
  75. package/build/lib/schema/index.d.ts.map +1 -0
  76. package/build/lib/schema/index.js +34 -0
  77. package/build/lib/schema/keywords.d.ts +24 -0
  78. package/build/lib/schema/keywords.d.ts.map +1 -0
  79. package/build/lib/schema/keywords.js +70 -0
  80. package/build/lib/schema/schema.d.ts +259 -0
  81. package/build/lib/schema/schema.d.ts.map +1 -0
  82. package/build/lib/schema/schema.js +452 -0
  83. package/build/lib/utils.d.ts +66 -0
  84. package/build/lib/utils.d.ts.map +1 -0
  85. package/build/lib/utils.js +35 -139
  86. package/build/tsconfig.tsbuildinfo +1 -0
  87. package/index.js +11 -0
  88. package/lib/appium-config.schema.json +278 -0
  89. package/lib/appium.js +398 -155
  90. package/lib/cli/args.js +174 -377
  91. package/lib/cli/driver-command.js +22 -7
  92. package/lib/cli/extension-command.js +372 -177
  93. package/lib/cli/extension.js +32 -10
  94. package/lib/cli/parser.js +252 -83
  95. package/lib/cli/plugin-command.js +19 -6
  96. package/lib/cli/utils.js +22 -2
  97. package/lib/config-file.js +223 -0
  98. package/lib/config.js +169 -69
  99. package/lib/constants.js +78 -0
  100. package/lib/extension/driver-config.js +249 -0
  101. package/lib/extension/extension-config.js +458 -0
  102. package/lib/extension/index.js +102 -0
  103. package/lib/extension/manifest.js +486 -0
  104. package/lib/extension/package-changed.js +63 -0
  105. package/lib/extension/plugin-config.js +113 -0
  106. package/lib/grid-register.js +25 -22
  107. package/lib/logger.js +1 -1
  108. package/lib/logsink.js +14 -7
  109. package/lib/main.js +233 -83
  110. package/lib/schema/arg-spec.js +232 -0
  111. package/lib/schema/cli-args.js +261 -0
  112. package/lib/schema/cli-transformers.js +122 -0
  113. package/lib/schema/index.js +2 -0
  114. package/lib/schema/keywords.js +134 -0
  115. package/lib/schema/schema.js +734 -0
  116. package/lib/utils.js +85 -129
  117. package/package.json +62 -85
  118. package/scripts/postinstall.js +71 -0
  119. package/types/appium-manifest.d.ts +61 -0
  120. package/types/cli.d.ts +134 -0
  121. package/types/extension.d.ts +56 -0
  122. package/types/external-manifest.d.ts +58 -0
  123. package/types/index.d.ts +7 -0
  124. package/CHANGELOG.md +0 -3515
  125. package/bin/ios-webkit-debug-proxy-launcher.js +0 -71
  126. package/build/lib/cli/npm.js +0 -206
  127. package/build/lib/cli/parser-helpers.js +0 -82
  128. package/build/lib/driver-config.js +0 -77
  129. package/build/lib/drivers.js +0 -96
  130. package/build/lib/extension-config.js +0 -251
  131. package/build/lib/plugin-config.js +0 -59
  132. package/build/lib/plugins.js +0 -14
  133. package/lib/cli/npm.js +0 -183
  134. package/lib/cli/parser-helpers.js +0 -79
  135. package/lib/driver-config.js +0 -46
  136. package/lib/drivers.js +0 -81
  137. package/lib/extension-config.js +0 -208
  138. package/lib/plugin-config.js +0 -34
  139. package/lib/plugins.js +0 -10
@@ -0,0 +1,232 @@
1
+ import _ from 'lodash';
2
+
3
+ /**
4
+ * The original ID of the Appium config schema.
5
+ * We use this in the CLI to convert it to `argparse` options.
6
+ */
7
+ export const APPIUM_CONFIG_SCHEMA_ID = 'appium.json';
8
+
9
+ /**
10
+ * The schema prop containing server-related options. Everything in here
11
+ * is "native" to Appium.
12
+ * Used by {@link flattenSchema} for transforming the schema into CLI args.
13
+ */
14
+ export const SERVER_PROP_NAME = 'server';
15
+
16
+ /**
17
+ * Used to parse extension info from a schema ID.
18
+ */
19
+ const SCHEMA_ID_REGEXP = /^(?<extType>.+?)-(?<normalizedExtName>.+)\.json$/;
20
+
21
+ /**
22
+ * Avoid typos by using constants!
23
+ */
24
+ const PROPERTIES = 'properties';
25
+
26
+ /**
27
+ * An `ArgSpec` is a class representing metadata about an argument (or config
28
+ * option) used for cross-referencing.
29
+ *
30
+ * This class has no instance methods, and is basically just a read-only "struct".
31
+ * @template D
32
+ */
33
+ export class ArgSpec {
34
+ /**
35
+ * The canonical name of the argument. Corresponds to key in schema's `properties` prop.
36
+ * @type {string}
37
+ */
38
+ name;
39
+
40
+ /**
41
+ * The `ExtensionType` of the argument. This will be set if the arg came from an extension;
42
+ * otherwise it will be `undefined`.
43
+ * @type {ExtensionType|undefined}
44
+ */
45
+ extType;
46
+
47
+ /**
48
+ * The name of the extension, if this argument came from an extension.
49
+ *
50
+ * Otherwise `undefined`.
51
+ * @type {string|undefined}
52
+ */
53
+ extName;
54
+
55
+ /**
56
+ * The schema ID (`$id`) for the argument. This is automatically determined, and any user-provided `$id`s will be overwritten.
57
+ *
58
+ * @type {string}
59
+ */
60
+ ref;
61
+
62
+ /**
63
+ * The CLI argument, sans leading dashes.
64
+ * @type {string}
65
+ */
66
+ arg;
67
+
68
+ /**
69
+ * The desired keypath for the argument after arguments have been parsed.
70
+ *
71
+ * Typically this is camelCased. If the arg came from an extension, it will be prefixed with
72
+ * `<extType>.<extName>.`
73
+ * @type {string}
74
+ */
75
+ dest;
76
+
77
+ /**
78
+ * The same as {@link ArgSpec.dest} but without the leading `<extType>.<extName>.` prefix.
79
+ */
80
+ rawDest;
81
+
82
+ /**
83
+ * Whatever the default value of this argument is, as specified by the
84
+ * `default` property of the schema.
85
+ * @type {D|undefined}
86
+ */
87
+ defaultValue;
88
+
89
+ /**
90
+ * Builds some computed fields and assigns them to the instance.
91
+ *
92
+ * Undefined properties are not assigned.
93
+ *
94
+ * The _constructor_ is private. Use {@link ArgSpec.create} instead.
95
+ * @private
96
+ * @param {string} name
97
+ * @param {ArgSpecOptions<D>} [opts]
98
+ */
99
+ constructor (name, {extType, extName, dest, defaultValue} = {}) {
100
+ // we must normalize the extension name to fit into our convention for CLI
101
+ // args.
102
+ const arg = ArgSpec.toArg(name, extType, extName);
103
+
104
+ const ref = ArgSpec.toSchemaRef(name, extType, extName);
105
+
106
+ // if no explicit `dest` provided, just camelCase the name to avoid needing
107
+ // to use bracket syntax when accessing props on the parsed args object.
108
+ const rawDest = _.camelCase(dest ?? name);
109
+
110
+ const destKeypath =
111
+ extType && extName ? [extType, extName, rawDest].join('.') : rawDest;
112
+
113
+ this.defaultValue = defaultValue;
114
+ this.name = name;
115
+ this.extType = extType;
116
+ this.extName = extName;
117
+ this.arg = arg;
118
+ this.dest = destKeypath;
119
+ this.ref = ref;
120
+ this.rawDest = rawDest;
121
+ }
122
+
123
+ /**
124
+ * Return the schema ID (`$id`) for the **argument** given the parameters.
125
+ *
126
+ * If you need the "root" or "base" schema ID, use {@link ArgSpec.toSchemaBaseRef} instead.
127
+ * @param {string} name - Argument name
128
+ * @param {ExtensionType} [extType] - Extension type
129
+ * @param {string} [extName] - Extension name
130
+ * @returns {string} Schema ID
131
+ */
132
+ static toSchemaRef (name, extType, extName) {
133
+ const baseRef = ArgSpec.toSchemaBaseRef(extType, extName);
134
+ if (extType && extName) {
135
+ return [`${baseRef}#`, PROPERTIES, name].join('/');
136
+ }
137
+ return [`${baseRef}#`, PROPERTIES, SERVER_PROP_NAME, PROPERTIES, name].join('/');
138
+ }
139
+
140
+ /**
141
+ * Return the schema ID for an extension or the base schema ID.
142
+ * @param {ExtensionType} [extType] - Extension type
143
+ * @param {string} [extName] - Extension name
144
+ */
145
+ static toSchemaBaseRef (extType, extName) {
146
+ if (extType && extName) {
147
+ return `${extType}-${ArgSpec.toNormalizedExtName(extName)}.json`;
148
+ }
149
+ return APPIUM_CONFIG_SCHEMA_ID;
150
+ }
151
+
152
+ /**
153
+ * Return the unique ID for the argument given the parameters.
154
+ * @param {string} name - Argument name
155
+ * @param {ExtensionType} [extType] - Extension type
156
+ * @param {string} [extName] - Extension name
157
+ * @returns {string} Unique ID
158
+ */
159
+ static toArg (name, extType, extName) {
160
+ const properName = _.kebabCase(name.replace(/^--?/, ''));
161
+ if (extType && extName) {
162
+ return [extType, _.kebabCase(extName), properName].join('-');
163
+ }
164
+ return properName;
165
+ }
166
+
167
+ /**
168
+ * Normalizes a raw extension name (not including the type).
169
+ * @param {string} extName - Extension name
170
+ * @returns {string} Normalized extension name
171
+ */
172
+ static toNormalizedExtName (extName) {
173
+ return _.kebabCase(extName);
174
+ }
175
+
176
+ /**
177
+ * When given the root ID of a schema for an extension (`<extType>-<normalizedExtName>.json`) Returns an object containing the extension type and the _normalized_ extension name.
178
+ * @param {string} schemaId - Root schema ID
179
+ * @returns { {extType?: ExtensionType, normalizedExtName?: string} }
180
+ */
181
+ static extensionInfoFromRootSchemaId (schemaId) {
182
+ const matches = schemaId.match(SCHEMA_ID_REGEXP);
183
+ if (matches?.groups) {
184
+ const {extType, normalizedExtName} =
185
+ /** @type { {extType: ExtensionType, normalizedExtName: string} } */ (
186
+ matches.groups
187
+ );
188
+ return {extType, normalizedExtName};
189
+ }
190
+ return {};
191
+ }
192
+
193
+ /**
194
+ * Creates an `ArgSpec`
195
+ *
196
+ * @param {string} name - The canonical name of the argument. Corresponds to a key in a schema's
197
+ * `properties` property.
198
+ * @template D
199
+ * @param {ArgSpecOptions<D>} [opts] - Options
200
+ * @returns {Readonly<ArgSpec>}
201
+ */
202
+ static create (name, opts) {
203
+ return Object.freeze(new ArgSpec(name, opts));
204
+ }
205
+
206
+ /**
207
+ * String representation, useful for debugging
208
+ * @returns {string}
209
+ */
210
+ /* istanbul ignore next */
211
+ toString () {
212
+ let str = `[ArgSpec] ${this.name} (${this.ref})`;
213
+ if (this.extType && this.extName) {
214
+ str += ` (ext: ${this.extType}/${this.extName})`;
215
+ }
216
+ return str;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Options for {@link ArgSpec.create}
222
+ * @template D
223
+ * @typedef ArgSpecOptions
224
+ * @property {string} [extName]
225
+ * @property {ExtensionType} [extType]
226
+ * @property {string} [dest]
227
+ * @property {D} [defaultValue]
228
+ */
229
+
230
+ /**
231
+ * @typedef {import('../extension/manifest').ExtensionType} ExtensionType
232
+ */
@@ -0,0 +1,261 @@
1
+
2
+ import {ArgumentTypeError} from 'argparse';
3
+ import _ from 'lodash';
4
+ import {formatErrors as formatErrors} from '../config-file';
5
+ import {flattenSchema, validate} from './schema';
6
+ import {transformers} from './cli-transformers';
7
+
8
+ /**
9
+ * This module concerns functions which convert schema definitions to
10
+ * `argparse`-compatible data structures, for deriving CLI arguments from a
11
+ * schema.
12
+ */
13
+
14
+ /**
15
+ * Lookup of possible values for the `type` field in a JSON schema.
16
+ * @type {Readonly<Record<string, import('json-schema').JSONSchema7TypeName>>}
17
+ */
18
+ const TYPENAMES = Object.freeze({
19
+ ARRAY: 'array',
20
+ OBJECT: 'object',
21
+ BOOLEAN: 'boolean',
22
+ INTEGER: 'integer',
23
+ NUMBER: 'number',
24
+ NULL: 'null',
25
+ STRING: 'string',
26
+ });
27
+
28
+ /**
29
+ * Options with alias lengths less than this will be considered "short" flags.
30
+ */
31
+ const SHORT_ARG_CUTOFF = 3;
32
+
33
+ /**
34
+ * Convert an alias (`foo`) to a flag (`--foo`) or a short flag (`-f`).
35
+ * @param {ArgSpec} argSpec - the argument specification
36
+ * @param {string} [alias] - the alias to convert to a flag
37
+ * @returns {string} the flag
38
+ */
39
+ function aliasToFlag (argSpec, alias) {
40
+ const {extType, extName, name} = argSpec;
41
+ const arg = alias ?? name;
42
+ const isShort = arg.length < SHORT_ARG_CUTOFF;
43
+ if (extType && extName) {
44
+ return isShort
45
+ ? `--${extType}-${_.kebabCase(extName)}-${arg}`
46
+ : `--${extType}-${_.kebabCase(extName)}-${_.kebabCase(arg)}`;
47
+ }
48
+ return isShort ? `-${arg}` : `--${_.kebabCase(arg)}`;
49
+ }
50
+
51
+ /**
52
+ * Converts a string to SCREAMING_SNAKE_CASE
53
+ */
54
+ const screamingSnakeCase = _.flow(_.snakeCase, _.toUpper);
55
+
56
+ /**
57
+ * Given unique property name `name`, return a function which validates a value
58
+ * against a property within the schema.
59
+ * @template Coerced
60
+ * @param {ArgSpec} argSpec - Argument name
61
+ * @param {(value: string) => Coerced} [coerce] - Function to coerce to a different
62
+ * primitive
63
+ * @todo See if we can remove `coerce` by allowing Ajv to coerce in its
64
+ * constructor options
65
+ * @returns
66
+ */
67
+ function getSchemaValidator ({ref: schemaId}, coerce = _.identity) {
68
+ /** @param {string} value */
69
+ return (value) => {
70
+ const coerced = coerce(value);
71
+ const errors = validate(coerced, schemaId);
72
+ if (_.isEmpty(errors)) {
73
+ return coerced;
74
+ }
75
+ throw new ArgumentTypeError(
76
+ '\n\n' + formatErrors(errors, value, {schemaId}),
77
+ );
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Determine the description for display on the CLI, given the schema.
83
+ * @param {AppiumJSONSchema} schema
84
+ * @returns {string}
85
+ */
86
+ function makeDescription (schema) {
87
+ const {appiumCliDescription, description = '', appiumDeprecated} = schema;
88
+ let desc = appiumCliDescription ?? description;
89
+ if (appiumDeprecated) {
90
+ desc = `[DEPRECATED] ${desc}`;
91
+ }
92
+ return desc;
93
+ }
94
+
95
+ /**
96
+ * Given arg `name`, a JSON schema `subSchema`, and options, return an argument definition
97
+ * as understood by `argparse`.
98
+ * @param {AppiumJSONSchema} subSchema - JSON schema for the option
99
+ * @param {ArgSpec} argSpec - Argument spec tuple
100
+ * @returns {[string[], import('argparse').ArgumentOptions]} Tuple of flag and options
101
+ */
102
+ function subSchemaToArgDef (subSchema, argSpec) {
103
+ let {
104
+ type,
105
+ appiumCliAliases,
106
+ appiumCliTransformer,
107
+ enum: enumValues,
108
+ } = subSchema;
109
+
110
+ const {name, arg} = argSpec;
111
+
112
+ const aliases = [
113
+ aliasToFlag(argSpec),
114
+ .../** @type {string[]} */ (appiumCliAliases ?? []).map((alias) =>
115
+ aliasToFlag(argSpec, alias),
116
+ ),
117
+ ];
118
+
119
+ /** @type {import('argparse').ArgumentOptions} */
120
+ let argOpts = {
121
+ required: false,
122
+ help: makeDescription(subSchema)
123
+ };
124
+
125
+ /**
126
+ * Generally we will provide a `type` to `argparse` as a function which
127
+ * validates using ajv (which is much more full-featured than what `argparse`
128
+ * can offer). The exception is `boolean`-type options, which have no
129
+ * `argType`.
130
+ *
131
+ * Not sure if this type is correct, but it's not doing what I want. I want
132
+ * to say "this is a function which returns something of type `T` where `T` is
133
+ * never a `Promise`". This function must be sync.
134
+ * @type {((value: string) => unknown)|undefined}
135
+ */
136
+ let argTypeFunction;
137
+
138
+ // handle special cases for various types
139
+ switch (type) {
140
+ // booleans do not have a type per `ArgumentOptions`, just an "action"
141
+ // NOTE: due to limitations of `argparse`, we cannot provide fancy help text, and must rely on its internal error messaging.
142
+ case TYPENAMES.BOOLEAN: {
143
+ argOpts.action = 'store_const';
144
+ argOpts.const = true;
145
+ break;
146
+ }
147
+
148
+ case TYPENAMES.OBJECT: {
149
+ argTypeFunction = transformers.json;
150
+ break;
151
+ }
152
+
153
+ // arrays are treated as CSVs, because `argparse` doesn't handle array data.
154
+ case TYPENAMES.ARRAY: {
155
+ argTypeFunction = transformers.csv;
156
+ break;
157
+ }
158
+
159
+ // "number" type is coerced to float. `argparse` does this for us if we use `float` type, but
160
+ // we don't.
161
+ case TYPENAMES.NUMBER: {
162
+ argTypeFunction = getSchemaValidator(argSpec, parseFloat);
163
+ break;
164
+ }
165
+
166
+ // "integer" is coerced to an .. integer. again, `argparse` would do this for us if we used `int`.
167
+ case TYPENAMES.INTEGER: {
168
+ argTypeFunction = getSchemaValidator(argSpec, _.parseInt);
169
+ break;
170
+ }
171
+
172
+ // strings (like number and integer) are subject to further validation
173
+ // (e.g., must satisfy a mask or regex or even some custom validation
174
+ // function)
175
+ case TYPENAMES.STRING: {
176
+ argTypeFunction = getSchemaValidator(argSpec);
177
+ break;
178
+ }
179
+
180
+ // TODO: there may be some way to restrict this at the Ajv level --
181
+ // that may involve patching the metaschema.
182
+ case TYPENAMES.NULL:
183
+ // falls through
184
+ default: {
185
+ throw new TypeError(
186
+ `Schema property "${arg}": \`${type}\` type unknown or disallowed`,
187
+ );
188
+ }
189
+ }
190
+
191
+ // metavar is used in help text. `boolean` cannot have a metavar--it is not
192
+ // displayed--and `argparse` throws if you give it one.
193
+ if (type !== TYPENAMES.BOOLEAN) {
194
+ argOpts.metavar = screamingSnakeCase(name);
195
+ }
196
+
197
+ // the validity of "appiumCliTransformer" should already have been determined
198
+ // by ajv during schema validation in `finalizeSchema()`. the `array` &
199
+ // `object` types have already added a formatter (see above, so we don't do it
200
+ // twice).
201
+ if (
202
+ type !== TYPENAMES.ARRAY &&
203
+ type !== TYPENAMES.OBJECT &&
204
+ appiumCliTransformer
205
+ ) {
206
+ argTypeFunction = _.flow(
207
+ argTypeFunction ?? _.identity,
208
+ transformers[appiumCliTransformer],
209
+ );
210
+ }
211
+
212
+ if (argTypeFunction) {
213
+ argOpts.type = argTypeFunction;
214
+ }
215
+
216
+ // convert JSON schema `enum` to `choices`. `enum` can contain any JSON type, but `argparse`
217
+ // is limited to a single type per arg (I think). so let's make everything a string.
218
+ // and might as well _require_ the `type: string` while we're at it.
219
+ if (enumValues && !_.isEmpty(enumValues)) {
220
+ if (type === TYPENAMES.STRING) {
221
+ argOpts.choices = enumValues.map(String);
222
+ } else {
223
+ throw new TypeError(
224
+ `Problem with schema for ${arg}; \`enum\` is only supported for \`type: 'string'\``,
225
+ );
226
+ }
227
+ }
228
+
229
+ return [aliases, argOpts];
230
+ }
231
+
232
+ /**
233
+ * Converts the finalized, flattened schema representation into
234
+ * ArgumentDefinitions for handoff to `argparse`.
235
+ *
236
+ * @throws If schema has not been added to ajv (via `finalizeSchema()`)
237
+ * @returns {import('../cli/args').ArgumentDefinitions} A map of arryas of
238
+ * aliases to `argparse` arguments; empty if no schema found
239
+ */
240
+ export function toParserArgs () {
241
+ const flattened = flattenSchema().filter(({schema}) => !schema.appiumCliIgnored);
242
+ return new Map(
243
+ _.map(flattened, ({schema, argSpec}) =>
244
+ subSchemaToArgDef(schema, argSpec),
245
+ ),
246
+ );
247
+ }
248
+
249
+ /**
250
+ * @template T
251
+ * @typedef {import('ajv/dist/types').FormatValidator<T>} FormatValidator<T>
252
+ */
253
+
254
+ /**
255
+ * A JSON 7 schema with our custom keywords.
256
+ * @typedef {import('./keywords').AppiumJSONSchemaKeywords & import('json-schema').JSONSchema7} AppiumJSONSchema
257
+ */
258
+
259
+ /**
260
+ * @typedef {import('./arg-spec').ArgSpec} ArgSpec
261
+ */
@@ -0,0 +1,122 @@
1
+
2
+ import { ArgumentTypeError } from 'argparse';
3
+ import { readFileSync } from 'fs';
4
+ import _ from 'lodash';
5
+
6
+ /**
7
+ * This module provides custom keywords for Appium schemas, as well as
8
+ * "transformers" (see `argTransformers` below).
9
+ *
10
+ * Custom keywords are just properties that will appear in a schema (e.g.,
11
+ * `appium-config-schema.js`) beyond what the JSON Schema spec offers. These
12
+ * are usable by extensions, as well.
13
+ */
14
+
15
+ /**
16
+ * Splits a CSV string into an array
17
+ * @param {string} value
18
+ * @returns {string[]}
19
+ */
20
+ function parseCsvLine (value) {
21
+ return value
22
+ .split(',')
23
+ .map((v) => v.trim())
24
+ .filter(Boolean);
25
+ }
26
+
27
+ /**
28
+ * Split a file by newline then calls {@link parseCsvLine} on each line.
29
+ * @param {string} value
30
+ * @returns {string[]}
31
+ */
32
+ function parseCsvFile (value) {
33
+ return value
34
+ .split(/\r?\n/)
35
+ .map((v) => v.trim())
36
+ .filter(Boolean)
37
+ .flatMap(parseCsvLine);
38
+ }
39
+
40
+ /**
41
+ * Namespace containing _transformers_ for CLI arguments. "Validators" and
42
+ * "formatters" do not actually modify the value, but these do.
43
+ *
44
+ * Use case is for when the config file can accept e.g., a `string[]`, but the
45
+ * CLI can only take a `string` (as `argparse` seems to be limited in that
46
+ * fashion; it also cannot understand an argument having multiple types).
47
+ *
48
+ * For example, the `csv` transform takes a `string` and returns a `string[]` by
49
+ * splitting it by comma--_or_ if that `string` happens to be a
50
+ * filepath--reading the file as a `.csv`.
51
+ *
52
+ * This contains some copy-pasted code from `lib/cli/parser-helpers.js`, which was
53
+ * obliterated.
54
+ */
55
+ export const transformers = {
56
+ /**
57
+ * Given a CSV-style string or pathname, parse it into an array.
58
+ * The file can also be split on newlines.
59
+ * @param {string} value
60
+ * @returns {string[]}
61
+ */
62
+ csv: (value) => {
63
+ let body;
64
+ // since this value could be a single string (no commas) _or_ a pathname, we will need
65
+ // to attempt to parse it as a file _first_.
66
+ try {
67
+ body = readFileSync(value, 'utf8');
68
+ } catch (err) {
69
+ if (err.code !== 'ENOENT') {
70
+ throw new ArgumentTypeError(
71
+ `Could not read file ${body}: ${err.message}`,
72
+ );
73
+ }
74
+ }
75
+
76
+ try {
77
+ return body ? parseCsvFile(body) : parseCsvLine(value);
78
+ } catch (err) {
79
+ throw new ArgumentTypeError(
80
+ 'Must be a comma-delimited string, e.g., "foo,bar,baz"',
81
+ );
82
+ }
83
+ },
84
+
85
+ /**
86
+ * Parse a string which could be a path to a JSON file or a JSON string.
87
+ * @param {string} jsonOrPath
88
+ * @returns {object}
89
+ */
90
+ json: (jsonOrPath) => {
91
+ let json = jsonOrPath;
92
+ let loadedFromFile = false;
93
+ try {
94
+ // use synchronous file access, as `argparse` provides no way of either
95
+ // awaiting or using callbacks. This step happens in startup, in what is
96
+ // effectively command-line code, so nothing is blocked in terms of
97
+ // sessions, so holding up the event loop does not incur the usual
98
+ // drawbacks.
99
+ json = readFileSync(jsonOrPath, 'utf8');
100
+ loadedFromFile = true;
101
+ } catch (err) {
102
+ // unreadable files don't count... but other problems do.
103
+ if (err.code !== 'ENOENT') {
104
+ throw err;
105
+ }
106
+ }
107
+ try {
108
+ const result = JSON.parse(json);
109
+ if (!_.isPlainObject(result)) {
110
+ throw new Error(
111
+ `'${_.truncate(result, {length: 100})}' is not an object`,
112
+ );
113
+ }
114
+ return result;
115
+ } catch (e) {
116
+ const msg = loadedFromFile
117
+ ? `The provided value of '${jsonOrPath}' must be a valid JSON`
118
+ : `The provided value must be a valid JSON`;
119
+ throw new TypeError(`${msg}. Original error: ${e.message}`);
120
+ }
121
+ },
122
+ };
@@ -0,0 +1,2 @@
1
+ export * from './schema';
2
+ export * from './cli-args';