File size: 9,107 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env node
const fs = require( 'fs' );
const path = require( 'path' );
const vm = require( 'vm' );
const _ = require( 'lodash' );

const areaCodes = {
	CA: [
		'204',
		'236',
		'249',
		'250',
		'289',
		'306',
		'343',
		'365',
		'387',
		'403',
		'416',
		'418',
		'431',
		'437',
		'438',
		'450',
		'506',
		'514',
		'519',
		'548',
		'579',
		'581',
		'587',
		'604',
		'613',
		'639',
		'647',
		'672',
		'705',
		'709',
		'742',
		'778',
		'780',
		'782',
		'807',
		'819',
		'825',
		'867',
		'873',
		'902',
		'905',
	],
	DO: [ '809', '829', '849' ],
	PR: [ '787', '939' ],
};

/**
 * Some countries share a dial code and need a priority order to make an early guess. These are made up numbers to order
 * the countries by their population.
 * Priorities should be distinct among the same dial code group.
 * @type Object
 */
const priorityData = {
	// dial code: +1
	US: 10,
	CA: 5,
	DO: 3,
	PR: 1,
	UM: -99,
	// dial code: +7
	RU: 10,
	KZ: 1,
	// dial code: +39
	IT: 10,
	VA: 1,
	// dial code: +44
	GB: 10,
	JE: 5,
	IM: 3,
	GG: 1,
	// dial code: +47
	NO: 10,
	SJ: 1,
	BV: -99,
	// dial code: +61
	AU: 10,
	CX: 5,
	CC: 1,
	HM: -99,
	// dial code: +64
	NZ: 10,
	PN: -99,
	// dial code: +290
	SH: 10,
	TA: 1,
	// dial code: +358
	FI: 10,
	AX: 1,
	// dial code: +500
	FK: 10,
	GS: -99,
	// dial code: +590
	GP: 10,
	MF: 5,
	BL: 1,
	// dial code: +599
	CW: 10,
	BQ: 1,
};

const LIBPHONENUMBER_METADATA_URL =
	'https://raw.githubusercontent.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/metadatalite.js';

const libPhoneNumberIndexes = {
	COUNTRY_CODE: 9,
	COUNTRY_DIAL_CODE: 10,
	INTERNATIONAL_PREFIX: 11,
	NATIONAL_PREFIX: 12,
	NATIONAL_PARSING_PREFIX: 15,
	NUMBER_FORMAT: 19,
	INTERNATIONAL_NUMBER_FORMAT: 20, // TYPE: NumberFormat,
	REGION_AREA_CODE: 23,
};

const numberFormatIndexes = {
	PATTERN: 1,
	FORMAT: 2,
	LEADING_DIGIT_PATTERN: 3,
	NATIONAL_CALLING_FORMAT: 4,
};

const aliases = {
	UK: 'GB',
};

async function getLibPhoneNumberData() {
	const response = await fetch( LIBPHONENUMBER_METADATA_URL );
	if ( response.status >= 400 ) {
		throw response.status;
	}

	const body = await response.text();

	const capture = body.substring( body.indexOf( 'countryToMetadata = ' ) + 20, body.length - 2 );
	const sandbox = { container: {} };
	const script = new vm.Script( 'container.data = ' + capture );

	script.runInNewContext( sandbox );

	if ( ! sandbox.container.data ) {
		throw new Error( 'Failed to parse data' );
	}

	return sandbox.container.data;
}

function processNumberFormat( format ) {
	return {
		match: format[ numberFormatIndexes.PATTERN ],
		replace: format[ numberFormatIndexes.FORMAT ],
		nationalFormat: format[ numberFormatIndexes.NATIONAL_CALLING_FORMAT ] || undefined,
		leadingDigitPattern: _.last( format[ numberFormatIndexes.LEADING_DIGIT_PATTERN ] || [] ),
	};
}

/**
 * Deeply iterates over the keys of an object to remove any keys that are "undefined". This method modifies the object.
 * @param {Object} obj
 * @returns {Object} obj, with keys with value "undefined" removed.
 */
function deepRemoveUndefinedKeysFromObject( obj ) {
	for ( const key in obj ) {
		if ( obj.hasOwnProperty( key ) ) {
			if ( typeof obj[ key ] === 'undefined' ) {
				delete obj[ key ];
			} else if ( _.isObject( obj[ key ] ) ) {
				deepRemoveUndefinedKeysFromObject( obj[ key ] );
			}
		}
	}
	return obj;
}

function generateDeepRemoveEmptyArraysFromObject( allowedKeys ) {
	return function deepRemoveEmptyArraysFromObject( obj ) {
		for ( const key in obj ) {
			if ( obj.hasOwnProperty( key ) ) {
				if (
					_.includes( allowedKeys, key ) &&
					Array.isArray( obj[ key ] ) &&
					obj[ key ].length === 0
				) {
					delete obj[ key ];
				} else if ( _.isObject( obj[ key ] ) ) {
					deepRemoveEmptyArraysFromObject( obj[ key ] );
				}
			}
		}
		return obj;
	};
}

function removeAllNumberKeys( obj ) {
	return _.omitBy( obj, ( val, key ) => /^\d+$/.test( key ) );
}

function removeRegionCodeAndCountryDialCodeIfSameWithCountryDialCode( countryData ) {
	for ( const key in countryData ) {
		if ( countryData.hasOwnProperty( key ) ) {
			const country = countryData[ key ];
			const { countryDialCode, dialCode } = country;
			if ( countryDialCode === dialCode ) {
				delete country.regionCode;
				delete country.countryDialCode;
			}
		}
	}
	return countryData;
}

/**
 * Processes Google's libphonenumber data and generates a proper JS object
 * @param {{}} libPhoneNumberData
 * @returns {{}}
 */
function processLibPhoneNumberMetadata( libPhoneNumberData ) {
	const data = {};
	for ( const countryCode in libPhoneNumberData ) {
		if ( libPhoneNumberData.hasOwnProperty( countryCode ) ) {
			const countryCodeUpper = countryCode.toUpperCase();
			const country = libPhoneNumberData[ countryCode ];
			data[ countryCodeUpper ] = {
				isoCode: countryCodeUpper,
				dialCode: String(
					country[ libPhoneNumberIndexes.COUNTRY_DIAL_CODE ] +
						( country[ libPhoneNumberIndexes.REGION_AREA_CODE ] || '' )
				),
				countryDialCode: String( country[ libPhoneNumberIndexes.COUNTRY_DIAL_CODE ] ),
				regionCode: country[ libPhoneNumberIndexes.REGION_AREA_CODE ] || '',
				areaCodes: areaCodes[ countryCode ],
				nationalPrefix: country[ libPhoneNumberIndexes.NATIONAL_PREFIX ],
				patterns: ( country[ libPhoneNumberIndexes.NUMBER_FORMAT ] || [] ).map(
					processNumberFormat
				),
				internationalPatterns: (
					country[ libPhoneNumberIndexes.INTERNATIONAL_NUMBER_FORMAT ] || []
				).map( processNumberFormat ),
				priority: priorityData[ countryCodeUpper ],
			};
		}
	}

	const noPattern = _.filter(
		data,
		_.conforms( { patterns: ( patterns ) => patterns.length === 0 } )
	);
	_.forIn( noPattern, function ( country ) {
		country.patternRegion = (
			_.maxBy( _.values( _.filter( data, { dialCode: country.dialCode } ) ), 'priority' ) || {}
		).isoCode;
		console.log(
			'Info: ' +
				country.isoCode +
				" didn't have a pattern" +
				( country.patternRegion ? ' so we use ' + country.patternRegion : '.' )
		);
	} );
	return data;
}

// Political correction
function injectHardCodedValues( libPhoneNumberData ) {
	return Object.assign(
		{},
		{
			KV: {
				isoCode: 'KV',
				dialCode: '383',
				nationalPrefix: '0',
				priority: priorityData.KV,
			},
			UM: {
				isoCode: 'UM',
				dialCode: '1',
				nationalPrefix: '',
				patternRegion: 'US',
				priority: priorityData.UM,
			},
			BV: {
				isoCode: 'BV',
				dialCode: '47',
				nationalPrefix: '',
				priority: priorityData.BV,
			},
			TF: {
				isoCode: 'TF',
				dialCode: '262',
				nationalPrefix: '0',
				priority: priorityData.TF,
			},
			HM: {
				isoCode: 'HM',
				dialCode: '61',
				nationalPrefix: '0',
				priority: priorityData.HM,
			},
			PN: {
				isoCode: 'PN',
				dialCode: '64',
				nationalPrefix: '0',
				priority: priorityData.PN,
			},
			GS: {
				isoCode: 'GS',
				nationalPrefix: '',
				dialCode: '500',
				priority: priorityData.GS,
			},
		},
		libPhoneNumberData
	);
}

/**
 * Creates aliases. E.g. allows `uk` to be found by both `gb` and `uk`.
 * @param data
 */
function insertCountryAliases( data ) {
	Object.keys( aliases ).forEach( ( source ) => {
		data[ source ] = data[ aliases[ source ] ];
	} );
	return data;
}

/**
 * Wraps and saves data to '../client/components/phone-input/data.js'
 * @param {Object} data
 */
function saveToFile( data ) {
	const scriptStr =
		'// Generated by build-metadata.js\n' +
		'/* eslint-disable */\n' +
		Object.keys( data )
			.map( ( key ) => `export const ${ key } = ${ JSON.stringify( data[ key ], null, '\t' ) };\n` )
			.join( '\n' ) +
		'/* eslint-enable */\n';
	const filePath = path.resolve(
		__dirname,
		'..',
		'client',
		'components',
		'phone-input',
		'data.js'
	);
	fs.writeFileSync( filePath, scriptStr );
}

function generateDialCodeMap( metadata ) {
	const res = {};
	function addValue( key, value ) {
		if ( ! /^\d+$/.test( key ) ) {
			console.warn( 'Warning: ' + value + ' has invalid dialCode: ' + key );
			return;
		}
		res[ key ] = res[ key ] || [];
		if ( ! _.includes( res[ key ], value ) ) {
			res[ key ].push( value );
		}
	}
	_.forIn( metadata, function ( country ) {
		addValue( country.dialCode, country.isoCode );
		( country.areaCodes || [] ).forEach( ( areaCode ) =>
			addValue( country.dialCode + areaCode, country.isoCode )
		);
	} );

	return _.mapValues( res, ( countryCodes ) =>
		_.orderBy( countryCodes, ( countryCode ) => metadata[ countryCode ].priority || 0, 'desc' )
	);
}

function generateFullDataset( metadata ) {
	return {
		countries: metadata,
		dialCodeMap: generateDialCodeMap( metadata ),
	};
}

getLibPhoneNumberData()
	.then( processLibPhoneNumberMetadata )
	.then( injectHardCodedValues )
	.then( generateDeepRemoveEmptyArraysFromObject( [ 'patterns', 'internationalPatterns' ] ) )
	.then( insertCountryAliases )
	.then( removeAllNumberKeys )
	.then( removeRegionCodeAndCountryDialCodeIfSameWithCountryDialCode )
	.then( generateFullDataset )
	.then( deepRemoveUndefinedKeysFromObject )
	.then( saveToFile )
	.catch( function ( error ) {
		console.error( error.stack );
		process.exit( -1 );
	} );