forked from opening-hours/opening_hours.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
4007 lines (3547 loc) · 186 KB
/
index.js
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* jshint laxbreak: true */
/* jshint boss: true */
/* jshint loopfunc: true */
import * as holiday_definitions from './holidays/index';
import word_error_correction from './locales/word_error_correction.yaml';
import lang from './locales/lang.yaml';
import moment from 'moment';
import SunCalc from 'suncalc';
import i18n from './locales/core';
export default function(value, nominatim_object, optional_conf_parm) {
// short constants {{{
var word_value_replacement = { // If the correct values can not be calculated.
dawn : 60 * 5 + 30,
sunrise : 60 * 6,
sunset : 60 * 18,
dusk : 60 * 18 + 30,
};
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var weekdays = ['Su','Mo','Tu','We','Th','Fr','Sa'];
var string_to_token_map = {
'su': [ 0, 'weekday' ],
'mo': [ 1, 'weekday' ],
'tu': [ 2, 'weekday' ],
'we': [ 3, 'weekday' ],
'th': [ 4, 'weekday' ],
'fr': [ 5, 'weekday' ],
'sa': [ 6, 'weekday' ],
'jan': [ 0, 'month' ],
'feb': [ 1, 'month' ],
'mar': [ 2, 'month' ],
'apr': [ 3, 'month' ],
'may': [ 4, 'month' ],
'jun': [ 5, 'month' ],
'jul': [ 6, 'month' ],
'aug': [ 7, 'month' ],
'sep': [ 8, 'month' ],
'oct': [ 9, 'month' ],
'nov': [ 10, 'month' ],
'dec': [ 11, 'month' ],
'day': [ 'day', 'calcday' ],
'days': [ 'days', 'calcday' ],
'sunrise': [ 'sunrise', 'timevar' ],
'sunset': [ 'sunset', 'timevar' ],
'dawn': [ 'dawn', 'timevar' ],
'dusk': [ 'dusk', 'timevar' ],
'easter': [ 'easter', 'event' ],
'week': [ 'week', 'week' ],
'open': [ 'open', 'state' ],
'closed': [ 'closed', 'state' ],
'off': [ 'off', 'state' ],
'unknown': [ 'unknown', 'state' ],
}
var default_prettify_conf = {
// Update README.md if changed.
'zero_pad_hour': true, // enforce ("%02d", hour)
'one_zero_if_hour_zero': false, // only one zero "0" if hour is zero "0"
'leave_off_closed': true, // leave keywords "off" and "closed" as is
'keyword_for_off_closed': 'off', // use given keyword instead of "off" or "closed"
'rule_sep_string': ' ', // separate rules by string
'print_semicolon': true, // print token which separates normal rules
'leave_weekday_sep_one_day_betw': true, // use the separator (either "," or "-" which is used to separate days which follow to each other like Sa,Su or Su-Mo
'sep_one_day_between': ',', // separator which should be used
'zero_pad_month_and_week_numbers': true, // Format week (e.g. `week 01`) and month day numbers (e.g. `Jan 01`) with "%02d".
'locale': 'en', // use local language (needs moment.js / i18n.js)
};
var osm_tag_defaults = {
'opening_hours' : { 'mode' : 0, 'warn_for_PH_missing' : true, },
'collection_times' : { 'mode' : 2, },
/* oh_mode 2: "including the hyphen because there are post boxes which are
* emptied several (undefined) times or one (undefined) time in a certain time
* frame. This shall be covered also.".
* Ref: https://wiki.openstreetmap.org/wiki/Key:collection_times */
'opening_hours:.+' : { 'mode' : 0, },
'.+:opening_hours' : { 'mode' : 0, },
'.+:opening_hours:.+' : { 'mode' : 0, },
'smoking_hours' : { 'mode' : 0, },
'service_times' : { 'mode' : 2, },
'happy_hours' : { 'mode' : 0, },
'lit' : { 'mode' : 0,
map: {
'yes' : 'sunset-sunrise open "specified as yes: At night (unknown time schedule or daylight detection)"',
'automatic': 'unknown "specified as automatic: When someone enters the way the lights are turned on."',
'no' : 'off "specified as no: There are no lights installed."',
'interval' : 'unknown "specified as interval"',
'limited' : 'unknown "specified as limited"',
}
},
};
var minutes_in_day = 60 * 24;
var msec_in_day = 1000 * 60 * minutes_in_day;
// var msec_in_week = msec_in_day * 7;
var library_name = 'opening_hours.js';
var repository_url = 'https://github.com/opening-hours/' + library_name;
// var issues_url = repository_url + '/issues?state=open';
/* }}} */
/* translation function {{{ */
/* Roughly compatibly to i18next so we can replace everything by i18next include later
* sprintf support
*/
var locale = 'en'; // Default locale
if (typeof i18n === 'object') {
locale = i18n.lng();
}
var t = function(str, variables) {
if (
typeof i18n === 'object'
&& typeof i18n.t === 'function'
&& typeof locale === 'string'
&& ['de'].indexOf(locale) !== -1
) {
var global_locale = i18n.lng();
if (global_locale !== locale) {
i18n.setLng(locale);
}
var text = i18n.t('opening_hours:texts.' + str, variables);
if (global_locale !== locale) {
i18n.setLng(global_locale);
}
return text;
}
var text = lang[str];
if (typeof text === 'undefined') {
text = str;
}
return text.replace(/__([^_]*)__/g, function (match, c) {
return typeof variables[c] !== 'undefined'
? variables[c]
: match
;
}
);
};
/* }}} */
/* Optional constructor parameters {{{ */
/* nominatim_object {{{
*
* Required to reasonably calculate 'sunrise' and holidays.
*/
var location_cc, location_state, lat, lon;
if (typeof nominatim_object === 'object' && nominatim_object !== null) {
if (typeof nominatim_object.address === 'object') {
if (typeof nominatim_object.address.country_code === 'string') {
location_cc = nominatim_object.address.country_code;
}
if (typeof nominatim_object.address.state === 'string') {
location_state = nominatim_object.address.state;
} else if (typeof nominatim_object.address.county === 'string') {
location_state = nominatim_object.address.county;
}
}
if (typeof nominatim_object.lon === 'string' && typeof nominatim_object.lat === 'string') {
lat = nominatim_object.lat;
lon = nominatim_object.lon;
}
} else if (nominatim_object === null) {
/* Set the location to some random value. This can be used if you don’t
* care about correct opening hours for more complex opening_hours
* values.
*/
location_cc = 'de';
location_state = 'Baden-W\u00fcrttemberg';
lat = '49.5400039';
lon = '9.7937133';
} else if (typeof nominatim_object !== 'undefined') {
throw 'The nominatim_object parameter is of unknown type.'
+ ' Given ' + typeof(nominatim_object)
+ ', expected object.';
}
/* }}} */
/* mode, locale, warnings_severity, tag_key, map_value {{{
*
* 0: time ranges (default), tags: opening_hours, lit, …
* 1: points in time
* 2: both (time ranges and points in time), tags: collection_times, service_times
*/
var warnings_severity = 4;
/* Default, currently the highest severity supported.
* This number is expected to be >= 4. This is not explicitly checked.
*/
var oh_mode;
var oh_map_value = false;
var oh_key, oh_regex_key;
if (typeof optional_conf_parm === 'number') {
oh_mode = optional_conf_parm;
} else if (typeof optional_conf_parm === 'object') {
locale = optional_conf_parm['locale'];
if (checkOptionalConfParm('mode', 'number')) {
oh_mode = optional_conf_parm['mode'];
}
if (checkOptionalConfParm('warnings_severity', 'number')) {
warnings_severity = optional_conf_parm['warnings_severity'];
if ([ 0, 1, 2, 3, 4, 5, 6, 7 ].indexOf(warnings_severity) === -1) {
throw t('warnings severity', { 'severity': warnings_severity, 'allowed': '[ 0, 1, 2, 3, 4, 5, 6, 7 ]' });
}
}
if (checkOptionalConfParm('tag_key', 'string')) {
oh_key = optional_conf_parm['tag_key'];
}
if (checkOptionalConfParm('map_value', 'boolean')) {
oh_map_value = optional_conf_parm.map_value;
}
} else if (typeof optional_conf_parm !== 'undefined') {
throw t('optional conf parm type', { 'given': typeof(optional_conf_parm) });
}
if (typeof oh_key === 'string') {
oh_regex_key = getRegexKeyForKeyFromOsmDefaults(oh_key)
if (oh_map_value
&& typeof osm_tag_defaults[oh_regex_key] === 'object'
&& typeof osm_tag_defaults[oh_regex_key]['map'] === 'object'
&& typeof osm_tag_defaults[oh_regex_key]['map'][value] === 'string'
) {
value = osm_tag_defaults[oh_regex_key]['map'][value];
}
} else if (oh_map_value) {
throw t('conf param tag key missing');
}
if (typeof oh_mode === 'undefined') {
if (typeof oh_key === 'string') {
if (typeof osm_tag_defaults[oh_regex_key]['mode'] === 'number') {
oh_mode = osm_tag_defaults[oh_regex_key]['mode'];
} else {
oh_mode = 0;
}
} else {
oh_mode = 0;
}
} else if ([ 0, 1, 2 ].indexOf(oh_mode) === -1) {
throw t('conf param mode invalid', { 'given': oh_mode, 'allowed': '[ 0, 1, 2 ]' });
}
/* }}} */
/* }}} */
// Tokenize value and generate selector functions. {{{
if (typeof value !== 'string') {
throw t('no string');
}
if (/^(?:\s*;?)+$/.test(value)) {
throw t('nothing');
}
var parsing_warnings = []; // Elements are fed into function formatWarnErrorMessage(nrule, at, message)
var done_with_warnings = false; // The functions which returns warnings can be called multiple times.
var done_with_selector_reordering = false;
var done_with_selector_reordering_warnings = false;
var tokens = tokenize(value);
// console.log(JSON.stringify(tokens, null, ' '));
var prettified_value = '';
var week_stable = true;
var rules = [];
var rule_infos = {};
/* Not reliable because tokens != new_tokens */
// for (var nrule = 0; nrule < tokens.length; nrule++) {
// rule_infos[nrule] = {};
// }
var new_tokens = [];
for (var nrule = 0; nrule < tokens.length; nrule++) {
if (tokens[nrule][0].length === 0) {
// Rule does contain nothing useful e.g. second rule of '10:00-12:00;' (empty) which needs to be handled.
parsing_warnings.push([nrule, -1,
t('nothing useful')
+ (nrule === tokens.length - 1 && nrule > 0 && !tokens[nrule][1] ?
' ' + t('programmers joke') : '')
]);
continue;
}
var continue_at = 0;
var next_rule_is_additional = false;
do {
if (continue_at === tokens[nrule][0].length) break;
// Additional rule does contain nothing useful e.g. second rule of '10:00-12:00,' (empty) which needs to be handled.
var selectors = {
// Time selectors
time: [],
// Temporary array of selectors from time wrapped to the next day
wraptime: [],
// Date selectors
weekday: [],
holiday: [],
week: [],
month: [],
monthday: [],
year: [],
// Array with non-empty date selector types, with most optimal ordering
date: [],
fallback: tokens[nrule][1],
additional: continue_at ? true : false,
meaning: true,
unknown: false,
comment: undefined,
build_from_token_rule: undefined,
};
selectors.build_from_token_rule = [ nrule, continue_at, new_tokens.length ];
continue_at = parseGroup(tokens[nrule][0], continue_at, selectors, nrule);
if (typeof continue_at === 'object') {
continue_at = continue_at[0];
} else {
continue_at = 0;
}
// console.log('Current tokens: ' + JSON.stringify(tokens[nrule], null, ' '));
new_tokens.push(
[
tokens[nrule][0].slice(
selectors.build_from_token_rule[1],
continue_at === 0
? tokens[nrule][0].length
: continue_at
),
tokens[nrule][1],
tokens[nrule][2],
]
);
if (next_rule_is_additional && new_tokens.length > 1) {
// Move 'rule separator' from last token of last rule to first token of this rule.
new_tokens[new_tokens.length - 1][0].unshift(new_tokens[new_tokens.length - 2][0].pop());
}
next_rule_is_additional = continue_at === 0 ? false : true;
/* Optimal order of selectors for checking. */
var selector_elements = ['year', 'holiday', 'month', 'monthday', 'week', 'weekday'];
selector_elements.forEach(function (element) {
if (selectors[element].length > 0) {
selectors.date.push(selectors[element]);
selectors[element] = [];
}
});
// console.log('weekday: ' + JSON.stringify(selectors.weekday, null, '\t'));
rules.push(selectors);
/* This handles selectors with time ranges wrapping over midnight (e.g. 10:00-02:00).
* It generates wrappers for all selectors and creates a new rule.
*/
if (selectors.wraptime.length > 0) {
var wrapselectors = {
time: selectors.wraptime,
date: [],
meaning: selectors.meaning,
unknown: selectors.unknown,
comment: selectors.comment,
wrapped: true,
build_from_token_rule: selectors.build_from_token_rule,
};
for (var dselg = 0; dselg < selectors.date.length; dselg++) {
wrapselectors.date.push([]);
for (var dsel = 0; dsel < selectors.date[dselg].length; dsel++) {
wrapselectors.date[wrapselectors.date.length-1].push(
generateDateShifter(selectors.date[dselg][dsel], -msec_in_day)
);
}
}
rules.push(wrapselectors);
}
} while (continue_at);
}
// console.log(JSON.stringify(tokens, null, ' '));
// console.log(JSON.stringify(new_tokens, null, ' '));
/* }}} */
/* Helper functions {{{ */
/* Get regex string key from key osm_tag_defaults. {{{
*
* :param key: Tag key e.g. opening_hours:kitchen.
* :returns: Regex key from osm_tag_defaults e.g. opening_hours:.*
*/
function getRegexKeyForKeyFromOsmDefaults(key) {
var regex_key;
var exact_match = false;
Object.keys(osm_tag_defaults).forEach(function (osm_key) {
if (exact_match === true) {
return;
}
if (key === osm_key) { // Exact match.
regex_key = osm_key;
// We can't just return here as some old browsers
// don't interpret it as a final return (like a loop break)
exact_match = true;
} else if (new RegExp(osm_key).test(key)) {
regex_key = osm_key;
}
});
return regex_key;
}
/* }}} */
/* Check given element in optional_conf_parm. {{{
*
* :param key: Key of optional_conf_parm.
* :param expected_type: Expected `typeof()` the parameter.
* :returns: True if the expected type matches the given type.
*/
function checkOptionalConfParm(key, expected_type) {
if (typeof optional_conf_parm[key] === expected_type) {
return true;
} else if (typeof optional_conf_parm[key] !== 'undefined') {
throw t('conf param unkown type', { 'key': key, 'given': typeof(optional_conf_parm[key]), 'expected': expected_type });
}
return false;
}
/* }}} */
/* }}} */
/* Format warning or error message for the user. {{{
*
* :param nrule: Rule number starting with 0.
* :param at: Token position at which the issue occurred.
* :param message: Human readable string with the message.
* :param tokens_to_use: List of token objects.
* :returns: String with position of the warning or error marked for the user.
*/
function formatWarnErrorMessage(nrule, at, message, tokens_to_use) {
if (typeof tokens_to_use === 'undefined') {
tokens_to_use = tokens;
}
// console.log(`Called formatWarnErrorMessage: ${nrule}, ${at}, ${message}`);
// FIXME: Change to new_tokens.
if (typeof nrule === 'number') {
var pos = 0;
if (nrule === -1) { // Usage of rule index not required because we do have access to value.length.
pos = value.length - at;
} else { // Issue occurred at a later time, position in string needs to be reconstructed.
if (typeof tokens_to_use[nrule][0][at] === 'undefined') {
if (typeof tokens_to_use[nrule][0] && at === -1) {
pos = value.length;
if (typeof tokens_to_use[nrule+1] === 'object' && typeof tokens_to_use[nrule+1][2] === 'number') {
pos -= tokens_to_use[nrule+1][2];
} else if (typeof tokens_to_use[nrule][2] === 'number') {
pos -= tokens_to_use[nrule][2];
}
} else {
// Given position is invalid.
//
formatLibraryBugMessage('Bug in warning generation code which could not determine the exact position of the warning or error in value.');
pos = value.length;
if (typeof tokens_to_use[nrule][2] === 'number') {
// Fallback: Point to last token in the rule which caused the problem.
// Run real_test regularly to fix the problem before a user is confronted with it.
pos -= tokens_to_use[nrule][2];
console.warn('Last token for rule: ' + JSON.stringify(tokens_to_use[nrule]));
console.log(value.substring(0, pos) + ' <--- (' + message + ')');
console.log('\n');
} {
console.warn('tokens_to_use[nrule][2] is undefined. This is ok if nrule is the last rule.');
}
}
} else {
pos = value.length;
if (typeof tokens_to_use[nrule][0][at+1] === 'object') {
pos -= tokens_to_use[nrule][0][at+1][2];
} else if (typeof tokens_to_use[nrule][2] === 'number') {
pos -= tokens_to_use[nrule][2];
}
}
}
return value.substring(0, pos) + ' <--- (' + message + ')';
} else if (typeof nrule === 'string') {
return nrule.substring(0, at) + ' <--- (' + message + ')';
}
}
/* }}} */
/* Format internal library error message. {{{
*
* :param message: Human readable string with the error message.
* :param text_template: Message template defined in the `lang` variable to use for the error message. Defaults to 'library bug'.
* :returns: Error message for the user.
*/
function formatLibraryBugMessage(message, text_template) {
if (typeof message === 'undefined') {
message = '';
} else {
message = ' ' + message;
}
if (typeof text_template !== 'string') {
text_template = 'library bug';
}
message = t(text_template, { 'value': value, 'url': repository_url, 'message': message });
console.error(message);
return message;
} /* }}} */
/* Tokenize input stream {{{
*
* :param value: Raw opening_hours value.
* :returns: Tokenized list object. Complex structure. Check the
* internal documentation in the docs/ directory for details.
*/
function tokenize(value) {
var all_tokens = [];
var curr_rule_tokens = [];
var last_rule_fallback_terminated = false;
while (value !== '') {
/* Ordered after likelihood of input for performance reasons.
* Also, error tolerance is supposed to happen at the end.
*/
// console.log("Parsing value: " + value);
var tmp = value.match(/^([a-z]{2,})\b((?:[.]| before| after)?)/i);
var token_from_map = undefined;
if (tmp && tmp[2] === '') {
token_from_map = string_to_token_map[tmp[1].toLowerCase()];
}
if (typeof token_from_map === 'object') {
curr_rule_tokens.push(token_from_map.concat([value.length]));
value = value.substr(tmp[1].length);
} else if (tmp = value.match(/^\s+/)) {
// whitespace is ignored
value = value.substr(tmp[0].length);
} else if (tmp = value.match(/^24\/7/)) {
// Reserved keyword.
curr_rule_tokens.push([tmp[0], tmp[0], value.length ]);
value = value.substr(tmp[0].length);
} else if (/^;/.test(value)) {
// semicolon terminates rule.
// Next token belong to a new rule.
all_tokens.push([ curr_rule_tokens, last_rule_fallback_terminated, value.length ]);
value = value.substr(1);
curr_rule_tokens = [];
last_rule_fallback_terminated = false;
} else if (/^[:.]/.test(value)) {
// Time separator (timesep).
if (value[0] === '.' && !done_with_warnings) {
parsing_warnings.push([ -1, value.length - 1, t('hour min separator')]);
}
curr_rule_tokens.push([ ':', 'timesep', value.length ]);
value = value.substr(1);
} else if (tmp = value.match(/^(?:PH|SH)/i)) {
// special day name (holidays)
curr_rule_tokens.push([tmp[0].toUpperCase(), 'holiday', value.length ]);
value = value.substr(2);
} else if (tmp = value.match(/^[°\u2070-\u209F\u00B2\u00B3\u00B9]{1,2}/)) {
var unicode_code_point_to_digit = {
176: 0,
0x2070: 0,
185: 1,
178: 2,
179: 3,
}
var regular_number = tmp[0].split('').map(function (ch) {
var code_point = ch.charCodeAt(0);
if (typeof unicode_code_point_to_digit[code_point] === 'number') {
return unicode_code_point_to_digit[code_point];
} else if (0x2074 <= code_point && code_point <= 0x2079) {
return code_point - 0x2070;
} else if (0x2080 <= code_point && code_point <= 0x2089) {
return code_point - 0x2080;
}
}).join('');
var ok = '';
if (curr_rule_tokens.length > 0 && matchTokens(curr_rule_tokens, curr_rule_tokens.length-1, 'number')) {
ok += ':';
}
ok += regular_number;
if (!done_with_warnings) {
for (var i = 0; i <= tmp[0].length; i++) {
if (value.charCodeAt(i) == 176) {
parsing_warnings.push([ -1, value.length - (1 + i),
t('rant degree sign used for zero')]);
}
}
parsing_warnings.push([ -1, value.length - tmp[0].length,
t('please use ok for ko', {'ko': tmp[0], 'ok': ok})]);
}
value = ok + value.substr(tmp[0].length);
} else if (tmp = value.match(/^(&|_|→|–|−|—|ー|=|·|öffnungszeit(?:en)?:?|opening_hours\s*=|\?|~|~|:|always (?:open|closed)|24x7|24 hours 7 days a week|24 hours|7 ?days(?:(?: a |\/)week)?|7j?\/7|all days?|every day|(?:bis|till?|-|–)? ?(?:open ?end|late)|(?:(?:one )?day (?:before|after) )?(?:school|public) holidays?|days?\b|до|рм|ам|jours fériés|on work days?|sonntags?|(?:nur |an )?sonn-?(?:(?: und |\/)feiertag(?:s|en?)?)?|(?:an )?feiertag(?:s|en?)?|(?:nach|on|by) (?:appointments?|vereinbarung|absprache)|p\.m\.|a\.m\.|[_a-zäößàáéøčěíúýřПнВсо]+\b|à|á|mo|tu|we|th|fr|sa|su|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(\.?)/i)) {
/* Handle all remaining words and specific other characters with error tolerance.
*
* à|á: Word boundary does not work with Unicode chars: 'test à test'.match(/\bà\b/i)
* https://stackoverflow.com/questions/10590098/javascript-regexp-word-boundaries-unicode-characters
* Order in the regular expression capturing group is important in some cases.
*
* mo|tu|we|th|fr|sa|su|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec: Prefer defended keywords
* if used in cases like 'mo12:00-14:00' (when keyword is followed by number).
*/
var correct_val = returnCorrectWordOrToken(tmp[1].toLowerCase(), value.length);
// console.log('Error tolerance for string "' + tmp[1] + '" returned "' + correct_val + '".');
if (typeof correct_val === 'object') {
curr_rule_tokens.push([ correct_val[0], correct_val[1], value.length ]);
value = value.substr(tmp[0].length);
} else if (typeof correct_val === 'string') {
if (correct_val === 'am' || correct_val === 'pm') {
var hours_token_at = curr_rule_tokens.length - 1;
var hours_token;
if (hours_token_at >= 0) {
if (hours_token_at -2 >= 0 &&
matchTokens(
curr_rule_tokens, hours_token_at - 2,
'number', 'timesep', 'number'
)
) {
hours_token_at -= 2;
hours_token = curr_rule_tokens[hours_token_at];
} else if (matchTokens(curr_rule_tokens, hours_token_at, 'number')) {
hours_token = curr_rule_tokens[hours_token_at];
}
if (typeof hours_token === 'object') {
if (correct_val === 'pm' && hours_token[0] < 12) {
hours_token[0] += 12;
}
if (correct_val === 'am' && hours_token[0] === 12) {
hours_token[0] = 0;
}
curr_rule_tokens[hours_token_at] = hours_token;
}
}
correct_val = '';
}
var correct_tokens = tokenize(correct_val)[0];
if (correct_tokens[1] === true) { // last_rule_fallback_terminated
throw formatLibraryBugMessage();
}
for (var i = 0; i < correct_tokens[0].length; i++) {
curr_rule_tokens.push([correct_tokens[0][i][0], correct_tokens[0][i][1], value.length]);
// value.length - tmp[0].length does not have the desired effect for all test cases.
}
value = value.substr(tmp[0].length);
// value = correct_val + value.substr(tmp[0].length);
// Does not work because it would generate the wrong length for formatWarnErrorMessage.
} else {
// No correction available. Insert as single character token and let the parser handle the error.
curr_rule_tokens.push([value[0].toLowerCase(), value[0].toLowerCase(), value.length - 1 ]);
value = value.substr(1);
}
if (typeof tmp[2] === 'string' && tmp[2] !== '' && !done_with_warnings) {
parsing_warnings.push([ -1, value.length, t('omit ko', {'ko': tmp[2]})]);
}
} else if (tmp = value.match(/^(\d+)(?:([.])([^\d]))?/)) {
// number
if (Number(tmp[1]) > 1900) { // Assumed to be a year number.
curr_rule_tokens.push([Number(tmp[1]), 'year', value.length ]);
if (Number(tmp[1]) >= 2100) // Probably an error
parsing_warnings.push([ -1, value.length - 1,
t('interpreted as year', {number: Number(tmp[1])})
]);
} else {
curr_rule_tokens.push([Number(tmp[1]), 'number', value.length ]);
}
value = value.substr(tmp[1].length + (typeof tmp[2] === 'string' ? tmp[2].length : 0));
if (typeof tmp[2] === 'string' && tmp[2] !== '' && !done_with_warnings) {
parsing_warnings.push([ -1, value.length, t('omit ko', {'ko': tmp[2]})]);
}
} else if (/^\|\|/.test(value)) {
// || terminates rule.
// Next token belong to a fallback rule.
if (curr_rule_tokens.length === 0) {
throw formatWarnErrorMessage(-1, value.length - 2, t('rule before fallback empty'));
}
all_tokens.push([ curr_rule_tokens, last_rule_fallback_terminated, value.length ]);
curr_rule_tokens = [];
// curr_rule_tokens = [ [ '||', 'rule separator', value.length ] ];
// FIXME: Use this. Unknown bug needs to be solved in the process.
value = value.substr(2);
last_rule_fallback_terminated = true;
} else if (tmp = value.match(/^"([^"]+)"/)) {
// Comment following the specification.
// Any character is allowed inside the comment except " itself.
curr_rule_tokens.push([tmp[1], 'comment', value.length ]);
value = value.substr(tmp[0].length);
} else if (tmp = value.match(/^(["'„“‚‘’«「『])([^"'“”‘’»」』;|]*)(["'”“‘’»」』])/)) {
// Comments with error tolerance.
// The comments still have to be somewhat correct meaning
// the start and end quote signs used have to be
// appropriate. So “testing„ will not match as it is not a
// quote but rather something unknown which the user should
// fix first.
// console.log('Matched: ' + JSON.stringify(tmp));
for (var pos = 1; pos <= 3; pos += 2) {
// console.log('Pos: ' + pos + ', substring: ' + tmp[pos]);
var correct_val = returnCorrectWordOrToken(tmp[pos],
value.length - (pos === 3 ? tmp[1].length + tmp[2].length : 0)
);
if (typeof correct_val !== 'string' && tmp[pos] !== '"') {
throw formatLibraryBugMessage(
'A character for error tolerance was allowed in the regular expression'
+ ' but is not covered by word_error_correction'
+ ' which is needed to format a proper message for the user.'
);
}
}
curr_rule_tokens.push([tmp[2], 'comment', value.length ]);
value = value.substr(tmp[0].length);
} else if (/^(?:␣|\s)/.test(value)) {
// Using "␣" as space is not expected to be a normal
// mistake. Just ignore it to make using taginfo easier.
value = value.substr(1);
} else {
// other single-character tokens
curr_rule_tokens.push([value[0].toLowerCase(), value[0].toLowerCase(), value.length ]);
value = value.substr(1);
}
}
all_tokens.push([ curr_rule_tokens, last_rule_fallback_terminated ]);
return all_tokens;
}
/* }}} */
/* error correction/tolerance function {{{
* Go through word_error_correction hash and get correct value back.
*
* :param word: Wrong word or character.
* :param value_length: Current value_length (used for warnings).
* :returns:
* * (valid) opening_hours sub string.
* * object with [ internal_value, token_name ] if value is correct.
* * undefined if word could not be found (and thus is not corrected).
*/
function returnCorrectWordOrToken(word, value_length) {
var correctWordOrToken;
var token_from_map = string_to_token_map[word];
if (typeof token_from_map === 'object') {
return token_from_map;
}
Object.keys(word_error_correction).forEach(function (comment) {
if (correctWordOrToken) {
return;
}
Object.keys(word_error_correction[comment]).forEach(function (old_val) {
if (correctWordOrToken) {
return;
}
if (new RegExp('^' + old_val + '$').test(word)) {
var val = word_error_correction[comment][old_val];
// Replace wrong words or characters with correct ones.
// This will return a string which is then being tokenized.
if (!done_with_warnings) {
parsing_warnings.push([
-1,
value_length - word.length,
t(comment, {'ko': word, 'ok': val}),
]);
}
correctWordOrToken = val;
}
});
});
return correctWordOrToken;
}
/* }}} */
/* return warnings as list {{{
*
* :param it: Iterator object if available (optional).
* :returns: Warnings as list with one warning per element.
*/
function getWarnings(it) {
if (warnings_severity < 4) {
return [];
}
if (!done_with_warnings && typeof it === 'object') {
/* getWarnings was called in a state without critical errors.
* We can do extended tests.
*/
/* Place all tests in this function if an additional (high
* level) test is added and this does not require to rewrite
* big parts of (sub) selector parsers only to get the
* position. If that is the case, then rather place the test
* code in the (sub) selector parser function directly.
*/
var wide_range_selector_order = [ 'year', 'month', 'week', 'holiday' ];
var small_range_selector_order = [ 'weekday', 'time', '24/7', 'state', 'comment'];
// How many times was a selector_type used per rule? {{{
var used_selectors = [];
var used_selectors_types_array = [];
var has_token = {};
for (var nrule = 0; nrule < new_tokens.length; nrule++) {
if (new_tokens[nrule][0].length === 0) continue;
// Rule does contain nothing useful e.g. second rule of '10:00-12:00;' (empty) which needs to be handled.
var selector_start_end_type = [ 0, 0, undefined ];
// console.log(new_tokens[nrule][0]);
used_selectors[nrule] = {};
used_selectors_types_array[nrule] = [];
do {
selector_start_end_type = getSelectorRange(new_tokens[nrule][0], selector_start_end_type[1]);
// console.log(selector_start_end_type, new_tokens[nrule][0].length);
for (var token_pos = 0; token_pos <= selector_start_end_type[1]; token_pos++) {
if (typeof new_tokens[nrule][0][token_pos] === 'object' && new_tokens[nrule][0][token_pos][0] === 'PH') {
has_token['PH'] = true;
}
}
if (selector_start_end_type[0] === selector_start_end_type[1] &&
new_tokens[nrule][0][selector_start_end_type[0]][0] === '24/7'
) {
has_token['24/7'] = true;
}
if (typeof used_selectors[nrule][selector_start_end_type[2]] !== 'object') {
used_selectors[nrule][selector_start_end_type[2]] = [ selector_start_end_type[1] ];
} else {
used_selectors[nrule][selector_start_end_type[2]].push(selector_start_end_type[1]);
}
used_selectors_types_array[nrule].push(selector_start_end_type[2]);
selector_start_end_type[1]++;
} while (selector_start_end_type[1] < new_tokens[nrule][0].length);
}
// console.log('used_selectors: ' + JSON.stringify(used_selectors, null, ' '));
// console.log('used_selectors_types_array: ' + JSON.stringify(used_selectors_types_array, null, ' '));
/* }}} */
for (var nrule = 0; nrule < used_selectors.length; nrule++) {
/* Check if more than one not connected selector of the same type is used in one rule {{{ */
Object.keys(used_selectors[nrule]).forEach(function (selector_type) {
// console.log(selector_type + ' use at: ' + used_selectors[nrule][selector_type].length);
if (used_selectors[nrule][selector_type].length > 1) {
parsing_warnings.push([nrule, used_selectors[nrule][selector_type][used_selectors[nrule][selector_type].length - 1],
t('use multi', {
'count': used_selectors[nrule][selector_type].length,
'part2': (
/^(?:comment|state)/.test(selector_type) ?
t('selector multi 2a', {'what': (selector_type === 'state' ? t('selector state'): t('comments'))})
:
t('selector multi 2b', {'what': t(selector_type + (/^(?:month|weekday)$/.test(selector_type) ? 's' : ' ranges'))})
)
})]
);
done_with_selector_reordering = true; // Correcting the selector order makes no sense if this kind of issue exists.
}
});
/* }}} */
/* Check if change default state rule is not the first rule {{{ */
if ( typeof used_selectors[nrule].state === 'object'
&& Object.keys(used_selectors[nrule]).length === 1
) {
if (nrule !== 0) {
parsing_warnings.push([nrule, new_tokens[nrule][0].length - 1, t('default state')]);
}
/* }}} */
/* Check if a rule (with state open) has no time selector {{{ */
} else if (typeof used_selectors[nrule].time === 'undefined') {
if ( ( typeof used_selectors[nrule].state === 'object'
&& new_tokens[nrule][0][used_selectors[nrule].state[0]][0] === 'open'
&& typeof used_selectors[nrule].comment === 'undefined'
) || ( typeof used_selectors[nrule].comment === 'undefined'
&& typeof used_selectors[nrule].state === 'undefined'
) &&
typeof used_selectors[nrule]['24/7'] === 'undefined'
) {
parsing_warnings.push([nrule, new_tokens[nrule][0].length - 1, t('vague')]);
}
}
/* }}} */
/* Check if empty comment was given {{{ */
if (typeof used_selectors[nrule].comment === 'object'
&& new_tokens[nrule][0][used_selectors[nrule].comment[0]][0].length === 0
) {
parsing_warnings.push([nrule, used_selectors[nrule].comment[0], t('empty comment')]);
}
/* }}} */
/* Check for valid use of <separator_for_readability> {{{ */
for (var i = 0; i < used_selectors_types_array[nrule].length - 1; i++) {
var selector_type = used_selectors_types_array[nrule][i];
var next_selector_type = used_selectors_types_array[nrule][i+1];
if ( ( wide_range_selector_order.indexOf(selector_type) !== -1
&& wide_range_selector_order.indexOf(next_selector_type) !== -1
) || ( small_range_selector_order.indexOf(selector_type) !== -1
&& small_range_selector_order.indexOf(next_selector_type) !== -1)
) {
if (new_tokens[nrule][0][used_selectors[nrule][selector_type][0]][0] === ':') {
parsing_warnings.push([nrule, used_selectors[nrule][selector_type][0],
t('separator_for_readability')
]);
}
}
}
/* }}} */
/* Check for missing use of <additional_rule_separator> for time wrapping midnight {{{ */
if (typeof rule_infos[nrule] === 'object'
&& typeof rule_infos[nrule]['time_wraps_over_midnight'] === 'boolean'
&& rule_infos[nrule]['time_wraps_over_midnight'] === true
&& typeof used_selectors[nrule+1] === 'object'
&& typeof used_selectors[nrule+1]['rule separator'] === 'undefined' // Not an additional rule
&& new_tokens[nrule+1][1] === false // Not a fallback rule
) {
var rules_too_complex = [ nrule, nrule+1 ].map(function (nrule){
for (var i = 0; i < wide_range_selector_order.length - 1; i++) {
if (typeof used_selectors[nrule][wide_range_selector_order[i]] === 'object') {
return true;
}
}
return false;
});
var rules_too_complex_count = rules_too_complex.filter(function (el){ return el; }).length;
var next_rule_selects_next_day = false;
if (
typeof rule_infos[nrule] === 'object'
&& typeof rule_infos[nrule] === 'object'
&& typeof rule_infos[nrule]['week_days'] === 'object'
&& typeof rule_infos[nrule+1] === 'object'
&& typeof rule_infos[nrule+1]['week_days'] === 'object'
) {
for (var i = 0; i < rule_infos[nrule]['week_days'].length; i++) {
var week_day = rule_infos[nrule]['week_days'][i];
// console.log(rule_infos[nrule+1]['week_days']);
// console.log(week_day);
if (rule_infos[nrule+1]['week_days'].indexOf(week_day === 6 ? 0 : week_day+1) !== -1) {
next_rule_selects_next_day = true;
break;
}
}
} else {
next_rule_selects_next_day = true;
}
// console.log(rule_infos);
// console.log(next_rule_selects_next_day);
if (rules_too_complex_count < 2 && next_rule_selects_next_day) {
parsing_warnings.push([nrule+1, new_tokens[nrule+1][0].length - 1,
t('additional_rule_separator not used after time wrapping midnight'),
new_tokens
]);
}
}
/* }}} */
/* Check if rule with closed|off modifier is additional {{{ */
if (typeof new_tokens[nrule][0][0] === 'object'
&& new_tokens[nrule][0][0][0] === ','
&& new_tokens[nrule][0][0][1] === 'rule separator'
&& typeof used_selectors[nrule].state === 'object'
&& (
new_tokens[nrule][0][used_selectors[nrule].state[0]][0] === 'closed'
|| new_tokens[nrule][0][used_selectors[nrule].state[0]][0] === 'off'
)
) {
parsing_warnings.push([nrule, new_tokens[nrule][0].length - 1,
t('additional rule which evaluates to closed'),
new_tokens
]);
}
/* }}} */
}
/* Check if 24/7 is used and it does not mean 24/7 because there are other rules {{{ */
var has_advanced = it.advance();