appium 2.0.0-beta.4 → 2.0.0-beta.40

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 (151) hide show
  1. package/README.md +10 -11
  2. package/build/lib/appium.d.ts +204 -0
  3. package/build/lib/appium.d.ts.map +1 -0
  4. package/build/lib/appium.js +257 -131
  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 +25 -18
  11. package/build/lib/cli/extension-command.d.ts +372 -0
  12. package/build/lib/cli/extension-command.d.ts.map +1 -0
  13. package/build/lib/cli/extension-command.js +286 -156
  14. package/build/lib/cli/extension.d.ts +18 -0
  15. package/build/lib/cli/extension.d.ts.map +1 -0
  16. package/build/lib/cli/extension.js +30 -17
  17. package/build/lib/cli/parser.d.ts +80 -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 +33 -0
  21. package/build/lib/cli/plugin-command.d.ts.map +1 -0
  22. package/build/lib/cli/plugin-command.js +24 -19
  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 +41 -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 +81 -0
  36. package/build/lib/extension/driver-config.d.ts.map +1 -0
  37. package/build/lib/extension/driver-config.js +177 -0
  38. package/build/lib/extension/extension-config.d.ts +242 -0
  39. package/build/lib/extension/extension-config.d.ts.map +1 -0
  40. package/build/lib/extension/extension-config.js +436 -0
  41. package/build/lib/extension/index.d.ts +48 -0
  42. package/build/lib/extension/index.d.ts.map +1 -0
  43. package/build/lib/extension/index.js +74 -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 +256 -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 +57 -0
  51. package/build/lib/extension/plugin-config.d.ts.map +1 -0
  52. package/build/lib/extension/plugin-config.js +78 -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 +14 -17
  62. package/build/lib/main.d.ts +55 -0
  63. package/build/lib/main.d.ts.map +1 -0
  64. package/build/lib/main.js +189 -90
  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/build/types/appium-manifest.d.ts +59 -0
  88. package/build/types/appium-manifest.d.ts.map +1 -0
  89. package/build/types/cli.d.ts +112 -0
  90. package/build/types/cli.d.ts.map +1 -0
  91. package/build/types/extension-manifest.d.ts +55 -0
  92. package/build/types/extension-manifest.d.ts.map +1 -0
  93. package/build/types/index.d.ts +16 -0
  94. package/build/types/index.d.ts.map +1 -0
  95. package/driver.d.ts +1 -0
  96. package/driver.js +14 -0
  97. package/index.js +11 -0
  98. package/lib/appium.js +517 -186
  99. package/lib/cli/args.js +269 -422
  100. package/lib/cli/driver-command.js +58 -23
  101. package/lib/cli/extension-command.js +612 -260
  102. package/lib/cli/extension.js +34 -16
  103. package/lib/cli/parser.js +241 -83
  104. package/lib/cli/plugin-command.js +48 -20
  105. package/lib/cli/utils.js +24 -10
  106. package/lib/config-file.js +219 -0
  107. package/lib/config.js +210 -91
  108. package/lib/constants.js +69 -0
  109. package/lib/extension/driver-config.js +249 -0
  110. package/lib/extension/extension-config.js +679 -0
  111. package/lib/extension/index.js +116 -0
  112. package/lib/extension/manifest.js +475 -0
  113. package/lib/extension/package-changed.js +64 -0
  114. package/lib/extension/plugin-config.js +113 -0
  115. package/lib/grid-register.js +49 -35
  116. package/lib/logger.js +1 -2
  117. package/lib/logsink.js +38 -33
  118. package/lib/main.js +303 -100
  119. package/lib/schema/arg-spec.js +229 -0
  120. package/lib/schema/cli-args.js +238 -0
  121. package/lib/schema/cli-transformers.js +115 -0
  122. package/lib/schema/index.js +2 -0
  123. package/lib/schema/keywords.js +136 -0
  124. package/lib/schema/schema.js +717 -0
  125. package/lib/utils.js +121 -140
  126. package/package.json +75 -85
  127. package/plugin.d.ts +1 -0
  128. package/plugin.js +13 -0
  129. package/scripts/autoinstall-extensions.js +177 -0
  130. package/support.d.ts +1 -0
  131. package/support.js +13 -0
  132. package/types/appium-manifest.ts +73 -0
  133. package/types/cli.ts +146 -0
  134. package/types/extension-manifest.ts +64 -0
  135. package/types/index.ts +21 -0
  136. package/CHANGELOG.md +0 -3515
  137. package/bin/ios-webkit-debug-proxy-launcher.js +0 -71
  138. package/build/lib/cli/npm.js +0 -206
  139. package/build/lib/cli/parser-helpers.js +0 -82
  140. package/build/lib/driver-config.js +0 -77
  141. package/build/lib/drivers.js +0 -96
  142. package/build/lib/extension-config.js +0 -253
  143. package/build/lib/plugin-config.js +0 -59
  144. package/build/lib/plugins.js +0 -14
  145. package/lib/cli/npm.js +0 -183
  146. package/lib/cli/parser-helpers.js +0 -79
  147. package/lib/driver-config.js +0 -46
  148. package/lib/drivers.js +0 -81
  149. package/lib/extension-config.js +0 -209
  150. package/lib/plugin-config.js +0 -34
  151. package/lib/plugins.js +0 -10
@@ -0,0 +1,717 @@
1
+ import Ajv from 'ajv';
2
+ import addFormats from 'ajv-formats';
3
+ import _ from 'lodash';
4
+ import path from 'path';
5
+ import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
6
+ import {AppiumConfigJsonSchema} from '@appium/schema';
7
+ import {APPIUM_CONFIG_SCHEMA_ID, ArgSpec, SERVER_PROP_NAME} from './arg-spec';
8
+ import {keywords} from './keywords';
9
+
10
+ /**
11
+ * Key/value pairs go in... but they don't come out.
12
+ *
13
+ * @template K,V
14
+ * @extends {Map<K,V>}
15
+ */
16
+ export class RoachHotelMap extends Map {
17
+ /**
18
+ * @param {K} key
19
+ * @param {V} value
20
+ */
21
+ set(key, value) {
22
+ if (this.has(key)) {
23
+ throw new Error(`${key} is already set`);
24
+ }
25
+ return super.set(key, value);
26
+ }
27
+
28
+ /**
29
+ * @param {K} key
30
+ */
31
+ // eslint-disable-next-line no-unused-vars
32
+ delete(key) {
33
+ return false;
34
+ }
35
+
36
+ clear() {
37
+ throw new Error(`Cannot clear RoachHotelMap`);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Extensions that an extension schema file can have.
43
+ */
44
+ export const ALLOWED_SCHEMA_EXTENSIONS = new Set(['.json', '.js', '.cjs']);
45
+
46
+ /**
47
+ * A wrapper around Ajv and schema-related functions.
48
+ *
49
+ * Should have been named Highlander, because _there can only be one_
50
+ */
51
+ class AppiumSchema {
52
+ /**
53
+ * A mapping of unique argument IDs to their corresponding {@link ArgSpec}s.
54
+ *
55
+ * An "argument" is a CLI argument or a config property.
56
+ *
57
+ * Used to provide easy lookups of argument metadata when converting between different representations of those arguments.
58
+ * @private
59
+ * @type {RoachHotelMap<string,ArgSpec>}
60
+ */
61
+ _argSpecs = new RoachHotelMap();
62
+
63
+ /**
64
+ * A map of extension types to extension names to schema objects.
65
+ *
66
+ * This data structure is used to ensure there are no naming conflicts. The schemas
67
+ * are stored here in memory until the instance is _finalized_.
68
+ * @private
69
+ * @type {Record<ExtensionType,Map<string,SchemaObject>>}
70
+ */
71
+ _registeredSchemas = {[DRIVER_TYPE]: new Map(), [PLUGIN_TYPE]: new Map()};
72
+
73
+ /**
74
+ * Ajv instance
75
+ *
76
+ * @private
77
+ * @type {Ajv}
78
+ */
79
+ _ajv;
80
+
81
+ /**
82
+ * Singleton instance.
83
+ * @private
84
+ * @type {AppiumSchema}
85
+ */
86
+ static _instance;
87
+
88
+ /**
89
+ * Lookup of schema IDs to finalized schemas.
90
+ *
91
+ * This does not include references, but rather the root schemas themselves.
92
+ * @private
93
+ * @type {Record<string,StrictSchemaObject>?}
94
+ */
95
+ _finalizedSchemas = null;
96
+
97
+ /**
98
+ * Initializes Ajv, adds standard formats and our custom keywords.
99
+ * @see https://npm.im/ajv-formats
100
+ * @private
101
+ */
102
+ constructor() {
103
+ this._ajv = AppiumSchema._instantiateAjv();
104
+ }
105
+
106
+ /**
107
+ * Factory function for {@link AppiumSchema} instances.
108
+ *
109
+ * Returns a singleton instance if one exists, otherwise creates a new one.
110
+ * Binds public methods to the instance.
111
+ * @returns {AppiumSchema}
112
+ */
113
+ static create() {
114
+ if (!AppiumSchema._instance) {
115
+ const instance = new AppiumSchema();
116
+ AppiumSchema._instance = instance;
117
+ _.bindAll(instance, [
118
+ 'finalize',
119
+ 'flatten',
120
+ 'getAllArgSpecs',
121
+ 'getArgSpec',
122
+ 'getDefaults',
123
+ 'getDefaultsForExtension',
124
+ 'getSchema',
125
+ 'hasArgSpec',
126
+ 'isFinalized',
127
+ 'registerSchema',
128
+ 'hasRegisteredSchema',
129
+ 'reset',
130
+ 'validate',
131
+ ]);
132
+ }
133
+
134
+ return AppiumSchema._instance;
135
+ }
136
+
137
+ /**
138
+ * Returns `true` if a schema has been registered using given extension type and name.
139
+ *
140
+ * This does not depend on whether or not the instance has been _finalized_.
141
+ * @param {ExtensionType} extType - Extension type
142
+ * @param {string} extName - Name
143
+ * @returns {boolean} If registered
144
+ */
145
+ hasRegisteredSchema(extType, extName) {
146
+ return this._registeredSchemas[extType].has(extName);
147
+ }
148
+
149
+ /**
150
+ * Return `true` if {@link AppiumSchema.finalize finalize} has been called
151
+ * successfully and {@link AppiumSchema.reset reset} has not been called since.
152
+ * @returns {boolean} If finalized
153
+ */
154
+ isFinalized() {
155
+ return Boolean(this._finalizedSchemas);
156
+ }
157
+
158
+ getAllArgSpecs() {
159
+ return this._argSpecs;
160
+ }
161
+
162
+ /**
163
+ * Call this when no more schemas will be registered.
164
+ *
165
+ * This does three things:
166
+ * 1. It combines all schemas from extensions into the Appium config schema,
167
+ * then adds the result to the `Ajv` instance.
168
+ * 2. It adds schemas for _each_ argument/property for validation purposes.
169
+ * The CLI uses these schemas to validate specific arguments.
170
+ * 3. The schemas are validated against JSON schema draft-07 (which is the
171
+ * only one supported at this time)
172
+ *
173
+ * Any method in this instance that needs to interact with the `Ajv` instance
174
+ * will throw if this method has not been called.
175
+ *
176
+ * If the instance has already been finalized, this is a no-op.
177
+ * @public
178
+ * @throws {Error} If the schema is not valid
179
+ * @returns {Readonly<Record<string,StrictSchemaObject>>} Record of schema IDs to full schema objects
180
+ */
181
+ finalize() {
182
+ if (this.isFinalized()) {
183
+ return /** @type {NonNullable<typeof this._finalizedSchemas>} */ (this._finalizedSchemas);
184
+ }
185
+
186
+ const ajv = this._ajv;
187
+
188
+ // Ajv will _mutate_ the schema, so we need to clone it.
189
+ const baseSchema = _.cloneDeep(AppiumConfigJsonSchema);
190
+
191
+ /**
192
+ *
193
+ * @param {SchemaObject} schema
194
+ * @param {ExtensionType} [extType]
195
+ * @param {string} [extName]
196
+ */
197
+ const addArgSpecs = (schema, extType, extName) => {
198
+ for (let [propName, propSchema] of Object.entries(schema)) {
199
+ const argSpec = ArgSpec.create(propName, {
200
+ dest: propSchema.appiumCliDest,
201
+ defaultValue: propSchema.default,
202
+ extType,
203
+ extName,
204
+ });
205
+ const {arg} = argSpec;
206
+ this._argSpecs.set(arg, argSpec);
207
+ }
208
+ };
209
+
210
+ addArgSpecs(_.omit(baseSchema.properties.server.properties, [DRIVER_TYPE, PLUGIN_TYPE]));
211
+
212
+ /**
213
+ * @type {Record<string,StrictSchemaObject>}
214
+ */
215
+ const finalizedSchemas = {};
216
+
217
+ const finalSchema = _.reduce(
218
+ this._registeredSchemas,
219
+ /**
220
+ * @param {typeof baseSchema} baseSchema
221
+ * @param {Map<string,SchemaObject>} extensionSchemas
222
+ * @param {ExtensionType} extType
223
+ */
224
+ (baseSchema, extensionSchemas, extType) => {
225
+ extensionSchemas.forEach((schema, extName) => {
226
+ const $ref = ArgSpec.toSchemaBaseRef(extType, extName);
227
+ schema.$id = $ref;
228
+ schema.additionalProperties = false; // this makes `schema` become a `StrictSchemaObject`
229
+ baseSchema.properties.server.properties[extType].properties[extName] = {
230
+ $ref,
231
+ $comment: extName,
232
+ };
233
+ ajv.validateSchema(schema, true);
234
+ addArgSpecs(schema.properties, extType, extName);
235
+ ajv.addSchema(schema, $ref);
236
+ finalizedSchemas[$ref] = /** @type {StrictSchemaObject} */ (schema);
237
+ });
238
+ return baseSchema;
239
+ },
240
+ baseSchema
241
+ );
242
+
243
+ ajv.addSchema(finalSchema, APPIUM_CONFIG_SCHEMA_ID);
244
+ finalizedSchemas[APPIUM_CONFIG_SCHEMA_ID] = finalSchema;
245
+ ajv.validateSchema(finalSchema, true);
246
+
247
+ this._finalizedSchemas = finalizedSchemas;
248
+ return Object.freeze(finalizedSchemas);
249
+ }
250
+
251
+ /**
252
+ * Configures and creates an Ajv instance.
253
+ * @private
254
+ * @returns {Ajv}
255
+ */
256
+ static _instantiateAjv() {
257
+ const ajv = addFormats(
258
+ new Ajv({
259
+ // without this not much validation actually happens
260
+ allErrors: true,
261
+ })
262
+ );
263
+
264
+ // add custom keywords to ajv. see schema-keywords.js
265
+ _.forEach(keywords, (keyword) => {
266
+ ajv.addKeyword(keyword);
267
+ });
268
+
269
+ return ajv;
270
+ }
271
+
272
+ /**
273
+ * Resets this instance to its original state.
274
+ *
275
+ * - Removes all added schemas from the `Ajv` instance
276
+ * - Resets the map of {@link ArgSpec ArgSpecs}
277
+ * - Resets the map of registered schemas
278
+ * - Sets the {@link AppiumSchema._finalized _finalized} flag to `false`
279
+ *
280
+ * If you need to call {@link AppiumSchema.finalize} again, you'll want to call this first.
281
+ * @returns {void}
282
+ */
283
+ reset() {
284
+ for (const schemaId of Object.keys(this._finalizedSchemas ?? {})) {
285
+ this._ajv.removeSchema(schemaId);
286
+ }
287
+ this._argSpecs = new RoachHotelMap();
288
+ this._registeredSchemas = {
289
+ [DRIVER_TYPE]: new Map(),
290
+ [PLUGIN_TYPE]: new Map(),
291
+ };
292
+ this._finalizedSchemas = null;
293
+
294
+ // Ajv seems to have an over-eager cache, so we have to dump the object entirely.
295
+ this._ajv = AppiumSchema._instantiateAjv();
296
+ }
297
+
298
+ /**
299
+ * Registers a schema from an extension.
300
+ *
301
+ * This is "fail-fast" in that the schema will immediately be validated against JSON schema draft-07 _or_ whatever the value of the schema's `$schema` prop is.
302
+ *
303
+ * Does _not_ add the schema to the `ajv` instance (this is done by {@link AppiumSchema.finalize}).
304
+ * @param {ExtensionType} extType - Extension type
305
+ * @param {string} extName - Unique extension name for `type`
306
+ * @param {SchemaObject} schema - Schema object
307
+ * @throws {SchemaNameConflictError} If the schema is an invalid
308
+ * @returns {void}
309
+ */
310
+ registerSchema(extType, extName, schema) {
311
+ if (!(extType && extName) || _.isUndefined(schema)) {
312
+ throw new TypeError('Expected extension type, extension name, and a defined schema');
313
+ }
314
+ if (!AppiumSchema.isSupportedSchemaType(schema)) {
315
+ throw new SchemaUnsupportedSchemaError(schema, extType, extName);
316
+ }
317
+ const normalizedExtName = _.kebabCase(extName);
318
+ if (this.hasRegisteredSchema(extType, normalizedExtName)) {
319
+ if (this._registeredSchemas[extType].get(normalizedExtName) === schema) {
320
+ return;
321
+ }
322
+ throw new SchemaNameConflictError(extType, extName);
323
+ }
324
+ this._ajv.validateSchema(schema, true);
325
+
326
+ this._registeredSchemas[extType].set(normalizedExtName, schema);
327
+ }
328
+
329
+ /**
330
+ * Returns a {@link ArgSpec} for the given argument name.
331
+ * @param {string} name - CLI argument name
332
+ * @param {ExtensionType} [extType] - Extension type
333
+ * @param {string} [extName] - Extension name
334
+ * @returns {ArgSpec|undefined} ArgSpec or `undefined` if not found
335
+ */
336
+ getArgSpec(name, extType, extName) {
337
+ return this._argSpecs.get(ArgSpec.toArg(name, extType, extName));
338
+ }
339
+
340
+ /**
341
+ * Returns `true` if the instance knows about an argument by the given `name`.
342
+ * @param {string} name - CLI argument name
343
+ * @param {ExtensionType} [extType] - Extension type
344
+ * @param {string} [extName] - Extension name
345
+ * @returns {boolean} `true` if such an {@link ArgSpec} exists
346
+ */
347
+ hasArgSpec(name, extType, extName) {
348
+ return this._argSpecs.has(ArgSpec.toArg(name, extType, extName));
349
+ }
350
+
351
+ /**
352
+ * Returns a `Record` of argument "dest" strings to default values.
353
+ *
354
+ * The "dest" string is the property name in object returned by
355
+ * `argparse.ArgumentParser['parse_args']`.
356
+ * @template {boolean|undefined} Flattened
357
+ * @param {Flattened} [flatten=true] - If `true`, flattens the returned object
358
+ * using "keypath"-style keys of the format `<extType>.<extName>.<argName>`.
359
+ * Otherwise, returns a nested object using `extType` and `extName` as
360
+ * properties. Base arguments (server arguments) are always at the top level.
361
+ * @returns {DefaultValues<Flattened>}
362
+ */
363
+ getDefaults(flatten = /** @type {Flattened} */ (true)) {
364
+ if (!this.isFinalized()) {
365
+ throw new SchemaFinalizationError();
366
+ }
367
+
368
+ /**
369
+ * @private
370
+ * @callback DefaultReducer
371
+ * @param {DefaultValues<Flattened>} defaults
372
+ * @param {ArgSpec} argSpec
373
+ * @returns {DefaultValues<Flattened>}
374
+ */
375
+ /** @type {DefaultReducer} */
376
+ const reducer = flatten
377
+ ? (defaults, {defaultValue, dest}) => {
378
+ if (!_.isUndefined(defaultValue)) {
379
+ defaults[dest] = defaultValue;
380
+ }
381
+ return defaults;
382
+ }
383
+ : (defaults, {defaultValue, dest}) => {
384
+ if (!_.isUndefined(defaultValue)) {
385
+ _.set(defaults, dest, defaultValue);
386
+ }
387
+ return defaults;
388
+ };
389
+
390
+ /** @type {DefaultValues<Flattened>} */
391
+ const retval = {};
392
+ return [...this._argSpecs.values()].reduce(reducer, retval);
393
+ }
394
+
395
+ /**
396
+ * Returns a flattened Record of defaults for a specific extension. Keys will
397
+ * be of format `<argName>`.
398
+ * @param {ExtensionType} extType - Extension type
399
+ * @param {string} extName - Extension name
400
+ * @returns {Record<string,ArgSpecDefaultValue>}
401
+ */
402
+ getDefaultsForExtension(extType, extName) {
403
+ if (!this.isFinalized()) {
404
+ throw new SchemaFinalizationError();
405
+ }
406
+ const specs = [...this._argSpecs.values()].filter(
407
+ (spec) => spec.extType === extType && spec.extName === extName
408
+ );
409
+ return specs.reduce((defaults, {defaultValue, rawDest}) => {
410
+ if (!_.isUndefined(defaultValue)) {
411
+ defaults[rawDest] = defaultValue;
412
+ }
413
+ return defaults;
414
+ }, {});
415
+ }
416
+
417
+ /**
418
+ * Flatten schema into an array of `SchemaObject`s and associated
419
+ * {@link ArgSpec ArgSpecs}.
420
+ *
421
+ * Converts nested extension schemas to keys based on the extension type and
422
+ * name. Used when translating to `argparse` options or getting the list of
423
+ * default values (see {@link AppiumSchema.getDefaults}) for CLI or otherwise.
424
+ *
425
+ * The return value is an intermediate reprsentation used by `cli-args`
426
+ * module's `toParserArgs`, which converts the finalized schema to parameters
427
+ * used by `argparse`.
428
+ * @throws If {@link AppiumSchema.finalize} has not been called yet.
429
+ * @returns {FlattenedSchema}
430
+ */
431
+ flatten() {
432
+ const schema = this.getSchema();
433
+
434
+ /** @type { {properties: SchemaObject, prefix: string[]}[] } */
435
+ const stack = [{properties: schema.properties, prefix: []}];
436
+ /** @type {FlattenedSchema} */
437
+ const flattened = [];
438
+
439
+ // this bit is a recursive algorithm rewritten as a for loop.
440
+ // when we find something we want to traverse, we add it to `stack`
441
+ for (const {properties, prefix} of stack) {
442
+ const pairs = _.toPairs(properties);
443
+ for (const [key, value] of pairs) {
444
+ const {properties, $ref} = value;
445
+ if (properties) {
446
+ stack.push({
447
+ properties,
448
+ prefix: key === SERVER_PROP_NAME ? [] : [...prefix, key],
449
+ });
450
+ } else if ($ref) {
451
+ let refSchema;
452
+ try {
453
+ refSchema = this.getSchema($ref);
454
+ } catch (err) {
455
+ // this can happen if an extension schema supplies a $ref to a non-existent schema
456
+ throw new SchemaUnknownSchemaError($ref);
457
+ }
458
+ const {normalizedExtName} = ArgSpec.extensionInfoFromRootSchemaId($ref);
459
+ if (!normalizedExtName) {
460
+ /* istanbul ignore next */
461
+ throw new ReferenceError(
462
+ `Could not determine extension name from schema ID ${$ref}. This is a bug.`
463
+ );
464
+ }
465
+ stack.push({
466
+ properties: refSchema.properties,
467
+ prefix: [...prefix, key, normalizedExtName],
468
+ });
469
+ } else if (key !== DRIVER_TYPE && key !== PLUGIN_TYPE) {
470
+ const [extType, extName] = prefix;
471
+ const argSpec = this.getArgSpec(key, /** @type {ExtensionType} */ (extType), extName);
472
+ if (!argSpec) {
473
+ /* istanbul ignore next */
474
+ throw new ReferenceError(
475
+ `Unknown argument with key ${key}, extType ${extType} and extName ${extName}. This is a bug.`
476
+ );
477
+ }
478
+ flattened.push({schema: _.cloneDeep(value), argSpec});
479
+ }
480
+ }
481
+ }
482
+
483
+ return flattened;
484
+ }
485
+
486
+ /**
487
+ * Retrieves the schema itself
488
+ * @public
489
+ * @param {string} [ref] - Schema ID
490
+ * @throws If the schema has not yet been finalized
491
+ * @returns {SchemaObject}
492
+ */
493
+ getSchema(ref = APPIUM_CONFIG_SCHEMA_ID) {
494
+ return /** @type {SchemaObject} */ (this._getValidator(ref).schema);
495
+ }
496
+
497
+ /**
498
+ * Retrieves schema validator function from Ajv
499
+ * @param {string} [id] - Schema ID
500
+ * @private
501
+ * @returns {import('ajv').ValidateFunction}
502
+ */
503
+ _getValidator(id = APPIUM_CONFIG_SCHEMA_ID) {
504
+ const validator = this._ajv.getSchema(id);
505
+ if (!validator) {
506
+ if (id === APPIUM_CONFIG_SCHEMA_ID) {
507
+ throw new SchemaFinalizationError();
508
+ } else {
509
+ throw new SchemaUnknownSchemaError(id);
510
+ }
511
+ }
512
+ return validator;
513
+ }
514
+
515
+ /**
516
+ * Given an object, validates it against the Appium config schema.
517
+ * If errors occur, the returned array will be non-empty.
518
+ * @param {any} value - The value (hopefully an object) to validate against the schema
519
+ * @param {string} [ref] - Schema ID or ref.
520
+ * @public
521
+ * @returns {import('ajv').ErrorObject[]} Array of errors, if any.
522
+ */
523
+ validate(value, ref = APPIUM_CONFIG_SCHEMA_ID) {
524
+ const validator = this._getValidator(ref);
525
+ return !validator(value) && _.isArray(validator.errors) ? [...validator.errors] : [];
526
+ }
527
+
528
+ /**
529
+ * Returns `true` if `filename`'s file extension is allowed (in {@link ALLOWED_SCHEMA_EXTENSIONS}).
530
+ * @param {string} filename
531
+ * @returns {boolean}
532
+ */
533
+ static isAllowedSchemaFileExtension(filename) {
534
+ return ALLOWED_SCHEMA_EXTENSIONS.has(path.extname(filename));
535
+ }
536
+
537
+ /**
538
+ * Returns `true` if `schema` is a plain object with a non-true `$async` property.
539
+ * @param {any} schema - Schema to check
540
+ * @returns {schema is SchemaObject}
541
+ */
542
+ static isSupportedSchemaType(schema) {
543
+ return _.isPlainObject(schema) && schema.$async !== true;
544
+ }
545
+ }
546
+
547
+ /**
548
+ * Thrown when the {@link AppiumSchema} instance has not yet been finalized, but
549
+ * the method called requires it.
550
+ */
551
+ export class SchemaFinalizationError extends Error {
552
+ /**
553
+ * @type {Readonly<string>}
554
+ */
555
+ code = 'APPIUMERR_SCHEMA_FINALIZATION';
556
+
557
+ constructor() {
558
+ super('Schema not yet finalized; `finalize()` must be called first.');
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Thrown when a "unique" schema ID conflicts with an existing schema ID.
564
+ *
565
+ * This is likely going to be caused by attempting to register the same schema twice.
566
+ */
567
+ export class SchemaNameConflictError extends Error {
568
+ /**
569
+ * @type {Readonly<string>}
570
+ */
571
+ code = 'APPIUMERR_SCHEMA_NAME_CONFLICT';
572
+
573
+ /**
574
+ * @type {Readonly<{extType: ExtensionType, extName: string}>}
575
+ */
576
+ data;
577
+
578
+ /**
579
+ * @param {ExtensionType} extType
580
+ * @param {string} extName
581
+ */
582
+ constructor(extType, extName) {
583
+ super(`Name for ${extType} schema "${extName}" conflicts with an existing schema`);
584
+ this.data = {extType, extName};
585
+ }
586
+ }
587
+
588
+ /**
589
+ * Thrown when a schema ID was expected, but it doesn't exist on the {@link Ajv} instance.
590
+ */
591
+ export class SchemaUnknownSchemaError extends ReferenceError {
592
+ /**
593
+ * @type {Readonly<string>}
594
+ */
595
+ code = 'APPIUMERR_SCHEMA_UNKNOWN_SCHEMA';
596
+
597
+ /**
598
+ * @type {Readonly<{schemaId: string}>}
599
+ */
600
+ data;
601
+
602
+ /**
603
+ * @param {string} schemaId
604
+ */
605
+ constructor(schemaId) {
606
+ super(`Unknown schema: "${schemaId}"`);
607
+ this.data = {schemaId};
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Thrown when a schema is provided, but it's of an unsupported type.
613
+ *
614
+ * "Valid" schemas which are unsupported include boolean schemas and async schemas
615
+ * (having a `true` `$async` property).
616
+ */
617
+ export class SchemaUnsupportedSchemaError extends TypeError {
618
+ /**
619
+ * @type {Readonly<string>}
620
+ */
621
+ code = 'APPIUMERR_SCHEMA_UNSUPPORTED_SCHEMA';
622
+
623
+ /**
624
+ * @type {Readonly<{schema: any, extType: ExtensionType, extName: string}>}
625
+ */
626
+ data;
627
+
628
+ /**
629
+ * @param {any} schema
630
+ * @param {ExtensionType} extType
631
+ * @param {string} extName
632
+ */
633
+ constructor(schema, extType, extName) {
634
+ // https://github.com/Microsoft/TypeScript/issues/8277
635
+ super(
636
+ (() => {
637
+ let msg = `Unsupported schema from ${extType} "${extName}":`;
638
+ if (_.isBoolean(schema)) {
639
+ return `${msg} schema cannot be a boolean`;
640
+ }
641
+ if (_.isPlainObject(schema)) {
642
+ if (schema.$async) {
643
+ return `${msg} schema cannot be an async schema`;
644
+ }
645
+ /* istanbul ignore next */
646
+ throw new TypeError(
647
+ `schema IS supported; this error should not be thrown (this is a bug). value of schema: ${JSON.stringify(
648
+ schema
649
+ )}`
650
+ );
651
+ }
652
+ return `${msg} schema must be a plain object without a true "$async" property`;
653
+ })()
654
+ );
655
+ this.data = {schema, extType, extName};
656
+ }
657
+ }
658
+
659
+ const appiumSchema = AppiumSchema.create();
660
+
661
+ export const {
662
+ registerSchema,
663
+ getAllArgSpecs,
664
+ getArgSpec,
665
+ hasArgSpec,
666
+ isFinalized,
667
+ finalize: finalizeSchema,
668
+ reset: resetSchema,
669
+ validate,
670
+ getSchema,
671
+ flatten: flattenSchema,
672
+ getDefaults: getDefaultsForSchema,
673
+ getDefaultsForExtension,
674
+ } = appiumSchema;
675
+ export const {isAllowedSchemaFileExtension} = AppiumSchema;
676
+
677
+ /**
678
+ * Appium only supports schemas that are plain objects; not arrays.
679
+ * @typedef {import('ajv').SchemaObject & {[key: number]: never}} SchemaObject
680
+ */
681
+
682
+ /**
683
+ * @typedef {import('../extension/manifest').ExtensionType} ExtensionType
684
+ */
685
+
686
+ /**
687
+ * An object having property `additionalProperties: false`
688
+ * @typedef StrictProp
689
+ * @property {false} additionalProperties
690
+ */
691
+
692
+ /**
693
+ * A {@link SchemaObject} with `additionalProperties: false`
694
+ * @typedef {SchemaObject & StrictProp} StrictSchemaObject
695
+ */
696
+
697
+ /**
698
+ * A list of schemas associated with properties and their corresponding {@link ArgSpec} objects.
699
+ *
700
+ * Intermediate data structure used when converting the entire schema down to CLI arguments.
701
+ * @typedef { {schema: SchemaObject, argSpec: ArgSpec}[] } FlattenedSchema
702
+ */
703
+
704
+ /**
705
+ * @typedef {ArgSpec['defaultValue']} ArgSpecDefaultValue
706
+ */
707
+
708
+ /**
709
+ * e.g. `{driver: {foo: 'bar'}}` where `foo` is the arg name and `bar` is the default value.
710
+ * @typedef {Record<string,Record<string,ArgSpecDefaultValue>>} NestedArgSpecDefaultValue
711
+ */
712
+
713
+ /**
714
+ * Helper type for the return value of {@link AppiumSchema.getDefaults}
715
+ * @template {boolean|undefined} Flattened
716
+ * @typedef {Record<string,Flattened extends true ? ArgSpecDefaultValue : ArgSpecDefaultValue | NestedArgSpecDefaultValue>} DefaultValues
717
+ */