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