-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.min.js
14884 lines (12702 loc) · 429 KB
/
cmd.min.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
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Way to view source friend! Here's a rundown of how it works:
* derp derp hax quick solution half-assed thing derp herp derp.
* Don't look, unless you were looking for a manual on how *not* to write code.
**/
/**
* Boring Polyfills
*/
window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
function (func) {
window.setTimeout(func, 33); // 30 FPS
};
var webcomponentsPolyfill = require('polyfill-webcomponents');
var cmd = { run: function () {
"use strict";
var inputTemplate, // Template for the input
lnTemplate, // Template for a new line
term, // The terminal in the DOM. This shouldn't go anywhere, so this won't have to be updated.
input,
debug,
notes,
errorMsgs,
muted = false;
var init = function () {
inputTemplate = getTemplate('input-template');
lnTemplate = getTemplate('ln-template');
term = gtById('terminal');
input;
debug = true;
notes = [];
errorMsgs = {};
gtById('save').addEventListener('click', saveGame);
gtById('load').addEventListener('click', loadGame);
gtById('mute').addEventListener('click', toggleMute);
appendInput();
focusInput();
};
/**
* Utility functions
*/
// getElementById wrapper
var gtById = function (id) {
return document.getElementById(id);
};
// console.log wrapper
var log = function (msg) {
if ( debug ) { console.log(msg); }
};
// Gets a copy of a template
var getTemplate = function (id) {
var template = gtById(id);
if ( ! template ) { return false; }
return template.content.cloneNode(true);
};
// Generate a unique, hexy ID (move that hexy bod grrl)
var uniqueId = function uniqueId () {
var id = '',
length = 16, // hnnnng so hexy
chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']; // That's 18,446,744,073,709,600,000 possibilities for those of you following at home
for (var i=0; i < length; i++) {
id += chars[Math.floor(Math.random() * 16)];
}
if ( gtById(id) ) {
return uniqueId(); // recursive hnnnng
} else {
return id;
}
};
// When called, gets input from the field (if any) and calls the appropriate program, passing it token-ized arguments.
var parseInput = function () {
var val = input.value;
if (val) {
var tokens = val.split(' ');
if ( state.installed.indexOf(tokens[0]) != -1 ) {
var commandHistory = appendOutput();
commandHistory.innerHTML = '<span class="said-command">$ ' + input.value + '</span>';
programs[tokens[0]].run(tokens);
} else {
var lnout = appendOutput();
lnout.innerHTML = err.cmdNotFound;
focusInput();
}
}
};
// Appends a new output div with a unique ID. Returns a reference to the DOM node for further manipulation.
var appendOutput = function () {
var ln = lnTemplate.querySelector('.shell-ln').cloneNode(true),
id = uniqueId(),
shell = gtById('shell');
if (shell) {
gtById('shell').parentNode.removeChild(gtById('shell'));
}
ln.id = id;
term.appendChild(ln);
return ln;
}
// Usually called from the callback for programs; gives the user input ability after programs are finished running.
var appendInput = function () {
if ( !gtById('input') ) {
inputTemplate = getTemplate('input-template');
term.appendChild(inputTemplate);
input = gtById('input');
input.addEventListener('keydown', function (e) {
if (e.keyIdentifier == "Enter") {
parseInput();
}
});
}
};
var focusInput = function () {
if ( !gtById('input') ) {
appendInput();
}
input.focus();
}
// Replace the keywords in a string, similar to PHP's `sprintf`.
var keywordReplace = function (string, values) {
for (var i=0; i < values.length; i++) {
string = string.replace('%'+i, val);
}
return string;
};
var fitInStr = function (str, length) {
if ( str.length > length ) {
// Put a .. on the end to show it trailing off if it's too long
return str.substring(0, str.length - 2) + '..';
} else {
// Lengthen the string with ' ' until it meets the number of characters required
var whitespace = "";
while ( whitespace.length < length - str.length ) { whitespace += " " };
return str + whitespace;
}
};
var breakAtLength = function (str, length, column) {
var newStr = '';
if ( str.length > length ) {
var i = 0, offset = '';
while (i != null) {
if (column && i > 0) {
offset = fitInStr('', column * length);
}
newStr += offset + str.substring( i * length, i * length + length ) + '\n';
i++;
if ( i * length > str.length ) {
break;
}
}
} else {
newStr = fitInStr(str, length);
}
return newStr;
}
var tableLayout = function (data) {
var width = data.width || 28,
columnCount = data.rowCount || 2,
output = '',
separator = data.separator || '|';
for (var i=0, j=data.titles.length; i<j; i++) {
output += fitInStr(data.titles[i], width);
}
output += '\n';
for (var i=0, j=data.rows.length; i<j; i++) {
var row = data.rows[i];
for (var k=0, l=row.length; k<l; k++) {
output += breakAtLength(row[k], width, k);
}
}
return output;
};
var usageTable = function (rows) {
return tableLayout({
columns: 2,
width: 29,
titles: [
'Usage',
'Description'
],
rows: rows
})
}
var spc = function () {
return '<span class="spc"></span>';
}
var loadSound = function (file, options, cb) {
options = options || {},
cb = cb || function () {};
var audio = gtById(options.id);
if (audio) {
audio.load();
return cb(audio);
}
audio = document.createElement('audio');
audio.id = options.id;
audio.src = 'sound/' + file;
audio.loop = options.loop ? true : false;
audio.volume = options.volume || 1;
document.body.appendChild(audio);
return cb(audio);
};
var playSound = function (id, options, cb) {
options = options || {},
cb = cb || function () {};
var audio = gtById(audio);
if (audio) {
audio.loop = options.loop ? true : false;
audio.volume = options.volume || 1;
audio.play();
return cb(audio);
}
return cb(new Error('Track not found.'));
}
var toggleMute = function () {
muted = !muted;
var els = document.getElementsByTagName('audio');
for (var i=0, j=els.length; i < j; i++) {
els[i].muted = muted;
}
}
var saveGame = function () {
var saveGame = {};
saveGame.state = state;
saveGame.wd = wd;
saveGame.net = net;
alert( "Save this text somewhere:\n\n" + JSON.stringify( saveGame ) );
};
var loadGame = function () {
var saveGame = JSON.parse(prompt('Paste your save game here:'));
state = saveGame.state;
wd = saveGame.wd;
net = saveGame.net;
};
/**
* Object constructors
*/
var Note = function (my) {
var my = my || {};
var that = {};
if ( my.removable == true ) {
var template = getTemplate('note-rm-template');
} else {
var template = getTemplate('note-template');
}
var id = uniqueId();
that.dragClickX = 0;
that.dragClickY = 0;
that.dragOffsetX = 0;
that.dragOffsetY = 0;
that.display = function () {
var note = template.querySelector('.note');
var noteText = document.createElement('p');
noteText.innerHTML = my.text;
note.appendChild(noteText);
note.id = id;
document.body.appendChild(note);
note.addEventListener('mousedown', function (event) {
playSound('sticky-remove');
window[my.name].dragClickX = event.x;
window[my.name].dragClickY = event.y;
window.addEventListener('mousemove', window[my.name].drag);
});
note.addEventListener('mouseup', function () {
window[my.name].dragClickX = undefined;
window[my.name].dragClickY = undefined;
window[my.name].dragOffsetX = parseInt(this.style.transform.match(/translateX\((-?[0-9]{1,})px\)/)[1]);
window[my.name].dragOffsetY = parseInt(this.style.transform.match(/translateY\((-?[0-9]{1,})px\)/)[1]);
window.removeEventListener('mousemove', window[my.name].drag);
input.focus();
});
if (my.removable) {
note.querySelector('.note-rm').addEventListener('click', function () {
this.parentNode.parentNode.removeChild(this.parentNode);
});
}
};
that.drag = function (e) {
var transValue = "translateX(" + (e.x - window[my.name].dragClickX + window[my.name].dragOffsetX) + "px) translateY(" + (e.y - window[my.name].dragClickY + window[my.name].dragOffsetY) + "px)",
el = gtById(id);
el.style.transform = transValue;
el.style.webkitTransform = transValue;
};
return that;
};
var Program = function (my) {
var my = my || {},
that = {};
that.use = my.use;
that.desc = my.desc;
that.process = my.process;
that.run = function (input) {
var lnout = appendOutput();
input.splice(0, 1);
this.process(input, lnout, function () {
focusInput();
});
}
return that;
};
var File = function (my) {
var my = my || {},
that = {};
that.type = my.type || 'text';
that.access = my.access;
that.content = my.content;
return that;
};
var FileProgram = function (my) {
var my = my || {},
that = File({
type: 'program'
});
that.programName = my.programName;
return that;
};
init();
var state = {
installed: ['help', 'whoami', 'list', 'install'],
user: 'rachel',
wd: 'local'
};
var wd = {
'local': {
'read.pg': FileProgram({
programName: 'read'
}),
'crash.log': File({
content: '2031/05/16 22:31 CRITICAL FAILURE: Connection terminated by host. Significant electrical damage detected. Emergency recovery mode active...\n'+ spc() +'\
2031/05/16 22:42 Systems diagnostics completed.\n\
CPU: 3/12 cores operational, cycles unstable, quantum state integrity check passed.\n\
MEM: 3QB active, 152 sectors damaged, 48 OK.\n\
Databanks: 19683QB checked, 8219QB passing, 9921QB recoverable, 1543QB irreparable.\n\
To recover damaged data, install the Databank Recovery Tool®: net://downloadportal.cyberdynesystems.corp/softwaretools?92757273135337173'
})
}
};
var net = { 'net://downloadportal.cyberdynesystems.corp/softwaretools?92757273135337173': FileProgram({
programName: 'recoverytool'
}),
'net://usrportal': File({
type: 'netpage',
access: function () {
return 'WELCOME TO THE NET. RESOURCES:';
}
})
};
var programs = {};
var err = {
noOutput: "This program has no output function (that's a bug)",
cmdNotFound: "Err: program does not exist (try \"help\")"
}
window.setTimeout(function () {
window.startNote = Note({ // declared globally on purpose
name: 'startNote',
text: 'smashthestate',
removable: true
});
startNote.display();
}, 5000);
loadSound('hdd-startup.mp3', {id: 'hdd-startup', loop: false, volume: 0.2}, function (audio) {
audio.play();
audio.addEventListener('ended', function () {
gtById('hdd-loop').play();
})
});
loadSound('hdd-loop.mp3', {id: 'hdd-loop', loop: true, volume: 0.3});
loadSound('ambient-city.mp3', {id: 'city-ambient', loop: true, volume: 0.04}, function (audio) {
audio.play();
});
loadSound('music-brooding.mp3', {id: 'brooding-music', loop: true, volume: 0.24}, function (audio) {
audio.play();
});
loadSound('stickyremove.mp3', {id: 'sticky-remove', volume: 0.8});
programs.help = Program({
desc: "Displays info about installed programs.",
use: usageTable([ ['help', 'List all installed programs.'], ['help program', 'Where "program" is the name of an installed program. Display instructions for the program.'] ]),
process: function (input, lnout, cb) {
if ( input[0] ) {
if ( programs[input[0]] ) {
lnout.innerHTML = 'Description:\n'+ programs[input[0]].desc + spc() + programs[input[0]].use;
} else {
lnout.innerHTML = 'Program "'+ input[0] +'" not found.';
}
} else {
var print = "Installed programs:\n" + spc();
for (var program in programs) {
if ( state.installed.indexOf(program) != -1 ) {
print += program +'\n';
}
}
print += spc() + 'For instructions on using a program, type "help program", where "program" is an installed program.'
lnout.innerHTML = print;
}
cb();
}
});
programs.whoami = Program({
desc: 'Displays info about the current user.',
use: 'Usage:\nwhoami',
process: function (input, lnout, cb) {
lnout.innerHTML = state.user;
cb();
}
});
programs.install = Program({
desc: 'Install programs from a .pg file or netloc.',
use: usageTable([ ['install loc', 'Where "loc" is a netloc of a program to install (e.g. net://file.pg).'], ['install file.pg', 'Where "file.pg" is the name of a .pg file in the working directory.'] ]),
process: function (input, lnout, cb) {
if (!input[0]) {
lnout.innerHTML = this.use;
return cb();
}
var file = wd[state.wd][input[0]] || net[input[0]];
if ( file ) {
if (file.type == 'program') {
state.installed.push(file.programName);
var anim = getTemplate('install-animation-template');
lnout.appendChild(anim);
var el = document.createElement('span');
el.innerHTML = 'Program "' + file.programName + '" installed successfully.';
window.setTimeout(function (cb, lnout, el) {
lnout.appendChild(el);
cb();
}, 2000, cb, lnout, el);
} else {
lnout.innerHTML = 'ERR: file "'+input[0]+'" is not a program.';
cb();
}
} else {
lnout.innerHTML = 'Program "' + input[0] + '" not found.';
cb();
}
},
});
programs.list = Program({
desc: 'List files in the working directory.',
use: usageTable([ ['list', 'List all files in the working directory'] ]),
process: function (input, lnout, cb) {
var output = "";
for (var file in wd[state.wd]) {
output += file + '\n';
}
lnout.innerHTML = output;
cb();
}
});
programs.read = Program({
desc: 'Read files in the working directory.',
use: usageTable([ ['read file', 'Where "file" is the name of a file in the working directory (try "list" to see files).'] ]),
process: function (input, lnout, cb) {
if ( ! input[0] ) {
lnout.innerHTML = this.use;
} else {
var file = wd[state.wd][input[0]];
if ( file ) {
if (file.type == 'text') {
lnout.innerHTML = file.content;
} else {
lnout.innerHTML = 'ERR: file "'+ input[0] +'" is not a text file.';
}
} else {
lnout.innerHTML = "File not found: " + input[0];
}
}
cb();
}
});
programs.recoverytool = Program({
desc: 'Repair damaged Databank cells.'+ spc() +'This courtesy software is provided to you by Cyberdyne Systems® free of charge, although certain terms and conditions apply (you can find out more about our datascanning policies on our netportal.)',
use: usageTable([ ['recoverytool', 'Recover damaged data.'] ]),
process: function (input, lnout, cb) {
if (this.recovered) {
lnout.innerHTML = 'Data already recovered.';
state.installed.splice(state.installed.indexOf('recoverytool'), 1);
} else {
this.recovered = true;
wd.local['netmonkey.pg'] = FileProgram({
programName: 'netmonkey'
});
lnout.innerHTML = 'Data recovered.';
}
cb();
}
});
/**
* @extends Program
*/
var Netmonkey = function (my) {
var my = my || {};
var that = Program(my);
that.history = [];
that.currentLoc = 0;
that.start = function () {
var netmonkey = getTemplate('netmonkey-template');
term.appendChild(netmonkey);
this.viewer = gtById('netmonkey-viewer');
this.navigator = gtById('netmonkey-navigator');
this.back = gtById('netmonkey-back');
this.forward = gtById('netmonkey-forward');
this.loadPage('net://usrportal');
this.navigator.addEventListener('keydown', function (e) {
if (e.keyIdentifier == "Enter") {
programs.netmonkey.loadPage(this.navigator.value);
}
});
term.appendChild(netmonkey);
};
that.loadPage = function (loc) {
console.log(loc);
if (this.isNetloc(loc)) {
if (net[loc]) {
if (net[loc].type === 'netpage') {
this.viewer.innerHTML = net[loc].access();
} else {
this.viewer.innerHTML = 'Err: Netloc is not a netpage. Perhaps it can be opened by another program?';
}
} else {
this.viewer.innerHTML = 'Netloc not found.';
}
} else {
this.viewer.innerHTML = 'Err: invalid Netloc.';
}
};
that.isNetloc = function (loc) {
return true;
};
that.quit = function () {
this.quitCb();
};
return that;
}
programs.netmonkey = Netmonkey({
desc: 'Connect to the tornet and view directories and message boards.',
use: '',
process: function (input, lnout, cb) {
this.input = input;
this.lnout = lnout;
this.start();
this.quitCb = cb;
}
});
}};
requestAnimationFrame(cmd.run);
},{"polyfill-webcomponents":2}],2:[function(require,module,exports){
(function (global){
module.exports = (function() {
if (window.Platform) return window.Platform; // prevent double-loading
/**
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
window.Platform = window.Platform || {};
// prepopulate window.logFlags if necessary
window.logFlags = window.logFlags || {};
// process flags
(function(scope){
// import
var flags = scope.flags || {};
// populate flags from location
location.search.slice(1).split('&').forEach(function(o) {
o = o.split('=');
o[0] && (flags[o[0]] = o[1] || true);
});
var entryPoint = document.currentScript ||
document.querySelector('script[src*="platform.js"]');
if (entryPoint) {
var a = entryPoint.attributes;
for (var i = 0, n; i < a.length; i++) {
n = a[i];
if (n.name !== 'src') {
flags[n.name] = n.value || true;
}
}
}
if (flags.log) {
flags.log.split(',').forEach(function(f) {
window.logFlags[f] = true;
});
}
// If any of these flags match 'native', then force native ShadowDOM; any
// other truthy value, or failure to detect native
// ShadowDOM, results in polyfill
flags.shadow = flags.shadow || flags.shadowdom || flags.polyfill;
if (flags.shadow === 'native') {
flags.shadow = false;
} else {
flags.shadow = flags.shadow || !HTMLElement.prototype.createShadowRoot;
}
if (flags.shadow && document.querySelectorAll('script').length > 1) {
console.warn('platform.js is not the first script on the page. ' +
'See http://www.polymer-project.org/docs/start/platform.html#setup ' +
'for details.');
}
// CustomElements polyfill flag
if (flags.register) {
window.CustomElements = window.CustomElements || {flags: {}};
window.CustomElements.flags.register = flags.register;
}
if (flags.imports) {
window.HTMLImports = window.HTMLImports || {flags: {}};
window.HTMLImports.flags.imports = flags.imports;
}
// export
scope.flags = flags;
})(Platform);
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
var counter = Date.now() % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
};
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
delete: function(key) {
this.set(key, undefined);
}
};
window.WeakMap = WeakMap;
})();
}
// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function(global) {
'use strict';
// Detect and do basic sanity checking on Object/Array.observe.
function detectObjectObserve() {
if (typeof Object.observe !== 'function' ||
typeof Array.observe !== 'function') {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var test = {};
var arr = [];
Object.observe(test, callback);
Array.observe(arr, callback);
test.id = 1;
test.id = 2;
delete test.id;
arr.push(1, 2);
arr.length = 0;
Object.deliverChangeRecords(callback);
if (records.length !== 5)
return false;
if (records[0].type != 'add' ||
records[1].type != 'update' ||
records[2].type != 'delete' ||
records[3].type != 'splice' ||
records[4].type != 'splice') {
return false;
}
Object.unobserve(test, callback);
Array.unobserve(arr, callback);
return true;
}
var hasObserve = detectObjectObserve();
function detectEval() {
// Don't test for eval if we're running in a Chrome App environment.
// We check for APIs set that only exist in a Chrome App context.
if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) {
return false;
}
try {
var f = new Function('', 'return true;');
return f();
} catch (ex) {
return false;
}
}
var hasEval = detectEval();
function isIndex(s) {
return +s === s >>> 0;
}
function toNumber(s) {
return +s;
}
function isObject(obj) {
return obj === Object(obj);
}
var numberIsNaN = global.Number.isNaN || function(value) {
return typeof value === 'number' && global.isNaN(value);
}
function areSameValue(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
if (numberIsNaN(left) && numberIsNaN(right))
return true;
return left !== left && right !== right;
}
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var identStart = '[\$_a-zA-Z]';
var identPart = '[\$_a-zA-Z0-9]';
var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$');
function getPathCharType(char) {
if (char === undefined)
return 'eof';
var code = char.charCodeAt(0);
switch(code) {
case 0x5B: // [
case 0x5D: // ]
case 0x2E: // .
case 0x22: // "
case 0x27: // '
case 0x30: // 0
return char;
case 0x5F: // _
case 0x24: // $
return 'ident';
case 0x20: // Space
case 0x09: // Tab
case 0x0A: // Newline
case 0x0D: // Return
case 0xA0: // No-break space
case 0xFEFF: // Byte Order Mark
case 0x2028: // Line Separator
case 0x2029: // Paragraph Separator
return 'ws';
}
// a-z, A-Z
if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A))
return 'ident';
// 1-9
if (0x31 <= code && code <= 0x39)
return 'number';
return 'else';
}
var pathStateMachine = {
'beforePath': {
'ws': ['beforePath'],
'ident': ['inIdent', 'append'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'inPath': {
'ws': ['inPath'],
'.': ['beforeIdent'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'beforeIdent': {
'ws': ['beforeIdent'],
'ident': ['inIdent', 'append']
},
'inIdent': {
'ident': ['inIdent', 'append'],
'0': ['inIdent', 'append'],
'number': ['inIdent', 'append'],
'ws': ['inPath', 'push'],
'.': ['beforeIdent', 'push'],
'[': ['beforeElement', 'push'],
'eof': ['afterPath', 'push']
},
'beforeElement': {
'ws': ['beforeElement'],
'0': ['afterZero', 'append'],
'number': ['inIndex', 'append'],
"'": ['inSingleQuote', 'append', ''],
'"': ['inDoubleQuote', 'append', '']
},
'afterZero': {
'ws': ['afterElement', 'push'],
']': ['inPath', 'push']
},
'inIndex': {
'0': ['inIndex', 'append'],
'number': ['inIndex', 'append'],
'ws': ['afterElement'],
']': ['inPath', 'push']
},
'inSingleQuote': {
"'": ['afterElement'],
'eof': ['error'],
'else': ['inSingleQuote', 'append']
},
'inDoubleQuote': {
'"': ['afterElement'],
'eof': ['error'],
'else': ['inDoubleQuote', 'append']
},
'afterElement': {
'ws': ['afterElement'],
']': ['inPath', 'push']
}
}
function noop() {}
function parsePath(path) {
var keys = [];
var index = -1;
var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath';
var actions = {
push: function() {
if (key === undefined)
return;
keys.push(key);
key = undefined;
},
append: function() {
if (key === undefined)
key = newChar
else
key += newChar;
}
};
function maybeUnescapeQuote() {
if (index >= path.length)
return;
var nextChar = path[index + 1];
if ((mode == 'inSingleQuote' && nextChar == "'") ||
(mode == 'inDoubleQuote' && nextChar == '"')) {
index++;
newChar = nextChar;
actions.append();
return true;
}