/ Check-in [733d68576a]
DEMO | DOWNLOAD | DEPLOY | SEARCH
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Refactor from jsiweb.js
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:733d68576a37a750856b1ef7df55f77189d151ca
User & Date: pmacdona 2019-05-30 17:22:09
Context
2019-05-31
14:37
Fix str add with embedded null. check-in: 593072fb9a user: pmacdona tags: trunk
2019-05-30
17:22
Refactor from jsiweb.js check-in: 733d68576a user: pmacdona tags: trunk
2019-05-24
00:33
Release "2.8.33". Fix issue [f8d3a82011]: NUL bytes not encodable. Now supports strings with \u0000 and \0. check-in: d58a5de09b user: pmacdona tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added lib/web/jsig.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
// JS signatures: type-check function call arguments.
// Emulates the typechecking builtin to Jsi, minus return types.  See https://jsish.org

(function () {
"use strict";

var doc = document,
    win = window,
    typeNameStr="number string boolean array function object regexp any userobj void null",
    typeNameLst= typeNameStr.split(' '),
    sigs = {},
    srcList = [],
    srcCnt = 0,
    onloadFunc = null,
    funcLst = [],
    ENDSTR = '<!--JSIG GEN-->',
    config = {
        alert:false,
        debug:true,
        enable:true,
        fatal :false,
        inline:true
    }
;

// Code to handle function parameter types and default values.
function Jsi() {
}

Jsi.prototype = {
    
    errorCmd: function(msg) {
        // Set breakpoint here to intercept function type warnings.
        console.log(msg);
        if (config.alert) alert(msg);
        if (config.debug) debugger;
        if (config.fatal) throw(msg);
    },
    
    parseError: function(msg) {
        errorCmd('PARSERR: '+msg+' ==> '+jsi.curSig);
        return [];
    },
    
    conf: function(vals) { // Configure options.
        for (var i in vals) {
            if (typeof config[i] == 'undefined')
                errorCmd("Option "+i+" not one of: "+Object.keys(config).join(', '));
            else
                config[i] = vals[i];
        }
    },

    ArgCheck: function(o, aind, val) { // Check arg type and return value or default.
        var af = o.args[aind],
            typ = af.typ, def = af.def;
        if (val===undefined) {
            if (def === undefined)
                return val;
            val = def;
        }
        if (typ && typ.length) {
            jsi.ArgCheckType(o, aind, val);
        }
        return val;
    },

    ArgCheckType: function(o, aind, val) {
        var typ, nam;
        if (aind>=0) {
            var af = o.args[aind];
            typ = af.typ,
            nam = af.name;
        } else {
            typ = o.rettyp;
            nam = 'return';
        }
        var tlst = typ, vtyp = typeof(val), fnam = o.name;
        var pre = 'In "'+fnam+'()" ' + (aind<0?"return value":"");
        for (var i = 0; i<tlst.length; i++) {
            switch (tlst[i]) {
                case "number":  if (vtyp === 'number') return; break;
                case "string":  if (vtyp === 'string') return; break;
                case "boolean": if (vtyp === 'boolean') return; break;
                case "function":if (vtyp === 'function') return; break;
                case "array":   if (vtyp === 'object' && val && val.constructor === Array) return; break;
                case "regexp":  if (vtyp === 'object' && val && val.constructor === RegExp) return; break;
                case "object":  if (vtyp === 'object' && val && val.constructor !== Array) return; break;
                case "any":     return; break;
                case "userobj": if (vtyp === 'object') return; break;
                case "undefined": case "void": if (val === undefined) return; break;
                case "null": if (val === null) return; break;
                default:
                    jsi.errorCmd(pre+" type unknown '"+tlst[i]+'" not one of: '+typeNameStr);
                    return 0;
            }
        }
        jsi.errorCmd(pre+' type mismatch for "'+nam+'" expected "'+typ.join('|')+'" but got "'+vtyp+'" => '+val);
    },
    
    Chk: function(sig, args) { // Check function arguments
        if (!config.enable)
            return;
        var o = sig;
        if (typeof sig === 'string') {
            o = sigs[sig];
            if (!o)
                o = sigs[sig] = jsi.SigParse(sig);        
        }
        if (typeof o !== 'object' || typeof args !== 'object')
            return jsi.errorCmd('bad sig or arguments:'+o);
        
        var len = o.args.length;
        var pre = 'In "'+o.name+'()" ';
        if (o.max>=0 && len>o.max)
            jsi.errorCmd('In "'+o.name+'()" '+"extra arguments: expected "+o.max+" got "+len);
        if (len<o.min)
            jsi.errorCmd('In "'+o.name+'()" '+"missing arguments: expected "+o.min+" got "+len);
        for (var aind = 0; aind<len; aind++) {
            var af = o.args[aind];
            jsi.ArgCheck(o, aind, args[aind]);
        }
    },

    typeValidate: function (typ) {
        if (typ === '') return null;
        var tlst = typ.split('|');
        var i = -1;
        for (i = 0; i<tlst.length; i++)
            if (typeNameLst.indexOf(tlst[i]) < 0) {
                jsi.parseError("type unknown '"+tlst[i]+'" not one of: '+typeNameStr);
                return null;
            }
        if (tlst.length===1 && tlst[0] === 'any')
            return [];
        return tlst;
    },

    SigParse: function(sig) { // Parse string signature and return info.
        jsi.curSig = sig;
        var reg = /^([a-zA-Z0-9_]*)\s*\(([^)]*)\)(:[\|a-z]+|)(\s*)$/;
        var vals = reg.exec(sig);
        var sargs = '';
        if (!vals)
            throw "invalid method: "+sig;
        //puts(vals);
        var fnam = vals[1];
        var someDef = sig.indexOf('=')>=0;
        if (sig.indexOf(':')<0 && !someDef) // Skip functions with no types or defaults
            return [];
        var res = {name:fnam}
    
        var astr = vals[2].trim();
        var acall = [];
        if (astr !== '') {
            var alst = astr.split(',');
            var minargs = alst.length, maxargs = minargs;
            var last = alst.length-1;
            for (var i = 0; i<=last; i++) {
                var aval = alst[i].trim();
                if (aval === '...') {
                    if (i != last)
                        return jsi.parseError("expected ... to be at end");
                    maxargs = -1;
                    continue;
                }
                var rega = /^([a-zA-Z0-9_]+)(:[|a-z]+|)(=.+|)$/;
                var avals = rega.exec(aval);
                if (!avals)
                    return jsi.parseError("invalid argument: "+aval);
                //puts(avals);
                if (i)
                    sargs += ', ';
                var afnam = avals[1];
                if (afnam === '' || avals.length<3)
                    afnam = aval;
                sargs += afnam;
                var defval=undefined, atyp = '';
                if (avals.length>2)
                    atyp = avals[2].substr(1);
                var tlst = jsi.typeValidate(atyp);
                   
                var hasDef = (avals[3] && avals[3] !== '');
                if (hasDef) { // Default value
                    if (avals[3] !== '=void')
                        defval = avals[3].substr(1);
                    if (minargs===alst.length)
                        minargs = i;
                }
                else if (minargs!==alst.length)
                    return jsi.parseError("non-default value follows default: "+aval+' in: '+str);
            }
            acall.push({name:afnam, typ:tlst, def:defval});
        }
        res.astr = astr;
        res.min = minargs;
        res.max = maxargs;
        res.args = acall;
        res.sargs = sargs;
        var rettyp = vals[3].substr(1);
        if (rettyp === '' || rettyp === 'any' || !jsi.typeValidate(rettyp))
            rettyp = '';
        res.rettyp = rettyp;
        res.retval = vals[3];
        res.ssig = sig;
        return res;
    },
    
    SigConvert: function(code) { // Convert typed functions to work in browser, adding $jsig and default-value set.
        
        function reMethod(str) {
            var reg = /^function\s*([a-zA-Z0-9_]*)\s*\(([^)]*)\)(:[\|a-z]+|)(\s*)\{$/;
            var vals = reg.exec(str);
            if (!vals) {
                puts("invalid method: "+str);
                return str;
            }
            //puts(vals);
            var fnam = vals[1];
            if (fnam !== '' && fnam[0] !== '_')
                funcLst.push(fnam);
            var someDflt = str.indexOf('=')>=0;
            if (str.indexOf(':')<0 && !someDflt) // Skip functions with no types or defaults
                return str;
            var res = 'function '+fnam+'(';
        
            var astr = vals[2].trim();
            if (astr === '')
                res += str + ') {';
            else {
                var sobj = jsi.SigParse(fnam+'('+vals[2]+')'+vals[3]);
                puts('SOBJ',JSON.stringify(sobj));
                res += sobj.sargs+')'+sobj.retval + '{ $jsig("'+sobj.ssig+'", arguments); ';
            }

            return res;
        }
        var reg = /function\s*[a-zA-Z0-9_]*\s*\([^)]*\)(:[\|a-z]+|)\s*\{/g;
        return code.replace(reg, reMethod) + '\n'+ENDSTR;
    },
    
    SaveFile: function(filename, data, mime) {
        var blob = new Blob([data], {type: (mime?mime:'text/html')});
        if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var elem = window.document.createElement('a');
            elem.href = window.URL.createObjectURL(blob);
            elem.download = filename;
            document.body.appendChild(elem);
            elem.click();
            document.body.removeChild(elem);
        }
    },
    
    AddClose: function(id, escFunc) {
        if (id.firstElementChild.className !== 'close-icon') {
            var ct = document.createElement('button');
            ct.onclick = escFunc;
            ct.className='close-icon';
            id.insertBefore(ct, id.firstElementChild);
        }
    },
    ajax: function(o) { // Get file using XMLHttpRequest.
        var xhr = new XMLHttpRequest();
        if (!o.method) o.method = 'GET';
        xhr.open(o.method, o.url);
        xhr.send(null);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) { // req is done.
                if (xhr.status >= 200 && xhr.status < 400) {
                    if (o.success)
                        o.success(xhr.responseText);
                    else
                        console.log(xhr.responseText);
                } else {
                    if (o.error)
                        o.error(xhr, "failed");
                    else
                        console.log('Error: ' + xhr.status);
                }
            }
        };                
    },
    srcAdd: function(fn, asData) {
        puts('adding',fn);
        var f=document.createElement('script');
        f.setAttribute("type","text/javascript");
        if (asData)
            f.innerHTML = fn;
        else {
            f.setAttribute("src", fn);
            srcCnt++;
            f.setAttribute("onload", '$jsi.srcDone("'+fn+'");');
        }
        document.getElementsByTagName("head")[0].appendChild(f);
    },
    src: function(fn) {
        if (window.jsiWebSocket)
            return jsi.srcAdd(fn);
        srcList.push(fn);
        srcCnt++;
        jsi.ajax({url:fn, success:jsi.srcSuccess, error:jsi.srcError});
    },
    srcDone: function(fn) {
        srcCnt--;
    },
    srcSuccess: function(str) {
        srcCnt--;
        puts('Src Success: '+str);
        var estr = str.substr(str.length-ENDSTR.length);
        if (estr !== ENDSTR) {
            str = jsi.SigConvert(str);
            puts('Src xlate: '+str);
        }
        jsi.srcAdd(str, true);
        //eval.call({}, str);
    },
    srcError: function(str) {
        srcCnt--;
        puts('Src Error: '+str);
    },
    query: function(sel, top) {
        var rc;
        if (typeof sel === 'function') {
            document.addEventListener("DOMContentLoaded", function () {
             sel(); });
            return null;
        }
        if (!top)
            top = document; 
        if (sel.match(/^#[\w]+$/)) {
            rc = top.getElementById(sel.substr(1));
            rc = (rc?[rc]:[]);
        } else if (top.querySelectorAll)
            rc = top.querySelectorAll(sel);
        else if (top.getElementsByClassName) {
            if (sel.substr(0,1) === '.')
                rc = top.getElementsByClassName(sel.substr(1));
            else
                rc = top.getElementsByTagName(sel);
        }
        return rc;
    },
    
    query1: function(sel, top) {
        var rc = jsi.query1(sel, top);
        if (rc && rc.length)
            return rc[0];
        puts('LOOKUP FAILURE: '+sel+' '+top);
        return null;
    },
    onload: function(f) {
        onloadFunc = f;
    },
    DoOnload: function(f) {
        if (srcCnt>0) {
            puts("waiting for src");
            setTimeout(jsi.DoOnload, 1000);
            return;
        }
        if (onloadFunc)
            onloadFunc();
    }

};

var jsi = new Jsi();
win['Jsi'] = win['$jsi'] = jsi;
win['$jsig']= jsi.Chk;

if (typeof win['$'] === 'undefined')
    win['$'] = jsi.query;

if (typeof win['$$'] === 'undefined')
    win['$$'] = jsi.query1;

if (typeof win['puts'] === 'undefined')
    win['puts'] = console.log.bind(console);
    

puts("Starting jsiweb...");

//eval.call({}, 'function foo() { puts("foo");}');

document.addEventListener('DOMContentLoaded', function() {
    jsi.DoOnload();
}, false);

}());