-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqmachine.js
More file actions
1921 lines (1834 loc) · 85.8 KB
/
qmachine.js
File metadata and controls
1921 lines (1834 loc) · 85.8 KB
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
//- JavaScript source code
//- qmachine.js ~~
// ~~ (c) SRW, 15 Nov 2012
// ~~ last updated 08 Feb 2015
(function (global, sandbox) {
'use strict';
// Pragmas
/*jshint maxparams: 5, quotmark: single, strict: true */
/*jslint indent: 4, maxlen: 80 */
/*properties
a, ActiveXObject, addEventListener, anon, appendChild, apply, ass,
atob, attachEvent, avar, b, bitwise, body, box, browser, btoa, by,
call, can_run_remotely, charAt, charCodeAt, clearTimeout, closure,
CoffeeScript, comm, configurable, console, constructor, contentWindow,
continue, createElement, data, debug, def, '__defineGetter__',
defineProperty, '__defineSetter__', detachEvent, devel, diagnostics,
display, document, done, enable_volunteer, enumerable, env, epitaph,
eqeq, error, errors, es5, eval, evil, exemptions, exit, f, fail, floor,
forin, fromCharCode, get, getElementsByTagName, global, hasOwnProperty,
head, host, ignoreCase, importScripts, indexOf, join, JSLINT, key,
length, lib, load_data, load_script, location, log, map, mapreduce,
method, multiline, navigator, newcap, node, nomen, now, on, onLine,
onload, onreadystatechange, open, parentElement, parse, passfail,
plusplus, ply, postMessage, predef, properties, protocol, prototype,
push, puts, Q, QM, QUANAH, query, random, readyState, reason, recent,
reduce, regexp, removeChild, removeEventListener, replace,
responseText, result, results, revive, rhino, run_remotely, send, set,
setRequestHeader, setTimeout, shelf, shift, slice, sloppy, source, src,
start, status, stay, stringify, stop, stupid, style, sub, submit, sync,
test, time, timer, toJSON, toSource, toString, todo, unparam, url, val,
value, valueOf, vars, via, visibility, volunteer, white, window,
withCredentials, writable, x, XDomainRequest, XMLHttpRequest, y
*/
// Prerequisites
if (global.hasOwnProperty('QM')) {
// Exit early if QMachine is already present.
return;
}
if (global.hasOwnProperty('QUANAH') === false) {
// This checks to make sure that Quanah 0.2.0 or later has been loaded.
throw new Error('Quanah is missing.');
}
// Declarations
var ajax, atob, AVar, avar, btoa, can_run_remotely, convert_to_js, copy,
deserialize, defineProperty, get_avar, get_list, in_a_browser,
in_a_WebWorker, is_closed, is_Function, is_RegExp, is_String, lib,
load_data, load_script, map, mapreduce, mothership, origin, ply, puts,
recent, reduce, revive, run_remotely, serialize, set_avar, start,
state, stop, submit, sync, uuid, update_local, update_remote,
volunteer;
// Definitions
ajax = function (method, url, body) {
// This function returns an avar.
var y = avar();
y.Q(function (evt) {
// This function needs documentation of a more general form ...
if ((body !== undefined) && (body.length > 65536)) {
// If it's likely to fail (because the default "max_body_size" is
// 64 KB), why not just fail preemptively?
return evt.fail('Upload size is too large.');
}
if (recent(method, url)) {
// If we have already issued this request recently, we need to
// wait a minute before doing it again to avoid hammering the
// server needlessly.
return evt.stay('Enforcing refractory period ...');
}
var request;
// As of Chrome 21 (and maybe sooner than that), Web Workers do have
// the `XMLHttpRequest` constructor, but it isn't one of `global`'s
// own properties as it is in Firefox 15.01 or Safari 6. In Safari 6,
// however, `XMLHttpRequest` has type 'object' rather than 'function',
// which makes _zero_ sense to me right now. Thus, my test is _not_
// intuitive in the slightest ...
if (global.XMLHttpRequest instanceof Object) {
request = new global.XMLHttpRequest();
if (origin() !== mothership) {
// This is a slightly weaker test than using `hasOwnProperty`,
// but it may work better with Firefox. I'll test in a minute.
if (request.withCredentials === undefined) {
if (global.hasOwnProperty('XDomainRequest')) {
request = new global.XDomainRequest();
} else {
return evt.fail('Browser does not support CORS.');
}
}
}
} else if (global.hasOwnProperty('ActiveXObject')) {
request = new global.ActiveXObject('Microsoft.XMLHTTP');
} else {
return evt.fail('Browser does not support AJAX.');
}
request.onreadystatechange = function () {
// This function needs documentation.
if (request.readyState === 4) {
if (request.status >= 500) {
// These are internal server errors that were occurring
// in early "full-stack" versions of QMachine due to a
// small error in a Monit script. I've left this arm in
// here just in case something silly like that happens
// again so that the client keeps trying to connect if
// the error is due to a temporary snag on the server.
return evt.stay('Internal server error?');
}
y.val = request.responseText;
if (((method === 'GET') && (request.status !== 200)) ||
((method === 'POST') && (request.status !== 201))) {
// Something else went wrong, and we can't ignore it.
return evt.fail(request.status);
}
return evt.exit();
}
// NOTE: Should we `revive` here?
return;
};
request.open(method, url, true);
if (method === 'POST') {
// This code only ever runs as part of an API call. As of v1.1.14,
// neither the Node.js nor Ruby servers check for this header, but
// frameworks like Express (http://expressjs.com) that parse the
// body of the incoming request automatically *do* care.
request.setRequestHeader('Content-Type', 'application/json');
}
request.send(body);
return;
});
return y;
};
atob = function (x) {
// This function redefines itself during its first invocation.
if (is_Function(global.atob)) {
atob = global.atob;
} else {
atob = function (x) {
// This function decodes a string which has been encoded using
// base64 encoding. It isn't part of JavaScript or any standard,
// but it _is_ a DOM Level 0 method, and it is extremely useful
// to have around. Unfortunately, it isn't available in Node.js,
// the Web Worker contexts of Chrome 21 or Safari 6, or common
// server-side developer shells like Spidermonkey, D8 / V8, or
// JavaScriptCore.
/*jslint bitwise: true */
var a, ch1, ch2, ch3, en1, en2, en3, en4, i, n, y;
n = x.length;
y = '';
if (n > 0) {
a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg' +
'hijklmnopqrstuvwxyz0123456789+/=';
// NOTE: This `for` loop may actually require sequentiality
// as currently written. I converted it from a `do..while`
// implementation, but I will write it as a `map` soon :-)
for (i = 0; i < n; i += 4) {
// Surprisingly, my own tests have shown that it is faster
// to use the `charAt` method than to use array indices,
// as of 19 Aug 2012. I _do_ know that `charAt` has better
// support in old browsers, but the speed surprised me.
en1 = a.indexOf(x.charAt(i));
en2 = a.indexOf(x.charAt(i + 1));
en3 = a.indexOf(x.charAt(i + 2));
en4 = a.indexOf(x.charAt(i + 3));
if ((en1 < 0) || (en2 < 0) || (en3 < 0) || (en4 < 0)) {
// It also surprised me to find out that testing for
// invalid characters inside the loop is faster than
// validating with a regular expression beforehand.
throw new Error('Invalid base64 characters: ' + x);
}
ch1 = ((en1 << 2) | (en2 >> 4));
ch2 = (((en2 & 15) << 4) | (en3 >> 2));
ch3 = (((en3 & 3) << 6) | en4);
y += String.fromCharCode(ch1);
if (en3 !== 64) {
y += String.fromCharCode(ch2);
}
if (en4 !== 64) {
y += String.fromCharCode(ch3);
}
}
}
return y;
};
}
return atob(x);
};
AVar = global.QUANAH.avar().constructor;
avar = global.QUANAH.avar;
btoa = function (x) {
// This function redefines itself during its first invocation.
if (is_Function(global.btoa)) {
btoa = global.btoa;
} else {
btoa = function (x) {
// This function encodes binary data into a base64 string. It
// isn't part of JavaScript or any standard, but it _is_ a DOM
// Level 0 method, and it is extremely useful to have around.
// Unfortunately, it isn't available in Node.js, the Web Worker
// contexts of Chrome 21 or Safari 6, or common server-side
// developer shells like Spidermonkey, D8 / V8, or JavaScriptCore.
// Also, it throws an error in most (?) browsers if you feed it
// Unicode (see http://goo.gl/3fLFs).
/*jslint bitwise: true */
var a, ch1, ch2, ch3, en1, en2, en3, en4, i, n, y;
n = x.length;
y = '';
if (n > 0) {
a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg' +
'hijklmnopqrstuvwxyz0123456789+/=';
// NOTE: This `for` loop may actually require sequentiality
// as currently written. I converted it from a `do..while`
// implementation, but I will write it as a `map` soon :-)
for (i = 0; i < n; i += 3) {
ch1 = x.charCodeAt(i);
ch2 = x.charCodeAt(i + 1);
ch3 = x.charCodeAt(i + 2);
en1 = (ch1 >> 2);
en2 = (((ch1 & 3) << 4) | (ch2 >> 4));
en3 = (((ch2 & 15) << 2) | (ch3 >> 6));
en4 = (ch3 & 63);
if (isNaN(ch2)) {
en3 = en4 = 64;
} else if (isNaN(ch3)) {
en4 = 64;
}
y += (a.charAt(en1) + a.charAt(en2) + a.charAt(en3) +
a.charAt(en4));
}
}
return y;
};
}
return btoa(x);
};
can_run_remotely = function (task) {
// This function returns a boolean.
return ((global.hasOwnProperty('JSON')) &&
(global.hasOwnProperty('JSLINT')) &&
(task instanceof Object) &&
(task.hasOwnProperty('f')) &&
(task.hasOwnProperty('x')) &&
(is_Function(task.f)) &&
(task.x instanceof AVar) &&
// (is_online()) &&
(is_closed(task, state.exemptions[task.x.key]) === false));
};
convert_to_js = function (x) {
// This function converts a function or string into an avar with a `val`
// property that is a JavaScript function. This isn't quite the same as an
// `eval`, however, because the string is expected to be used only when it
// represents CoffeeScript code. Unfortunately, the mere use of the word
// so irritates JSLint that I must designate this function "evil" just to
// suppress its scary messages.
/*jslint evil: true */
var y = avar();
y.Q(function (evt) {
// This function needs documentation.
if (is_Function(x)) {
y.val = x;
return evt.exit();
}
if (is_String(x) === false) {
return evt.fail('Cannot convert argument to a function');
}
if (global.hasOwnProperty('CoffeeScript')) {
y.val = global.CoffeeScript['eval'](x);
return evt.exit();
}
lib('//cdnjs.cloudflare.com/ajax/libs/coffee-script' +
'/1.6.3/coffee-script.min.js').Q(function (lib_evt) {
// This function needs documentation.
y.val = global.CoffeeScript['eval'](x);
lib_evt.exit();
return evt.exit();
}).on('error', evt.fail);
return;
});
return y;
};
copy = function (x, y) {
// This function copies the properties of `x` to `y`, specifying `y` as
// object literal if it was not provided as an input argument. It does
// not perform a "deep copy", which means that properties whose values
// are objects will be "copied by reference" rather than by value. Right
// now, I see no reason to worry about deep copies or getters / setters.
// Because the current version of Quanah no longer uses ECMAScript 5.1
// features to make the `comm` method non-enumerable, however, we do have
// to be careful not to overwrite the `y.comm` method if `y` is an avar.
if (y === undefined) {
// At one point, I used a test here that `arguments.length === 1`,
// but it offended JSLint:
// "Do not mutate parameter 'y' when using 'arguments'."
y = {};
}
var comm, key;
if (y instanceof AVar) {
comm = y.comm;
}
for (key in x) {
if (x.hasOwnProperty(key)) {
y[key] = x[key];
}
}
if (is_Function(comm)) {
y.comm = comm;
}
return y;
};
defineProperty = function (obj, name, params) {
// This function wraps the ES5 `Object.defineProperty` function so that
// it degrades gracefully in crusty old browsers. I would like to improve
// my implementation eventually so that the fallback definition will more
// closely simulate the ES5 specification, but for now, this works well.
// For more information, see the documentation at http://goo.gl/xXHKr.
if (Object.hasOwnProperty('defineProperty')) {
defineProperty = Object.defineProperty;
} else if (Object.prototype.hasOwnProperty('__defineGetter__')) {
defineProperty = function (obj, name, params) {
// This function needs documentation.
/*jslint nomen: true */
params = (params instanceof Object) ? params : {};
ply(params).by(function (key, val) {
// This has a "forEach" pattern ==> `ply` is justified.
if (key === 'get') {
obj.__defineGetter__(name, val);
} else if (key === 'set') {
obj.__defineSetter__(name, val);
} else if (key === 'value') {
// NOTE: This may fail if the property's `configurable`
// attribute was set to `false`, but if such an error
// could occur, that JS implementation would have had a
// native `Object.defineProperty` method anyway :-P
delete obj[name];
obj[name] = val;
}
return;
});
return obj;
};
} else {
throw new Error('Platform lacks support for getters and setters.');
}
return defineProperty(obj, name, params);
};
deserialize = function ($x) {
// This function is a JSON-based deserialization utility that can invert
// the `serialize` function provided herein. Unfortunately, no `fromJSON`
// equivalent exists for obvious reasons -- it would have to be a String
// prototype method, and it would have to be extensible for all types.
// NOTE: This definition could stand to be optimized, but I recommend
// leaving it as-is until improving performance is absolutely critical.
/*jslint unparam: true */
return JSON.parse($x, function reviver(key, val) {
// This function is provided to `JSON.parse` as the optional second
// parameter that its documentation refers to as a `reviver` function.
// NOTE: This is _not_ the same as Quanah's `revive`!
var f, re;
re = /^\[(FUNCTION|REGEXP) ([A-z0-9\+\/\=]+) ([A-z0-9\+\/\=]+)\]$/;
// Is the second condition even reachable in the line below?
if (is_String(val)) {
if (re.test(val)) {
val.replace(re, function ($0, type, code, props) {
// This function is provided to the String prototype's
// `replace` method and uses references to the enclosing
// scope to return results. I wrote things this way in
// order to avoid changing the type of `val` and thereby
// confusing the JIT compilers, but I'm not certain that
// using nested closures is any faster anyway. For that
// matter, calling the regular expression twice may be
// slower than calling it once and processing its output
// conditionally, and that way might be clearer, too ...
f = sandbox(atob(code));
copy(deserialize(atob(props)), f);
return;
});
}
}
return (f !== undefined) ? f : val;
});
};
get_avar = function (x) {
// This function needs documentation.
var y = ajax('GET', mothership + '/box/' + x.box + '?key=' + x.key);
return y.Q(function (evt) {
// This function deserializes the string returned as the `val` of
// `y` into a temporary variable and then copies its property values
// back onto `y`.
copy(deserialize(y.val), y);
return evt.exit();
});
};
get_list = function (box) {
// This function retrieves a list of tasks that need to be executed.
var y = ajax('GET', mothership + '/box/' + box + '?status=waiting');
return y.Q(function (evt) {
// This function needs documentation.
y.val = JSON.parse(y.val);
return evt.exit();
});
};
in_a_browser = function () {
// This function returns a boolean.
return ((global.hasOwnProperty('location')) &&
(global.hasOwnProperty('navigator')) &&
(global.hasOwnProperty('phantom') === false) &&
(global.hasOwnProperty('system') === false));
};
in_a_WebWorker = function () {
// This function returns a boolean.
return ((is_Function(global.importScripts)) &&
(global.location instanceof Object) &&
(global.navigator instanceof Object) &&
(global.hasOwnProperty('phantom') === false) &&
(global.hasOwnProperty('system') === false));
};
is_closed = function (x, options) {
// This function tests an input argument `x` for references that "close"
// over external references from another scope. This function solves a
// very important problem in JavaScript because function serialization is
// extremely difficult to perform rigorously. Most programmers consider a
// function only as its source code representation, but because it is also
// a closure and JavaScript has lexical scope, the exact "place" in the
// code where the code existed is important, too. A third consideration is
// that a function is also an object which can have methods and properties
// of its own, and these need to be included in the serializated form. I
// puzzled over this problem and eventually concluded that because I may
// not be able to serialize an entire scope (I haven't solved that yet), I
// _can_ get the source code representation of a function from within most
// JavaScript implementations even though it isn't part of the ECMAScript
// standard (June 2011). Thus, if a static analysis tool were able to
// parse the source code representation to confirm that the function did
// not depend on its scope, then I might be able to serialize it, provided
// that it did not contain any methods that depended on their scopes. Of
// course, writing such a tool is a huge undertaking, so instead I just
// used a fantastic program by Douglas Crockford, JSLINT, which contains
// an expertly-written parser with configurable parameters. A bonus here
// is that JSLINT allows me to avoid a number of other unsavory problems,
// such as functions that log messages to a console -- such functions may
// or may not be serializable, but their executions should definitely
// occur on the same machines that invoked them! Anyway, this function is
// only one solution to the serialization problem, and I welcome feedback
// from others who may have battled the same problems :-)
/*jslint unparam: true */
if ((options instanceof Object) === false) {
options = {};
}
var comm, $f, flag, left, right;
if (x instanceof AVar) {
// We'll put this back later.
comm = x.comm;
delete x.comm;
}
flag = false;
left = '(function () {\nreturn ';
right = ';\n}());';
if (x instanceof Object) {
if (is_Function(x)) {
if (is_Function(x.toJSON)) {
$f = x.toJSON();
} else if (is_Function(x.toSource)) {
$f = x.toSource();
} else if (is_Function(x.toString)) {
$f = x.toString();
} else {
// If we fall this far, we're probably in trouble anyway, but
// we aren't out of options yet. We could try to coerce to a
// string by adding an empty string or calling the String
// constructor without the `new` keyword, but I'm not sure if
// either would cause Quanah itself to fail JSLINT. Of course,
// we can always just play it safe and return `true` early to
// induce local execution of the function -- let's do that!
return true;
}
// By this point, `$f` must be defined, and it must be a string
// or else the next line will fail when we try to remove leading
// and trailing parentheses in order to appease JSLINT.
$f = left + $f.replace(/^[(]|[)]$/g, '') + right;
// Now, we send our function's serialized form `$f` into JSLINT
// for analysis, taking care to disable all options that are not
// directly relevant to determining if the function is suitable
// for running in some remote JavaScript environment. If JSLINT
// returns `false` because the scan fails for some reason, the
// answer to our question would be `true`, which is why we have
// to negate JSLINT's output.
flag = (false === global.JSLINT($f, copy(options, {
// JSLINT configuration options, as of version 2013.05.31:
'ass': true, //- allow assignment expressions?
'bitwise': true, //- allow use of bitwise operators?
'browser': false, //- assume browser as JS environment?
'closure': true, //- tolerate Google Closure idioms?
'continue': true, //- allow continuation statement?
'debug': false, //- allow debugger statements?
'devel': false, //- allow output logging?
'eqeq': true, //- allow `==` instead of `===`?
'es5': true, //- allow ECMAScript 5 syntax?
'evil': false, //- allow the `eval` statement?
'forin': true, //- allow unfiltered `for..in`?
//'indent': 4,
//'maxerr': 50,
//'maxlen': 80,
'newcap': true, //- constructors must be capitalized?
'node': false, //- assume Node.js as JS environment?
'nomen': true, //- allow names' dangling underscores?
'passfail': true, //- halt the scan on the first error?
'plusplus': true, //- allow `++` and `--` usage?
'predef': {}, //- predefined global variables
'properties': false,//- require JSLINT /*properties */?
'regexp': true, //- allow `.` in regexp literals?
'rhino': false, //- assume Rhino as JS environment?
'sloppy': true, //- ES5 strict mode pragma is optional?
'stupid': true, //- allow `*Sync` calls in Node.js?
'sub': true, //- allow all forms of subset notation?
'todo': true, //- allow comments that start with TODO
'unparam': true, //- allow unused parameters?
'vars': true, //- allow multiple `var` statements?
'white': true //- allow sloppy whitespace?
})));
}
ply(x).by(function (key, val) {
// This function examines all methods and properties of `x`
// recursively to make sure none of those are closed, either.
// Because order isn't important, use of `ply` is justified.
if (flag === false) {
flag = is_closed(val, options);
}
return;
});
}
if (is_Function(comm)) {
x.comm = comm;
}
return flag;
};
is_Function = function (f) {
// This function returns `true` if and only if input argument `f` is a
// function. The second condition is necessary to avoid a false positive
// in a pre-ES5 environment when `f` is a regular expression.
return ((typeof f === 'function') && (f instanceof Function));
};
is_RegExp = function (x) {
// This function returns `true` if its input argument `x` is a RegExp. It
// is known to work in ES5, but if there is a way to "defeat" this test in
// pre-ES5 environments, please let me know!
return (Object.prototype.toString.call(x) === '[object RegExp]');
};
is_String = function (x) {
// This function returns a boolean that indicates whether the given
// argument `x` can be safely assumed to have `String.prototype` methods.
return ((typeof x === 'string') || (x instanceof String));
};
/*
is_online = function () {
// This function returns a boolean. It is not currently necessary, but I
// have future plans that will require this function, so I have already
// generalized QM in preparation.
return (mothership === 'LOCAL_ADDR') || global.navigator.onLine;
};
*/
lib = function (url) {
// This function returns an avar.
var y = avar();
if (in_a_WebWorker()) {
y.Q(function (evt) {
// This function needs documentation.
global.importScripts(url);
return evt.exit();
});
} else if (in_a_browser()) {
y.Q(function (evt) {
// This function use the conventional "script tag loading"
// technique to import external libraries. Ideally, it would try
// to avoid loading libraries it has already loaded, but it turns
// out that this is a very difficult once JSONP becomes involved
// because those scripts _do_ need to reload every time. Thus, I
// will need to start documenting best practices to teach others
// how to construct idempotent scripts that won't leak memory and
// plan to begin using "disposable execution contexts" like Web
// Workers again soon.
//
// See also: http://goo.gl/byXCA and http://goo.gl/fUCXa .
//
/*jslint browser: true, unparam: true */
var current, script;
current = global.document.getElementsByTagName('script');
script = global.document.createElement('script');
if (is_Function(script.attachEvent)) {
script.attachEvent('onload', function onload() {
// This function needs documentation.
script.detachEvent('onload', onload);
if (script.parentElement === global.document.head) {
global.document.head.removeChild(script);
} else {
global.document.body.removeChild(script);
}
script = null;
return evt.exit();
});
} else {
script.addEventListener('load', function onload() {
// This function needs documentation.
script.removeEventListener('load', onload, false);
if (script.parentElement === global.document.head) {
global.document.head.removeChild(script);
} else {
global.document.body.removeChild(script);
}
script = null;
return evt.exit();
}, false);
}
script.src = url;
ply(current).by(function (key, val) {
// This function needs documentation.
if (script.src === val.src) {
// Aha! At long last, I have found a practical use for
// Cantor's Diagonalization argument :-P
script.src += '?';
}
return;
});
if ((global.document.body instanceof Object) === false) {
global.document.head.appendChild(script);
} else {
global.document.body.appendChild(script);
}
current = null;
return;
});
} else {
y.Q(function (evt) {
// This function needs documentation.
return evt.fail('Missing `lib` definition');
});
}
return y;
};
load_data = function (x, callback) {
// This function is an incredibly rare one in the sense that it accepts
// `x` which can be either an object literal or a string. Typically, I am
// too "purist" to write such a _convenient_ function :-P
var xdm, y, yql;
xdm = function (evt) {
// This function needs documentation.
var proxy, request;
proxy = global.document.createElement('iframe');
request = this;
proxy.src = request.val.via;
proxy.display = 'none';
proxy.style.visibility = 'hidden';
proxy.onload = function () {
// This function runs when the iframe loads.
proxy.contentWindow.postMessage(JSON.stringify({
x: request.val.url
}), proxy.src);
return;
};
global.window.addEventListener('message', function cb(dom_evt) {
// This function needs documentation.
var temp = JSON.parse(dom_evt.data);
if (temp.x === request.val.url) {
request.val = temp.y;
global.window.removeEventListener('message', cb, false);
global.document.body.removeChild(proxy);
proxy = null;
return evt.exit();
}
return;
}, false);
global.document.body.appendChild(proxy);
return;
};
y = (x instanceof AVar) ? copy(x, avar(x.val)) : avar(x);
yql = function (evt) {
// This function uses Yahoo Query Language (YQL) as a cross-domain
// proxy for retrieving text files. Binary file types probably won't
// work very well at the moment, but I'll tweak the Open Data Table
// I created soon to see what can be done toward that end.
var base, callback, diag, format, query, temp;
global.QM.shelf['temp' + y.key] = function (obj) {
// This function needs documentation.
if (obj.query.results === null) {
return evt.fail(obj.query.diagnostics);
}
y.val = obj.query.results.result;
delete global.QM.shelf['temp' + y.key];
return evt.exit();
};
base = '//query.yahooapis.com/v1/public/yql?';
diag = 'diagnostics=true';
callback = 'callback=QM.shelf.temp' + y.key;
format = 'format=json';
query = 'q=' +
'USE "https://wilkinson.github.io/qmachine/qm.proxy.xml";' +
'SELECT * FROM qm.proxy WHERE url="' + y.val.url + '";';
temp = lib(base + [callback, diag, format, query].join('&'));
temp.on('error', evt.fail);
return;
};
y.on('error', function (message) {
// This function needs documentation.
if (is_Function(callback)) {
y.val = callback(message, y.val);
}
return;
}).Q(function (evt) {
// This function needs documentation.
var flag;
flag = ((y.val instanceof Object) &&
(y.val.hasOwnProperty('url')) &&
(y.val.hasOwnProperty('via')) &&
(in_a_browser() === true) &&
(is_Function(global.window.postMessage)));
return (flag === true) ? xdm.call(y, evt) : yql.call(y, evt);
}).Q(function (evt) {
// This function needs documentation.
if (is_Function(callback)) {
y.val = callback(null, y.val);
}
return evt.exit();
});
return y;
};
load_script = function (url, callback) {
// This function loads external JavaScript files using the usual callback
// idioms to which most JavaScripters are accustomed / addicted ;-)
return lib(url).Q(function (evt) {
// This function only runs if the script loaded successfully.
if (is_Function(callback)) {
callback(null);
}
return evt.exit();
}).on('error', function (message) {
// This function only runs if the script fails to load.
if (is_Function(callback)) {
callback(message);
}
return;
});
};
map = function (x, f, box, env) {
// This function needs documentation.
var y = ((x instanceof AVar) ? x : avar(x)).Q(function (evt) {
// This function needs documentation.
var i, n, temp;
n = this.val.length;
temp = [];
for (i = 0; i < n; i += 1) {
temp[i] = submit(this.val[i], f, box, env);
temp[i].on('error', evt.fail);
}
sync.apply(this, temp).Q(function (temp_evt) {
// This function needs documentation.
var i, n;
n = temp.length;
y.val = [];
for (i = 0; i < n; i += 1) {
y.val[i] = temp[i].val;
}
temp_evt.exit();
return evt.exit();
});
return;
});
return y;
};
mapreduce = function (x, mapf, redf, box, env) {
// This function needs documentation.
var y = avar();
y.Q(function (evt) {
// This function needs documentation.
map(x, mapf, box, env).Q(function (temp_evt) {
// This function needs documentation.
y.val = this.val;
temp_evt.exit();
return evt.exit();
}).on('error', evt.fail);
return;
}).Q(function (evt) {
// This function needs documentation.
reduce(y.val, redf, box, env).Q(function (temp_evt) {
// This function needs documentation.
y.val = this.val;
temp_evt.exit();
return evt.exit();
}).on('error', evt.fail);
return;
});
return y;
};
mothership = 'https://api.qmachine.org';
origin = function () {
// This function needs documentation.
return global.location.protocol + '//' + global.location.host;
};
ply = function () {
// This function has been condensed from its previous forms because
// changes in Quanah 0.2.x made its support of dual asynchronous and
// synchronous idioms both unnecessary and obsolete.
var args = Array.prototype.slice.call(arguments);
return {
by: function (f) {
// This function is a general-purpose iterator for key-value
// pairs, and it works exceptionally well in JavaScript because
// hash-like objects are so common in this language. This
// definition itself is a little slower than previous versions
// because they were optimized for internal use. In
// performance-critical sections of Quanah that run often but
// rarely change, I have inlined loops as appropriate. It is
// difficult to optimize code for use with modern JIT compilers,
// and my own recommendation is to hand-optimize with loops only
// if you're truly obsessed with performance -- it's a lot of
// work, and the auto-detecting and delegating dynamically in
// order to use the fastest possible loop pattern adds overhead
// that can be difficult to optimize for use in real-world
// applications. That said, if you have ideas for how to make
// `ply..by` run more efficiently, by all means drop me a line :-)
if (is_Function(f) === false) {
throw new TypeError('`ply..by` expects a function.');
}
var i, key, obj, n, toc, x;
n = args.length;
toc = {};
x = [];
for (i = 0; i < n; i += 1) {
if ((args[i] !== null) && (args[i] !== undefined)) {
obj = args[i].valueOf();
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (toc.hasOwnProperty(key) === false) {
toc[key] = x.push([key]) - 1;
}
x[toc[key]][i + 1] = obj[key];
}
}
}
}
n = x.length;
for (i = 0; i < n; i += 1) {
f.apply(this, x[i]);
}
return;
}
};
};
puts = function () {
// This function needs documentation.
var args = Array.prototype.slice.call(arguments);
return sync.apply(this, args).Q(function (evt) {
// This function needs documentation.
if ((global.console instanceof Object) &&
(is_Function(global.console.log))) {
global.console.log(args.join(' '));
return evt.exit();
}
return evt.fail('The `console.log` method is not available.');
}).on('error', function (message) {
// This function needs documentation.
if ((global.console instanceof Object) &&
(is_Function(global.console.error))) {
global.console.error('Error:', message);
}
return;
});
};
recent = function (method, url) {
// This function helps keep clients from polling too rapidly when they are
// waiting for a remote task to finish. It keeps track of HTTP requests
// made within the last 1000 milliseconds in order to prevent repeat calls
// that use the same method and URL. This doesn't affect task execution by
// volunteers, however, because those alternate between GETs and POSTs.
var dt, flag, key, time;
dt = 1000;
time = Date.now();
for (key in state.recent) {
if (state.recent.hasOwnProperty(key)) {
if ((time - state.recent[key].time) > dt) {
delete state.recent[key];
}
}
}
flag = ((state.recent.hasOwnProperty(url)) &&
(state.recent[url].method === method));
if (flag === false) {
state.recent[url] = {
method: method,
time: time
};
revive(dt + 1);
}
return flag;
};
reduce = function (x, redf, box, env) {
// This function needs documentation.
var f, y;
f = convert_to_js(redf);
y = ((x instanceof AVar) ? x : avar(x)).Q(function (evt) {
// This function needs documentation.
if (is_Function(f.val) === false) {
f.on('error', evt.fail);
return evt.stay('Awaiting function translation ...');
}
if (this.val.length < 2) {
this.val = this.val[0];
return evt.exit();
}
var g, i, n, obj, temp, that, x;
g = function (obj) {
// This function needs documentation.
return obj.f(obj.a, obj.b);
};
temp = [];
that = this;
x = that.val;
// This line is easier to read than modulo junk ...
n = 2 * Math.floor(x.length / 2);
for (i = 0; i < n; i += 2) {
obj = {f: f.val, a: x[i], b: x[i + 1]};
temp.push(submit(obj, g, box, env).on('error', evt.fail));
}
if (n !== x.length) {
temp.push(avar(x[x.length - 1]).on('error', evt.fail));
}
sync.apply(this, temp).Q(function (temp_evt) {
// This function needs documentation.
var i, n, x;
n = temp.length;
x = [];
for (i = 0; i < n; i += 1) {
x[i] = temp[i].val;
}
that.val = x;
temp_evt.exit();
return evt.stay('asynchronous loop');
}).on('error', evt.fail);
return;
});
return y;
};
revive = function (ms) {
// This function restarting Quanah's event loop asynchronously using the
// browser's own event loop if possible. It accepts an optional argument
// specifying the number of milliseconds to wait before restarting.
var dt = parseInt(ms, 10);
if (is_Function(global.setTimeout)) {
global.setTimeout(AVar.prototype.revive, isNaN(dt) ? 0 : dt);
} else {
AVar.prototype.revive();
}
return;
};
run_remotely = function (obj) {
// This function distributes computations to remote execution nodes by
// constructing a task that represents the computation, writing it to a
// shared storage, polling for changes to its status, and then reading
// the new values back into the local variables. My strategy is to use
// a bunch of temporary avars that only execute locally -- on this part
// I must be very careful, because remote calls should be able to make
// remote calls of their own, but execution of a remote call should not
// require remote calls of its own! A publication is forthcoming, and at