-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathshim.js
More file actions
1216 lines (1055 loc) · 42.6 KB
/
shim.js
File metadata and controls
1216 lines (1055 loc) · 42.6 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
// LATEST OFFICIAL DATASHELL SHIM
/******************************************************************************
LOAD_CONFIG
******************************************************************************/
function deepfreeze (o, cryo = true) {
const keys = Object.keys(o) // Object.getOwnPropertyNames(obj)
for (const key of keys) {
const val = o[key]
if (typeof val == 'object' && val !== null) deepfreeze(val, cryo)
}
if (cryo) {
const p = o.__proto__
if (typeof p == 'object' && p !== null) deepfreeze(p, cryo)
}
return Object.freeze(o)
}
async function load_config (document, api) {
const { user_href, page_href, shim_href } = await extract(document, api)
const delimiter = `this.open ? document.body.append(Object.assign(document.createElement('script'), { src })) : importScripts(src)`
const source = await (await fetch(page_href)).text()
const lines = source.split(delimiter)
if (lines.length < 2) throw new Error(`invalid "${page_href}"
The following line of code is missing, but expected to load the shim:
${delimiter}
copy & paste code line above to ensure correctness.
\`src\` can be defined before that line and any custom system code after it.
`)
const system = lines[1].trim()
if (system) {}
const user_url = url(user_href)
const user_env = parse(user_url.search)
const user_arg = parse(user_url.hash.slice(1))
const page_url = url(page_href)
const page_env = parse(page_url.search)
const page_arg = parse(page_url.hash.slice(1))
const shim_url = url(shim_href)
const shim_env = parse(shim_url.search)
const shim_arg = parse(shim_url.hash.slice(1))
const config = {
user: { url: user_url, env: user_env, arg: user_arg },
page: { url: page_url, env: page_env, arg: page_arg },
shim: { url: shim_url, env: shim_env, arg: shim_arg },
}
return config
function parse (querystring) {
const entries = new URLSearchParams(querystring).entries()
return Object.fromEntries(entries)
}
function url (url) {
const {
ancestorOrigins, hash, host, hostname, href,
origin, pathname, port, protocol, search
} = new URL(url)
return {
toString: () => href,
ancestorOrigins, hash, host, hostname, href,
origin, pathname, port, protocol, search
}
}
async function extract (document, run) {
const { currentScript: { src: shim_href }, location } = document
const user_href = location.href
const srcdoc = (await (await fetch(user_href, { cache: 'no-store' }))
.text()).replaceAll('<script', '<script_')
.replaceAll('script>', '_script>')
const iframe = Object.assign(document.createElement('iframe'), {
sandbox: 'allow-same-origin', srcdoc
})
const ready = new Promise(ok => iframe.onload = ok)
run('load', iframe)
const idoc = (await ready).currentTarget.contentWindow.document
const [meta, link] = idoc.head.children
const [charset, ...headattribs] = [...meta.attributes]
const [rel, href, ...linkattribs] = [...link.attributes]
const [script] = idoc.body.children
const [src, ...scriptattribs] = [...script.attributes]
const invalid = [
idoc.doctype.name !== 'html',
idoc.doctype.nodeType !== 10,
idoc.documentElement.children.length !== 2,
[...idoc.documentElement.attributes].length !== 0,
[...idoc.head.attributes].length !== 0,
idoc.head.children.length !== 2,
headattribs.length !== 0,
linkattribs.length !== 0,
charset.name !== 'charset',
charset.value !== 'utf-8',
rel.name !== 'rel',
rel.value !== 'icon',
href.name !== 'href',
href.value !== 'data:,',
[...idoc.body.attributes].length !== 0,
idoc.body.children.length !== 1,
scriptattribs.length !== 0,
src.name !== 'src',
].some(Boolean)
if (invalid) return run('fail', new Error(`invalid "index.html" shim, make sure it looks like:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><link rel="icon" href="data:,"></head>
<body><script src="index.js?...#..."></script></body>
</html>
copy & paste html above to ensure correctness.
\`?...#...\` can be used for configuratoin.
`))
const page_href = new URL(src.value, user_href).href
return { user_href, page_href, shim_href }
}
}
/*****************************************************************************/
globalThis.top ? globalThis === globalThis.top ? renderer() : iframe() : sewo()
/******************************************************************************
IFRAME
******************************************************************************/
function iframe () {
onmessage = e => eval(e.data)
console.log('[iwin]')
}
/******************************************************************************
SEWO
******************************************************************************/
function sewo () {
console.log('[sewo]', '@TODO: support service worker for offline first')
}
/******************************************************************************
BOOTLOAD
******************************************************************************/
async function renderer () {
const { body, defaultView: { navigator } } = document
const title = '⬡js'
const style = `background-color:black; color:mediumseagreen; font-family:mono;`
document.title = title
body.style = style
const on = { load, fail }
function load (dom) { body.append(dom) }
function fail (error) { // @TODO: use proper reporter!
console.error(error.message)
body.innerHTML = `<pre>${error.message}</pre>`
throw error
}
function api (type, data) {
console.log(`{${type}}`)
const cmd = on[type]
if (cmd) cmd(data)
else fail(new Error('unknown command', { cause: m }))
}
const config = await load_config(document, api)
console.log('[renderer]', config)
// @TODO: a flag to show boot menu and/or enter bios
// @TODO: a hotkey to enter bios at any time - maybe password protected
// const sewo = await navigator.serviceWorker.register(config.page.url)
// system version
const system_version = config.user.version || config.shim.version // vs. default system
// system params
// 1. define system in url
// 2. define system at end of file
// 3. use default datashell system
// 1. enduser: user config (location.href)
// 2. dev ops: html+boot url config -> default boot app and devops config
// can only validate kernel config if i have kernel versions and params?
// can only validate system cobfug uf u gave ststen versions and params?
const kernel_url = new URL('./', config.shim.url).href
const system_url = new URL('bundle.js', config.page.url).href
const [code, drive_json] = await Promise.all([
load_system(system_url),
load_kernel_versions(kernel_url, api),
])
// 3. coredev: shim code + shim html & versions json
// 4. enduser: localStorage
LESEZEICHEN: `what is needed to validate conf?`
const versions = JSON.parse(drive_json)
const conf = validate_conf(config, versions)
const v = conf.user.arg.version
const pack = versions[''][v]
// const pack = shim.versions[user_arg.version] || get_pack()
const old_conf = {
pack,
shim_env: config.shim.env,
shim_arg: config.shim.arg,
page_env: config.page.env,
page_arg: config.page.arg,
user_env: config.user.env,
user_arg: config.user.arg,
}
const script = document.createElement('script')
// @TODO: maybe create blobURL instead!
script.textContent = wrap(code, JSON.stringify(old_conf), drive_json)
body.replaceChildren(script) //@TODO: removes iframe though...
/***************************************************************************/
return
/****************************************************************************
LOAD_KERNEL_VERSIONS
****************************************************************************/
async function load_kernel_versions (src, run) {
const iframe = Object.assign(document.createElement('iframe'), { src })
const ready = new Promise(ok => iframe.onload = ok)
run('load', iframe)
await ready
const iwin = iframe.contentWindow
const { port1, port2 } = new MessageChannel()
const promise = new Promise(ok => port1.onmessage = e => port1.onmessage = ok(e.data))
// @TODO: think about etags
// @TODO: think about timeout reject
// @TODO:
// if (status === 404) return body.innerHTML = `GET ${drive_json} 404 (Not Found)`
iwin.postMessage(`
{
onmessage = void 0
document.body.style = "background-color:fuchsia;"
const [port] = e.ports
const url = new URL('./drive.json', location)
fetch(url, { cache: 'no-store' }).then(async response => {
const json = await response.text()
port.postMessage(json)
})
}
`, src, [port2])
return promise
}
/****************************************************************************
LOAD_SYSTEM
****************************************************************************/
async function load_system (code_href) {
const req = async res => ({ status: res.status, text: await res.text() })
const { status, text } = await fetch(code_href, { cache: 'no-store' }).then(req)
if (status === 404) return body.innerHTML = `GET ${code_href} 404 (Not Found)`
// @TODO handle etag as well
// @TODO: handle fetch timeout and reject on 404
return text
}
/****************************************************************************
PROMPT_UI
****************************************************************************/
function prompt_ui (v, wmax = 57, hmax = 17) {
// Data Application Terminal
// Data Access Terminal
// Distributed Application Terminal
// DataShell Application Terminal
// DataShell Access Terminal
const aliases = Object.keys(v).filter(Boolean)
const resolve = Object.fromEntries(aliases.map(k => [v[k], k]))
const numbers = Object.keys(v[''])
const version_list = numbers.sort().reverse().map(n => resolve[n] ? `${n} (${resolve[n]})` : n)
const current = localStorage['/conf/user/arg/version']
const ending = `(current version: ${current || ''})`
const choose = format_line(['➤ choose version:', '', ending])
// const show = { ask:[choose, box].join('\n') }
// const status = {
// invalid: version => `⛔ invalid version: ${version}`,
// release: version => `📦 new version available: ${version}`
// }
const all = v['']
return bui
function bui (version = v.stable, type = '', txt = '', pack = all[version]) { // get_pack
const lines = view(type.length ? `⛔ ${type}:` : '', txt, choose, version_list.join(', '))
if (lines.length > 11) console.warn(`⛔ overlay view has more than 17 lines`, lines.length, '\n', lines.join('\n'))
if (lines.length > 24) console.error(`⛔ overlay view has more than 24 lines`, lines.length, '\n', lines.join('\n'))
const prompt_text = lines.join('\n')
// const name = 'invalid'
// status[name](version) || ''
while (!pack) {
version = prompt(prompt_text, v.stable)
if (version === null) break
version = Number.isInteger(Number(version)) ? version : v[version]
pack = all[version]
}
return version
}
function view (issue, description, prompt, options) {
return [issue, ...format_box(description), '', prompt, ...format_box(options) ]
}
function format_line (PARTS, max = wmax, len = 0, line = []) {
const LINES = []
for (let part of PARTS) {
const plen = part.length
if (len + plen > max) {
if (len) LINES.push(line)
if (plen > max) LINES.push(...split(part, max).map(p => [p]))
;[len, line] = plen > max ? [0, []] : [plen, [part]]
} else {
len += plen
line.push(part)
}
}
if (len) LINES.push(line)
return LINES.map(line => {
const sizes = line.map(s => Number(s.length || 0))
const width = sizes.reduce((s, n) => s + n, 0)
const pad = (max - width) / sizes.filter(c => !c).length
return line.map(s => s || ' '.repeat(pad)).join('')
})
}
function split (str, max = 54, lines = [], split, c) {
while (str.length > max) {
split = str.lastIndexOf(' ', max)
;[split, c] = split === -1 ? [max, 0] : [split, 1]
lines.push(str.slice(0, split).padEnd(max, ' '))
str = str.slice(split + c)
}
return str.length ? lines.concat(str.padEnd(max, ' ')) : lines
}
function format_box (txt) {
txt = split(txt)
const width = Math.max(...txt.map(s => s.length))
const line = '─'.repeat(width)
const paddedLines = txt.map(line => `│ ${line}${' '.repeat(width - line.length)} │`)
const header = `┌─${line}─┐`
const footer = `└─${line}─┘`
return [header, ...paddedLines, footer]
}
}
/****************************************************************************
GET_PACK
****************************************************************************/
function validate_version (version, v, fix) {
do {
const defined = Number.isInteger(Number(version)) ? version : v[version]
const isvalid = v[''][defined]
if (isvalid) return defined
if (!fix) throw new Error(`invalid version: "${version}"`)
try {
version = fix(version)
} catch (error) {
// @TODO: use proper reporter!
console.error(error.message)
document.body.innerHTML = `<pre>${error.message}</pre>`
throw error
}
} while(true)
}
function validate_shim_versions (versions) {
console.warn('@TODO: validate versions')
// assume valid v (=shim versions) // @TODO: fix
// @TODO: make sure config is valid to avoid infinite prompt loop
// e.g. no valid option in conf problem for version!!!!
const keys = Object.keys(versions)
// @TODO: validate
const invalid = false
if (invalid) throw new Error('`drive.json` is invalid')
return versions
}
function validate_conf (conf, versions, decided) {
const v = validate_shim_versions(versions)
const USER = {
ask_version: prompt_ui(v)
}
const userver = conf.user.arg.version && validate_version(conf.user.arg.version, v, function fix (version) {
const type = 'user'
const txt = `invalid ${type} set version "${version}", If version param is provided it must be valid`
version = USER.ask_version(version, `invalid`, txt)
if (version === null) throw new Error(txt, { cause: new Error('abort') })
return version
})
// valid userver or userver === undefined (if not aborted)
const loadver = localStorage['/conf/user/arg/version'] && validate_version(localStorage['/conf/user/arg/version'] || 6, v, function fix (version) {
const txt = `corrupted cached version "${version}". Try to repair by choosing valid shim version`
if (userver) return (console.warn(txt), userver)
version = USER.ask_version(version, 'invalid', txt)
if (version === null) throw new Error(txt, { cause: new Error('abort') })
return version
})
// valid loadver or loadver === undefined (if not aborted)
const shimver = validate_version(conf.shim.env.version || v.stable, v, function fix (version) {
if (userver || loadver) return (console.warn(txt), userver || loadver)
const type = 'shim'
const txt = `invalid ${type} set version "${version}"`
version = USER.ask_version(version, 'invalid', txt) // more prompt: adapt prompt to share previous wrong selection
if (version === null) throw new Error(txt, { cause: new Error('abort') })
return version
})
// valid shimver (if not aborted)
const version = userver || loadver || shimver // @NOTE: here a version WILL exist, otherwise it exited with error already!
console.log(version, { userver, shimver, loadver })
// uservar > loadver > shimver
;{ // UPDATE CONF:
// @TODO: switch updates to enable using `conf`
// conf.user.arg.version = localStorage['/conf/user/arg/version'] = version
// location.hash = new URLSearchParams(conf.user.arg)
config.user.arg.version = localStorage['/conf/user/arg/version'] = version
// @TODO: maybe always remove url param set version to use user specified instead only when set!
// @NOTE: security issue - what if user clicks a url somebody shared to update or prompt user for version?
// @TODO: should we uncomment the line below to update url params or not?
// location.hash = new URLSearchParams(config.user.arg)
location.hash = ''
}
// @TODO: what if (re) load an an update is available????
// if (latest_cached_number_or_label < latest_number_or_label) {} // @TODO: update avaliable??
return deepfreeze(config)
}
/****************************************************************************
WRAP
****************************************************************************/
function wrap (code, config, versions_json, map) {
var mark = 'return o}return r})()'
const smap = '//# sourceMappingURL=data:'
const mime = 'application/json;charset=utf-8;base64,'
const parts = code.slice(0, -1).split(smap)
if (parts.length > 1) map = parts.pop()
if (map && !map.startsWith(mime)) parts.push(map)
code = parts.join(smap).slice(0, -1)
code = code.replace(mark, `${mark}(...await (F.bind(${config}, ${versions_json})`)
code = `void (async F => {${code}))})(${init})`
if (map) code = code + `\n${smap}${mime}${map}`
return code
async function init (versions, ...args) {
//# sourceMappingURL=init.js
// const usopen = '00af49'
// const color1 = '41b557'
// const color2 = '63bd58'
// const color3 = 'a8cf80'
// const color4 = '2b9d48'
// const color5 = '2ca449'
const color6 = '53bc67'
const link = document.createElement('link')
link.setAttribute('rel', 'icon')
link.setAttribute('href', `data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90" fill="%23${color6}">⬢</text></svg>`)
document.head.append(link)
document.title = '⬢js'
const {
pack,
shim_env, shim_arg, page_env, page_arg, user_env, user_arg
} = this
console.log(`%c⬢js:v${user_arg.version}`, `color: #${color6}`, {
versions,
pack,
shim_env, shim_arg, page_env, page_arg, user_env, user_arg
})
const bindmap = new Map()
const USE_LOCAL = 'dev' in user_arg
const HELPER_MODULES = ['io', 'localdb', 'STATE'] // @TODO: localdb/io for userland too?
clear_db_on_file_change()
const [source_cache, module_cache] = args
await patch_cache_in_browser(source_cache, module_cache)
document.onvisibilitychange = _ => document.hidden && sessionStorage.setItem('last_item', Date.now())
console.log('****************************')
console.log('[INIT]')
console.log('****************************')
return args
function bind (self, name) {
const f = self[name]
const F = f.bind(self)
if (bindmap.get(f)) return bindmap.get(f)
bindmap.set(f, F)
const valid = x => !['caller', 'callee', 'arguments'].includes(x)
const names = Object.getOwnPropertyNames(f).filter(valid)
for (const key of names) {
F[key] = typeof f[key] === 'function' ? bind(f, key) : f[key]
}
return F
}
function sandbox (name, module) {
const module_source = `return ${module}`
const G = globalThis
const glob = {}
const names = Object.getOwnPropertyNames(G)
for (const key of names) {
glob[key] = typeof G[key] === 'function' ? bind(G, key) : G[key]
}
glob.console = { // @TODO: should be removed to enable logging in userland
log: (...args) => {},
warn: (...args) => {},
error: console.error.bind(console),
}
const boxed_module = load(name, module_source, glob)
const boxed_source = `${boxed_module}`
// console.log('%cSANDBOX', 'color: orange;', { name, module_source, boxed_source })
return boxed_module
}
function load_cjs (label = '(anon)', source, require) {
const f = load(label, `return function (require, module, exports) { ${source} }`)
// console.log('%cCJS', 'color: yellow;', { label, source, f: ''+f })
const exports = {}
const module = { exports }
// const f = new Function('module', 'require', source)
console.log('%cLOAD', 'color: yellow;', label)
f(require, module, exports)
return module.exports
}
function load (label = '(anon)', source, sdk) {
const node = { id: null }
if (!sdk) {
sdk = {}
sdk.Set = Set
sdk.window = window
sdk.Boolean = Boolean
sdk.localStorage = localStorage
sdk.JSON = JSON
sdk.Object = Object
sdk.Function = Function
sdk.Math = Math
sdk.Error = Error
sdk.console = console
sdk.undefined = undefined
sdk.structuredClone = structuredClone.bind(globalThis)
sdk.isNaN = isNaN
sdk.Number = Number
sdk.Symbol = Symbol
sdk.Promise = Promise
sdk.fetch = fetch.bind(window)
// ------------------------------
sdk.AsyncFunction = `${(async () => {}).constructor}`
// ------------------------------
sdk.node = node
// ------------------------------
sdk.require = null // @TODO: fix this
sdk.top = null // @TODO: fix this
// ------------------------------
}
// @TODO: use source with `return ...` to make proper use of `evaluate()
const opts = { label, source, sdk }
return evaluate(opts)
}
function clear_db_on_file_change () {
const last_item = sessionStorage.getItem('last_item')
const now = Date.now()
const is_reload = performance.getEntriesByType("navigation")[0]?.type === "reload"
if (is_reload && !(last_item && (now - last_item) < 200)) localStorage.clear()
sessionStorage.removeItem('last_item')
}
async function patch_cache_in_browser (source_cache, module_cache) {
const prefix = 'https://raw.githubusercontent.com/playproject-io/datashell/'
///////////////////////////////////////////////////////////////////////////////
// const dev = user_arg.dev
// const USE_LOCAL = true
// const dev = 'http://localhost:9999/lib/node_modules/'
const state_url = new URL(USE_LOCAL ? dev + 'STATE.js' : prefix + pack['STATE'])
const localdb_url = new URL(USE_LOCAL ? dev + 'localdb.js' : prefix + pack['localdb'])
const io_url = new URL(USE_LOCAL ? dev + 'io.js' : prefix + pack['io'])
// @TODO: make iframe based cors compatible temporary `STATE` module fetch possible!
// @TODO: think about whether that makes sense in the long run too or not!
///////////////////////////////////////////////////////////////////////////////
const [STATE_JS, localdb_js, io_js] = await Promise.all([
fetch(state_url, { cache: 'no-store' }).then(res => res.text()),
fetch(localdb_url, { cache: 'no-store' }).then(res => res.text()),
fetch(io_url, { cache: 'no-store' }).then(res => res.text())
]).then(([state_source, localdb_source, io_source]) => {
const dependencies = {
localdb: load_cjs('STATE/localdb', localdb_source),
io: load_cjs('STATE/io', io_source)
}
const STATE_JS = load_cjs('STATE', state_source, (dependency) => dependencies[dependency])
return [STATE_JS, dependencies.localdb, dependencies.io]
})
const meta = { modulepath: ['page'], paths: {} }
for (const key of Object.keys(source_cache)) {
const source = source_cache[key]
source[0] = sandbox(key, source[0])
const [module, names] = source
const dependencies = names || {}
source_cache[key][0] = patch(module, dependencies, meta)
}
function patch (module, dependencies, meta) {
const MAP = {}
for (const [name, number] of Object.entries(dependencies)) MAP[name] = number
return (...args) => {
const original_require = args[0]
require.cache = module_cache
require.resolve = resolve
args[0] = require
return module(...args)
function require (name) {
const identifier = resolve(name)
if (HELPER_MODULES.some(suffix => name.endsWith(suffix))) {
const modulepath = meta.modulepath.join('>')
let original_export
if (name.endsWith('STATE')) original_export = STATE_JS
else if (name.endsWith('localdb')) original_export = localdb_js
else if (name.endsWith('io')) original_export = io_js
// else {
// console.log('%cHELPER_MODULES', 'color: red;', name)
// original_export = require.cache[identifier] || (require.cache[identifier] = original_require(name))
// }
const exports = (...args) => original_export(...args, modulepath, Object.keys(dependencies))
return exports
} else {
console.log('%cMODULES', 'color: green;', name)
// Clear cache for non-STATE and non-io modules
delete require.cache[identifier]
const counter = meta.modulepath.concat(name).join('>')
if (!meta.paths[counter]) meta.paths[counter] = 0
const localid = `${name}${meta.paths[counter] ? '#' + meta.paths[counter] : ''}`
meta.paths[counter]++
meta.modulepath.push(localid.replace(/^\.\+/, '').replace('>', ','))
const exports = original_require(name)
meta.modulepath.pop(name)
return exports
}
}
}
function resolve (name) { return MAP[name] }
}
}
}
}
}
/////////////////////////////////////////////////////////////////////
/* PROXy CONCEPT SANDBOX
// proxy-sandbox.js
function createProxySandbox(endowments = {}) {
// copy and freeze endowments so guest can't mutate host objects
const safeEndow = {};
for (const k of Object.keys(endowments)) {
safeEndow[k] = endowments[k];
Object.freeze(safeEndow[k]);
}
Object.freeze(safeEndow);
const handler = {
// Only report names that are actually present in the endowments.
// This is what makes `typeof missingName` return "undefined" and
// unqualified `missingName` produce ReferenceError semantics.
has(target, prop) {
// treat Symbol.unscopables and internals conservatively:
if (prop === Symbol.unscopables) return false;
return Object.prototype.hasOwnProperty.call(safeEndow, prop);
},
get(target, prop, receiver) {
if (prop === Symbol.unscopables) return;
if (Object.prototype.hasOwnProperty.call(safeEndow, prop)) {
return safeEndow[prop];
}
// If get is called for a non-existent property, throw like an undefined global read
// would in strict-mode code that resolves in the env. This keeps semantics strict-ish.
throw new ReferenceError(`${String(prop)} is not defined`);
},
// optional: block property creation and assignment unless allowed
set(target, prop, value) {
if (!Object.prototype.hasOwnProperty.call(safeEndow, prop)) {
// writing to unknown global: mimic strict-mode behavior (throw)
throw new ReferenceError(`${String(prop)} is not defined`);
}
// if present and we allowed mutability, you could update; here we forbid
return false; // indicate failure to set (in strict mode this throws)
},
// prevent enumeration from leaking internals
ownKeys() {
return Object.keys(safeEndow);
},
getOwnPropertyDescriptor(target, prop) {
if (Object.prototype.hasOwnProperty.call(safeEndow, prop)) {
return {
configurable: false,
enumerable: true,
writable: false,
value: safeEndow[prop],
};
}
return undefined;
}
};
const proxy = new Proxy({}, handler);
// Build a non-strict outer function that uses `with(proxy)` and invokes a strict IIFE.
// The outer function must be non-strict to allow `with`.
function run(src) {
// We intentionally avoid giving the outer function access to anything else.
const wrapper = new Function('sandboxProxy', `
with (sandboxProxy) {
return (function() { "use strict";\n${src}\n})()
}
`);
return wrapper(proxy);
}
return { run, proxy, endowments: safeEndow };
}
// Example:
const sb = createProxySandbox({ a: 1, Math });
console.log(sb.run('a + 2')); // 3
try { sb.run('b + 1'); } catch (e) { console.log(e.name, e.message); } // ReferenceError b is not defined
console.log(sb.run('typeof b')); // "undefined"
// @TODO: Implementing temporal dead zone (TDZ) or other lexically-scoped behaviors precisely is hard with this approach.
// @TODO: time limits in iframe to abort
// Consider running the compiled function in a separate process, worker, or real VM for defense-in-depth and to allow CPU/time limits.
// QUESTION:
// 1. strict mode cant define vars on global implicitly like e.g. `foo = 123` in sloppy mode can
// 2. can i have `x.run('const x = 123')` followed by `x.run('console.log(x)')` ?
*/
function evaluate ({ label, source, sdk = {} } = {}) {
// ------------------------------
const name = label || sdk.name || '(anon)' // @TODO: increase counter maybe
if (typeof source === 'function') source = `return (${source})()`
Object.assign(sdk, { globalThis: sdk })
const global = new Proxy(sdk, {
// @TODO: try to catch any proxy trap errors and modify stack trace to exclude proxy
// @TODO: consider full membrane!
get (sdk, k) {
if (k === Symbol.unscopables) return
if (Object.prototype.hasOwnProperty.call(sdk, k)) {
const value = sdk[k] === sdk ? global : sdk[k]
var new_value
if (typeof value === 'function') {
new_value = value.bind(sdk)
const names = Object.getOwnPropertyNames(value).filter(x => !['caller', 'callee', 'arguments'].includes(x))
for (const name of names) new_value[name] = value[name]
}
else new_value = value
return new_value
}
// If get is called for a non-existent property, throw like an undefined global read
// would in strict-mode code that resolves in the env. This keeps semantics strict-ish.
throw new ReferenceError(`${String(k)} is not defined`)
// throw new Error(`Uncaught ReferenceError: ${k} is not defined`)
},
put (sdk, k, v) { return sdk[k] = v === sdk ? global : v },
has (sdk, k) {
if (k === Symbol.unscopables) return false
return Object.prototype.hasOwnProperty.call(sdk, k)
},
deleteProperty (sdk, k) { return delete sdk[k] },
ownKeys(sdk) { return Object.keys(sdk) },
isExtensible (sdk) { return Object.isExtensible(sdk) },
setPrototypeOf (sdk, p) { return Reflect.setPrototypeOf(sdk, p) },
getPrototypeOf (sdk) { return Reflect.getPrototypeOf(sdk) },
// apply (sdk, self, args) { return Reflect.apply(sdk, sefl, args) },
// construct (sdk, args, o) { return Reflect.construct(sdk, args, o) },
defineProperty (sdk, k, descriptor) {
Object.defineProperty(sdk, k, descriptor)
return global
},
getOwnPropertyDescriptor (sdk, k) {
return Object.getOwnPropertyDescriptor(sdk, k)
},
preventExtension (sdk) {
Object.preventExtensions(sdk)
return true
},
})
// const run = new Function(`return async node => { ${source} }`)()
const run = new Function('global', `//# sourceURL=${name}
with (global) return (function () { "use strict";\n${source};\n})()`)
// ------------------------------
// const input_drives = [drive1, drive2, drive3]
// launch or work on a task worked on by a person or machine:
const exports = run(global) // = evaluate or execute
return exports
}
/* ALTERNATIVE:
function make_box (code = '', context = {}, ended = false) {
code = typeof code === 'function' ? `(${code})()` : code
const makegen = (0, eval)(`(function make (global = {}) {
with (global) return (function * () {
'use strict'
console.log(123, global, a)
;${code};
while (true) eval(yield)
})()
})`)
const gen = makegen(context)
gen.next(code)
return { run, end }
function end (src) {
if (ended) return
ended = true
const { value, done } = gen.return(src)
console.log({ value, done })
return
}
function run (src) {
if (ended) return
const { value, done } = gen.next(src)
if (done) ended = true
return value
}
}
const context = { a: 123, b: 321 }
const box = make_box('console.log("start"); const c = 321', context)
box.run('console.log(a)'); // 123
box.run('var b = 321'); // creates b in context
box.run('console.log(a + c)'); // 444
function create_context_function_template(eval_string, context) {
return `
return function (context) {
"use strict";
${Object.keys(context).length > 0
? `let ${Object.keys(context).map((key) => ` ${key} = context['${key}']`)};`
: ``
}
return ${eval_string};
}
`
}
function make_context_evaluator(eval_string, context) {
let template = create_context_function_template(eval_string, context)
let functor = Function(template)
return functor()
}
let context = {b: (a, b) => console.log(a, b)}
let evaluator = make_context_evaluator("b('foo', 'bar')", context)
let result = evaluator(context)
function eval_like(text, context={}) {
let evaluator = make_context_evaluator(text, context)
return evaluator(context)
}
eval_like("fun + 2", {fun: 1})
eval_like("() => fun", {fun: 2})()
///////////
function evalInContext(js, context) {
return function(str){
return eval(str);
}.call(context, ' with(this) { ' + js + ' } ');
}
var evalWithinContext = function(context, code) {
(function(code) { eval(code); }).apply(context, [code]);
}
evalWithinContext(anyContext, anyString)
/////////////////
function makeEvalContext (declarations) {
eval(declarations);
return function (str) { eval(str); }
}
eval1 = makeEvalContext ("var x;");
eval2 = makeEvalContext ("var x;");
eval1("x = 'first context';");
eval2("x = 'second context';");
eval1("window.alert(x);");
eval2("window.alert(x);");
//////////////////
function execInContext(code, context) {
return Function(...Object.keys(context), 'return '+ code (...Object.values(context));
}
//////////////////
class ScopedEval {
constructor(scope) {
this.scope = scope;
}
eval(__script) {
return new Function(...Object.keys(this.scope),`
return eval(
'"use strict";delete this.__script;'
+ this.__script
);
`.replace(/[\n\t]| +/g,'')
).bind({__script})(...Object.values(this.scope));
}
}
// VS
class ScopedEval {
constructor(scope) {
this.scope = scope;
}
eval(__script) {
return new Function(...Object.keys(this.scope),`
return eval(
'"use strict";delete this.__script;'
+ this.__script
);
`.replace(/[\n\t]| +/g,'')
).bind({__script})(...Object.values(this.scope));
}
}
const context = {
hi: 12,
x: () => 'this is x',
get xGet() {
return 'this is the xGet getter'
}
};
const x = new ScopedEval(context)
console.log(x.eval('"hi = " + hi'));
console.log(x.eval(`
let k = x();
"x() returns " + k
`));
console.log(x.eval('xGet'));
x.scope.someId = 42;
console.log(x.eval('(() => someId)()'))
// VS
// Source - https://stackoverflow.com/a
// Posted by joshhemphill, modified by community. See post 'Timeline' for change history
// Retrieved 2025-12-03, License - CC BY-SA 4.0
class ScopedEval {
constructor(scope) {
this.scope = scope;
}
eval (__script) {
return new Function(...Object.keys(this.scope), `
return eval(
'"use strict";delete this.__script;'
+ this.__script
);
`.replace(/\t/, ''))