-
Notifications
You must be signed in to change notification settings - Fork 0
/
t348.mjs
9050 lines (8240 loc) · 314 KB
/
t348.mjs
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
// https://github.com/wizzard0/t348-loader CHANGELOG
// MIT license. Includes code from https://github.com/alangpierce/sucrase and https://github.com/paulmillr/noble-hashes
// p4804: url in 404 msg
// p3702: node20 support
// p3217: public release
// p3115: resolve "./something" -> "./something.ts" too
// p2a22: path in syntax error message
// p2808: log caching events
// p2723: don't nag unknownCommand (require t348 prefix for arg0)
// p2720: node18 support
// p2628: correct sourceURL in browser
// p2621: handle empty publish urls
// p2423: browser support for non-t348 .js/.ts imports;
// ignore commented out imports
// maybe fix relative URLs for path imports
// fix loading t348 urns from different base paths. browser, node...
// p2421: browser support, omg. p2422: fixes.
// p2411: correct stack traces and noEmit!
// p2410: typescript! (via sucrase)
// added notes p2401, package.json skip 1220
// copied p2321, fix 1634, refactor 1656
//
// important: keep this single-file because this is a bootstrapper
// see usage BELOW
//
// UNSUPPORTED: CommonJS, import cycles
// detect cycles: madge --warning --circular --extensions ts,js --image deps-circular.svg <ENTRYPOINT/FOLDER>
// https://github.com/pahen/madge
/* USAGE
download everything in ./t348repo if T348CACHE, logs if TEST/DEBUG/VERBOSE is set
"via348": "node --experimental-loader=./t348.mjs index.js param1",
"cache348": "T348CACHE=1 DEBUG=1 node --experimental-loader=./t348.mjs index.js param1",
upload file (idempotent, can also re-upload from repo though this will kill meta filename)
node ./t348.mjs t348pack something.js
change local repo in package.json: use .ts extension if you need IDE to eat typescript
"type": "module",
"t348": { "repo": "./t348repo/t0$HASH.js" },
assumes node v16/v18. use mjs extension if no package.json present.
BROWSER USAGE:
note: only 1 script tag with type="text/typescript" is supported
default global url is $T348_GLOBAL_REPO ($HASH will be replaced with h48)
TRACE and T348_GLOBAL_REPO can be set in localStorage as t348_trace, t348_global_repo etc.
<head>
<script type="module" src="https://website.com/path/t0lYxZJvli.js#t348"></script>
<!-- OR -->
<script src="t348.mjs" type="module" data-global-repo="./t348repo/t0$HASH.ts"></script>
<script src="app.js" type="text/typescript"> (OR CODE WITH NEWLINES HERE) </script>
</head>
PLAN
+ read t348repo folder from package.json
+ try repoPath, then ~/.t348repo/v1, then hash-store
+ cache in ~/.t348repo/v1 (implicit)
- and t348repo-folder (explicit)
+ t348pack subcommand (publishes normalized to './t0aaa1bbb2.js')
+ pack to ~/.t348repo/v1/t0aaa1bbb2.js
+ pack to hash-store
- config USE_HASH_STORE, USE_MACHINE, T348_GLOBAL_REPO etc
- pack from browser
+ boot from browser
- fix import '" regexes
- redesign so .ts browser import won't require js>ts 404
*/
let isBrowser = !!(globalThis.window && globalThis.document);
let importedModules; // don't access directly, use imports()
let importStarted;
function imports(){
if(!importedModules){throw new Error('performNodeImports() must be called first')}
return importedModules;
}
function findBrowserEnv(){
let goodName = name => name.substring(5).toUpperCase().replace('-','_')
let selfTags = document.querySelectorAll('script[type="module"][src*="t348"]');
if(selfTags.length!==1){throw new Error(`T348: Expected exactly one script tag with type="module" src='...t348...' but found ${selfTags.length}`);}
let moduleAttrs = [...selfTags[0].attributes].filter(x=>x.name.startsWith('data-')).map(x=>[goodName(x.name),x.value]);
let storageAttrs = Object.entries(localStorage).filter(x=>x[0].match(/^t348[-_].+/i)).map(x=>[goodName(x[0]),x[1]]);
return Object.fromEntries([...moduleAttrs,...storageAttrs]);
}
async function performNodeImports(){
//console.log({performNodeImports:true})
importStarted=true;
//console.warn({T348:1,isBrowser,performNodeImports:!!importedModules}) // direct log as conSole is still dummy at this point
let modules;
if(isBrowser){
let scriptTags = document.querySelectorAll('script[type="text/typescript"]');
if(scriptTags.length!==1){throw new Error(`T348: Expected exactly one script tag with type="text/typescript" but found ${scriptTags.length}`);}
let appEntryPoint = scriptTags[0].src || scriptTags[0].innerHTML;
modules = ({
env:{ /* add overrides here if you fancy */
'IS_BROWSER':'1',
...findBrowserEnv(),
},
fs:{
readFileSync:(path) => {let e = new Error('no files exist in the browser: '+path); e.code = 'ENOENT';throw e;},
writeFileSync:(path,data) => {xlog({writeFileSync:path,ignored:1})},
},
argv:['browser',appEntryPoint,'t348run'],
})
}else {
let {get: secureGet, request: secureRequest} = await import('https');
let {get} = await import('http');
let fs = await import('fs');
let path = await import('path');
let {homedir} = await import('os');
modules = ({
get,
secureGet,
secureRequest,
fs,
path,
homedir,
env:globalThis.process?.env || {},
argv:globalThis.process?.argv || [],
});
}
let {TEST, DEBUG, VERBOSE, TRACE} = modules.env;
if (TEST || DEBUG || VERBOSE || TRACE) {conSole = console}
log({t348:'done imports',argv:modules.argv}) // todo remove this
importedModules = modules;
return modules;
}
let isT348spec = (url) => url.startsWith('https://') || url.startsWith('http://127.0.0.1') || h48FromUrl(url);
// logger
let id = x => x;
let conSole = {log: id};
let xlog = id; // one-letter disable
// log is enabled when modules are imported, so we don't access `process` global here.
let log = (...args) => {
conSole.log('T348', ...args);
return id;
}
// NODE LOADER API
let nodeNativeSpecifierRegex = /^[a-z0-9/-]+$/
let redirected = {}
function processResolveError(e, specifier, parentURL) {
// log({defaultResolveError: e,specifier,parentURL})
// try to replace .js with .ts
if (e.code !== 'ERR_MODULE_NOT_FOUND' || !specifier.match(/^\.|\.js$/)) {
log({defaultResolveError: e,specifier,parentURL})
throw e
}
// console.log({specifier,parentURL});
// attempt our own resolution
let urlObject = parentURL ? new URL(specifier, parentURL) : new URL(specifier);
let url = urlObject.href.replace(/(\.js)?$/, '.ts')
if (!redirected[url]) {log({redirectToTypeScript: url}); redirected[url] = true;}
return ({url})
}
// noinspection JSUnusedGlobalSymbols
export function resolve(specifier, context, defaultResolve) {
log({resolve:specifier});
const {parentURL = null} = context;
// Normally Node.js would error on specifiers starting with 'https://', so
// this hook intercepts them and converts them into absolute URLs to be
// passed along to the hooks below.
if (isT348spec(specifier)) {
let url = h48FromUrl(specifier)?buildGlobalUrl(h48FromUrl(specifier)):specifier;
return log({t348Direct: url})({url, shortCircuit:true});
}
if (parentURL && isT348spec(parentURL) && !specifier.match(nodeNativeSpecifierRegex)) {
log({specifier,parentURL,willCombine:true})
let url = new URL(specifier, parentURL).href
return log({t348Parent: url})({url, shortCircuit:true})
}
log({defaultResolve: specifier})
try {
let drr= defaultResolve(specifier, context, defaultResolve)
if(drr.then){
return drr.then(x=>x,e=>processResolveError(e,specifier,parentURL))
}else {
return drr
}
}catch(e){
return processResolveError(e, specifier, parentURL);
}
}
let importInProgress;
// noinspection JSUnusedGlobalSymbols
export function load(url, context, defaultLoad) {
//console.log({load:url});
// hits when loader is operational
if(!!importedModules){return loadImpl(url, context, defaultLoad)}
if(url.startsWith('node:')) {
//console.log({nodeDefaultLoad:url});
return defaultLoad(url, context, defaultLoad)
}
// if(!importInProgress){ // first hit
// importInProgress = performNodeImports();
// }
// otherwise
return importInProgress.then(()=>loadImpl(url, context, defaultLoad))
}
let _transpiler;
function getTranspiler(){
if(!_transpiler) {
let {env} = imports();
let {DISABLE_SUCRASE} = env;
_transpiler = DISABLE_SUCRASE ? id : (code, originalUrl) => `${transform(code, {
transforms: ["typescript"],
filePath: originalUrl,
disableESTransforms: true
}).code}
//# sourceURL=${originalUrl}
//# sourceURL=${originalUrl}`;
// one of them will get removed by the loader, second is at the end so line numbers match
// todo keep file paths where the blobs were originally loaded from, if available
}
return _transpiler;
}
export function loadImpl(url, context, defaultLoad) {
log({loadImpl:url});
let {fs} = imports();
let transpiler = getTranspiler();
if (!isT348spec(url) && !isBrowser) { // AND IF NODE ONLY
if(url.endsWith('.ts')){
let filePath = url.replace('file://',''); let code;
log({url,filePath, willTranspile:true});
try {
code = fs.readFileSync(filePath).toString() // force modules lol
} catch (e) {
if(e.code==='ENOENT'){
code = fs.readFileSync(filePath.replace(/\.js$/,'.ts')).toString() // force modules lol
}else{
throw e;
}
}
return ({format:'module', source: transpiler(code, url), shortCircuit: true})
}else {
log({defaultLoad: url});
return defaultLoad(url, context, defaultLoad)
}
}
// note we get here only if not h348. need to refactor this out
let hash = h48FromUrl(url);
if (hash) {return loadAndMaybeCache(hash, transpiler)}
log({t348UrlFetch: url})
// NOTE: cannot check without hash, maybe log warning? assumes ESM
return miniGetJsTs(url).then(code => ({format: 'module', source: transpiler(code, url), shortCircuit:true}))
}
// todo real ugly hack, need to redesign so we don't do 2x the requests
async function miniGetJsTs(url){
try {
return await miniGet(url);
}catch(e){
if(e.code==='ENOENT' && url.endsWith('.js')){
return await miniGet(url.replace(/\.js$/,'.ts'))
}else{
throw e;
}
}
}
// END NODE API
const fc = path => imports().fs.readFileSync(path).toString('utf-8');
let packageJsonData;
function packageJson() {
// todo search starting from jsPath
if (!packageJsonData) {packageJsonData = JSON.parse(fc('package.json'))}
return packageJsonData
}
let t348MetaRegex = /^\s*\/\*\s+t348meta:\s+({.*})\s+\*\/\s*$/
let t348MetaPlaceholder = "/* t348meta: $JSON */"
// PACK FUNCTION
export async function packModule(argv) {
let {fs,path}=imports();
// normalize module, put it to t348repo
let [node, index, arg0pack, jsPath] = argv; // prefix and suffix so that idea imports work
// let suffix = '.js'; if(jsPath.endsWith('.ts')) {suffix = '.ts'}
// TODO: hash request is without suffix but repo stores files with suffix > either make everything .ts or not.
let [hash, normalized] = normalizeModuleAndHash(fc(jsPath), './t0', '.js');
// insert source path + date... oops this means normalized must skip comments like these
// /* t348meta: {"name":file.js "date":"2020-01-01"} */ to be replaced with /* t348meta: {} */
let name = path.basename(jsPath);
let date = new Date().toISOString()
let all = [t348MetaPlaceholder.replace('$JSON', JSON.stringify({hash, name, date})), normalized].join('\n')
let pathInRepo;
try{
pathInRepo = repoPath(hash)
}catch (e){
if(e.code==='ENOENT'){console.warn({noPackageJsonFound:1})}else{throw e}
}
if(pathInRepo) { fs.writeFileSync(pathInRepo, all) }
fs.writeFileSync(machineRepoPath(hash), all)
await postT227HashStore(hash, all);
let exports = detectExports(all).join(', ');
console.info({
jsPath, pathInRepo, hash,
import: pathInRepo? `import {${exports}} from '${pathInRepo}'` : undefined,
global: `import {${exports}} from '${buildGlobalUrl(hash)}'`
})
}
function detectExports(source) {
// https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
// return list of exports, ignore default export and export {}
return [...source.matchAll(/export\s+(?:let|const|function|class)\s+(\w+)/g)].map(x=>x[1]);
}
// BROWSER LOADER
async function t348run(){
let {argv}=imports();
let [browser, index, arg0run] = argv;
log({t348run:index});
let session = {
getBlob: async (session, id)=>{
log({getBlob:id});
// TODO implement this lol
//nyi('getBlob');
let {format,source} =await loadImpl(id, null, (id, ctx, _) => err('no defaultLoad in the browser for id='+id+' ctx='+ctx))
return source;
}
} // todo
// fetch and transpile
let convertedObjectUrl = await reallyLoadIntoBlobURL(session, index)
// run
return import(convertedObjectUrl); // it should be sufficient to trigger import of the index module
// nope sadly we can't rely on dynamic import as it won't fire our hooks.
// and we must remap blobs after sucrase processing.
}
// copied from t352
async function entryPoint(argv) {
let [node, index, arg0] = argv;
if (!(arg0+'').startsWith("t348")){return}
let commands = [];
log({arg0})
let cc = (command, fn) => check(arg0, commands, command, fn);
if (cc("t348pack", packModule)) {return}
if(cc("t348run", t348run)) {return}
if (arg0) {console.error({unknownCommand: arg0, allCommands: commands})}
}
// copied from t352
function check(arg, commands, command, fn) {
let {argv}=imports();
if (arg === command) {fn(argv);return true;}
commands.push(command);
return false
}
function repoPath(hash) {
// noinspection JSUnresolvedVariable
return (packageJson()?.t348?.repo || "./t348repo/t0$HASH.js").replace('$HASH', hash);
}
function machineRepoPath(hash) {
let{path,homedir}=imports();
if(!path){xlog({machineRepoPath:'no path module'});return}
let machinePath = path.resolve(homedir(), ".t348repo/v1/t0$HASH.js").replace('$HASH', hash)
return log({machinePath})(machinePath)
}
function buildGlobalUrl(hash) {
// data-global-repo="./t348repo/t0$HASH.ts"
// noinspection JSUnresolvedVariable
let {T348_GLOBAL_REPO, GLOBAL_REPO}=imports().env;
let url = T348_GLOBAL_REPO || GLOBAL_REPO || "t348:t0$HASH.js"; // was "https://localhost/t0$HASH.js" but that was causing ERR_NETWORK_IMPORT_DISALLOWED
return url.replace('$HASH', hash)
}
async function postT227HashStore(hash, data) {
let{secureRequest,env}=imports();
// something like https://website.com/path/?version=1&mime=text/javascript&source=t348publish&name=t0$HASH.js
// noinspection JSUnresolvedVariable
let {T348_GLOBAL_REPO_PUBLISH, GLOBAL_REPO_PUBLISH}=imports().env;
let url = (T348_GLOBAL_REPO_PUBLISH||GLOBAL_REPO_PUBLISH||"").replace('$HASH', hash);
if(!url){console.error({noPublishUrl:'please set T348_GLOBAL_REPO_PUBLISH or GLOBAL_REPO_PUBLISH'})}
// accessible at https://website.com/path/t0SfTi5Wrr.js
const options = {
method: 'POST',
headers: {'Content-Length': Buffer.byteLength(data), 'Content-Type': 'text/javascript'}
};
return new Promise((resolve, reject) => {
const req = secureRequest(url, options, (res) => {
log(`STATUS: ${res.statusCode}`);
let data = {c: ''};
res.setEncoding('utf8');
res.on('data', (chunk) => { log(`BODY: ${chunk}`); data.c += chunk});
res.on('end', () => resolve(log('request completed')(data.c)));
}).on('error', reject);
req.write(data);
req.end();
})
}
async function loadAndMaybeCache(hash, transpiler) {
let{fs,env}=imports();
let {IGNORE_HASHES,T348CACHE}=env;
let localSourceCode = loadFromRepoSync(hash);
let fetchRequired = false;
if (localSourceCode === false) {
let globalUrl = buildGlobalUrl(hash);
localSourceCode = await miniGet(log({globalUrl})(globalUrl));
fetchRequired = true
}
let [fileHash, normalized, nameHint] = normalizeModuleAndHash(localSourceCode, 't0')
if (fileHash !== hash && !IGNORE_HASHES) { throw new Error(`repo damaged for hash: ${hash} => ${fileHash} DATA: ${normalized}`)}
// localSourceCode has meta, normalized has not. keep it.
if (fetchRequired) {fs.writeFileSync(machineRepoPath(hash), localSourceCode);}
if (T348CACHE) {
log({t348cache:hash})
fs.writeFileSync(repoPath(hash), localSourceCode)}
let nameHintSuffix = nameHint ? `#${nameHint}` : ''
let byHash = ({format: 'module', source: transpiler(normalized, 't0:'+hash+nameHintSuffix), shortCircuit:true});/*log*/
id({byHash});
return byHash;
}
function miniGet(url) {
let{secureGet,get}=imports();
if(!secureGet){
return fetch(url).then(response => response.status<300? response.text():err(`cannot fetch ${url}: ${response.status} ${response.statusText}`, {code:response.status===404?'ENOENT':'EIO'}))
}
return new Promise((resolve, reject) => {
let getter = url.startsWith('https://') ? secureGet : get;
getter(url, (res) => {
let data = {c: ''}; res.setEncoding('utf8');
res.on('data', (chunk) => data.c += chunk);
res.on('end', () => resolve(data.c));
}).on('error', (err) => reject(err));
})
}
function loadFromRepoSync(hash) {
try {return fc(repoPath(hash))} catch (e) {if (e.code !== 'ENOENT') {throw e}}
try {return fc(machineRepoPath(hash))} catch (e) {if (e.code !== 'ENOENT') {throw e}}
return false
}
export function normalizeModuleAndHash(codeString, prefix = '', suffix = '') {
let lines = codeString.split('\n')
let normalized = lines.map(x => normalizeImportLine(x)).filter(x => x !== false).join('\n');
let hash = h48(normalized)
if (prefix + suffix) {
normalized = lines.map(x => normalizeImportLine(x, prefix, suffix)).filter(x => x !== false).join('\n')
}
let nameHint = lines.find(x => x.match(t348MetaRegex))?.match(t348MetaRegex)?.[1];
if(nameHint){
try {
nameHint = JSON.parse(nameHint).name // todo maybe date too
}catch (e) {
nameHint = 'parseError'
}
}
// console.log({nameHint})
return [hash, normalized, nameHint]
}
function normalizeImportLine(line, prefix = '', suffix = '') {
// to be used only in normalizeModuleAndHash. false = line should be ignored
if (line.match(t348MetaRegex)) {return false}
let specifier = line.match(importRegex)?.[1];
if (!specifier) {return line}
let specHash = h48FromUrl(specifier);
if (!specHash) {return line}
return line.replace(specifier, prefix + specHash + suffix)
}
// import {c
// } from 'http://127.0.0.1:7348/c.js'; // so track from 'STRING'
// it's fine to replace commented out imports here
let importRegex = /\bfrom\s+['"]([^'"]+)['"]/;
// like bech32 but base64$_ because I want 6*8, not 5*10. two-byte prefix is passable.
let h48Regex = /.*\bt0([a-zA-Z0-9$_]{8})(\.m?js)?\b/ // remove .* to match first
export const h48FromUrl = url => url.match(h48Regex)?.[1];
// BEGIN stuff copied from t352 module-loader, discover-dependencies.js
export function nyi(message = 'nyi') {
throw new Error(message)
}
export function err(message = 'error', props = {}) {
let err = new Error(message);
for(let k in props){err[k]=props[k]}
throw err;
}
// holy shit, our id should be absolute if we resolve paths not just ids.
export async function discoverDependencies(session, id, depth) {
let sourceCode = await loadOriginalModuleSource(session, id)
// todo proper parsing later, now let's match from 'blob:BlobId' and from '/path/module.js'
// (?:^|\n)(?:(?!\/\/).)* means "does not contain // since start of file or line"
let importRegex = /(?:^|\n)(?:(?!\/\/).)*?from ['"]([^'"\n\s]+)['"]/g // todo this will match from 'a"
let importRegex2 = /(?:^|\n)(?:(?!\/\/).)*?from ['"]([^'"\n\s]+)['"]/
let importList = sourceCode.match(importRegex) || []
log({id, importList})
let map = {}
for (let importKey of importList) {
let detailMatch = importKey.match(importRegex2)
log({detailMatch:detailMatch?.[1]})
let importKey2 = detailMatch[1];
// for each one, find true url
map[importKey2] = await reallyLoadIntoBlobURL(session, importKey2, [...depth, id])
}
log({sourceCode, map})
let remappedCode = sourceCode
for (let importKey in map) {
remappedCode = remappedCode.replaceAll(importKey, map[importKey])
// todo add comments on what was replaced
}
return [sourceCode, remappedCode, map];
}
// hash to blob url
let moduleToUrl = {}
// hash to source
let originalSources = {}
// debug only
let remappedSources = {}
export async function loadOriginalModuleSource(session, id) {
if (!originalSources[id]) {
originalSources[id] = await session.getBlob(session, id)
}
return originalSources[id]
}
// todo: remove them?
let staticRemaps = {
'mini-react': '/react/mini-html.js',
'widget-frame': '/src/ui/widget-frame.js',
'use-async-value': '/src/ui/use-async-value.js',
'connected': '/src/vm/connected.js',
}
// holy crap, we're going to mix modules from different sessions together.
// but if blobs are content-keyed then it's okay!
export async function reallyLoadIntoBlobURL(session, source, depth = []) {
if (staticRemaps[source]) {
source = staticRemaps[source]
}
if (source.length > 100 || source.indexOf('\n') !== -1) {
log("assuming it's direct source code. still need to transpile.")
let id = h48(source)
log({directSourceId:id});
let fullId = new URL(id,document.location.href).href;
originalSources[fullId] = getTranspiler()(source, fullId);
return reallyLoadIntoBlobURL(session, fullId, [...depth, fullId])
}
// somewhere here we need to absolutize the url.
let sourceHash = h48FromUrl(source)
if(sourceHash){ // all hashes are equal regardless of baseURI
source = new URL(buildGlobalUrl(sourceHash),document.location.href).href;
log({sourceHash, source})
}else {
let prev = (depth.length > 1) ? depth[depth.length - 1] : document.location.href;
let absolute = new URL(source, prev).href
log({source, prev, absolute, depth});
source = absolute;
}
if (moduleToUrl[source]) {
log({returningExisting: source}); return moduleToUrl[source]
}
if (source.match(/^\/.*\.js$/)) { // it's our existing module, don't transcode
// todo really?
log({skipTranscode: source});
moduleToUrl[source] = document.location.href + source.slice(1);
return moduleToUrl[source];
}
log({reallyLoadIntoBlobURL: source, depth})
if (depth.length > 90) { // 100 is collapsed by devtools
err('dependency chain too deep')
}
// if already loaded - return
// otherwise, go depth-first.
let [code, remapped, remaps] = await discoverDependencies(session, source, depth)
log({code, remapped, remaps})
log(remapped);
remappedSources[source] = remapped;
// build
// todo maybe inject logger on load event?
moduleToUrl[source] = URL.createObjectURL(new Blob([remapped], {type: 'application/javascript'}))
// return URL!
return moduleToUrl[source]
}
//window.debugReallyLoadIntoBlobURL = reallyLoadIntoBlobURL;
//window.debugLoaderTables = {moduleToUrl, originalSources, remappedSources}
// END stuff copied from t352 module-loader, discover-dependencies.js
// todo: maybe re-do h48 via node/web crypto? or keep inline?
// copying stuff from t352
export function h48(v) {
// 48 is 6 bytes or 8 bytes of base64, 50% on 16M items is fine.
let h = sha256(v).slice(0, 6);
// $_ is variable-name-safe, -_ is url-safe, but I don't like it
// $ also breaks word-select in browsers though... abc$def
return u8b64(h).replaceAll('+', '$').replaceAll('/', '_')
}
// h48 deps
export const u8b64 = uint8array => {
const output = []; // note maybe rewrite this, not utf8 etc
for (let i = 0, {length} = uint8array; i < length; i++) {
output.push(String.fromCharCode(uint8array[i]));
}
return btoa(output.join(''));
}
// Uint8Array.from(arrayLike, mapFn, thisArg)
export const b64u8 = chars => Uint8Array.from(atob(chars), c => c.charCodeAt(0));
// lib/noble/sha256.js imports below
//import {SHA2} from './_sha2.js';
// lib/noble/_sha2.js imports below
//import {Hash, createView, toBytes} from './utils.js';
export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
// There is almost no big endian hardware, but js typed arrays uses platform specific endianness.
// So, just to be sure not to corrupt anything.
if (!isLE) {throw new Error('Non little-endian hardware is not supported')}
// For runtime check if class implements interface
export class Hash {
// Safe version that clones internal state
clone() { // noinspection JSUnresolvedFunction
return this._cloneInto();}
}
// Cast array to view
export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
export function toBytes(data) {
if (typeof data === 'string') {data = new TextEncoder().encode(data);}
if (!(data instanceof Uint8Array)) {
throw new TypeError(`Expected input type is Uint8Array (got ${typeof data}) `);
}
return data;
}
// Polyfill for Safari 14
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function') {
return view.setBigUint64(byteOffset, value, isLE);
}
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
// Base SHA2 class (RFC 6234)
export class SHA2 extends Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
if (this.destroyed) {throw new Error('instance is destroyed');}
const {view, buffer, blockLen, finished} = this;
if (finished) {throw new Error('digest() was already called');}
data = toBytes(data);
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input, cast it to view and process
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
if (this.destroyed) {throw new Error('instance is destroyed');}
if (!(out instanceof Uint8Array) || out.length < this.outputLen) {
throw new Error('_Sha2: Invalid output buffer');
}
if (this.finished) {throw new Error('digest() was already called');}
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const {buffer, view, blockLen, isLE} = this;
let {pos} = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
this.buffer.subarray(pos).fill(0);
// we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++) buffer[i] = 0;
// NOTE: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
// So we just write lowest 64bit of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
this.get().forEach((v, i) => oview.setUint32(4 * i, v, isLE));
}
digest() {
const {buffer, outputLen} = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const {blockLen, buffer, length, finished, destroyed, pos} = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen) {to.buffer.set(buffer);}
return to;
}
}
//import {rotr, wrapConstructor} from './utils.js';
// The rotate right (circular right shift) operation for uint32
export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
export function wrapConstructor(hashConstructor) {
const hashC = (message) => hashConstructor().update(toBytes(message)).digest();
const tmp = hashConstructor();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashConstructor();
hashC.init = hashC.create;
return hashC;
}
// lib/noble/sha256.js imports end, body below
// Choice: a ? b : c
const Chi = (a, b, c) => (a & b) ^ (~a & c);
// Majority function, true if any two inpust is true
const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
// Round constants:
// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
// prettier-ignore
const SHA256_K = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74,
0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3,
0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb,
0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa,
0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
// prettier-ignore
const IV = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19]);
// Temporary buffer, not used to store anything between runs
// Named this way because it matches specification.
const SHA256_W = new Uint32Array(64);
class SHA256 extends SHA2 {
constructor() {
super(64, 32, 8, false);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
this.A = IV[0] | 0;
this.B = IV[1] | 0;
this.C = IV[2] | 0;
this.D = IV[3] | 0;
this.E = IV[4] | 0;
this.F = IV[5] | 0;
this.G = IV[6] | 0;
this.H = IV[7] | 0;
}
get() {
const {A, B, C, D, E, F, G, H} = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
}
// Compression function main loop, 64 rounds
let {A, B, C, D, E, F, G, H} = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
const T2 = (sigma0 + Maj(A, B, C)) | 0;
H = G;
G = F;
F = E;
E = (D + T1) | 0;
D = C;
C = B;
B = A;
A = (T1 + T2) | 0;
}
// Add the compressed chunk to the current hash value
A = (A + this.A) | 0;
B = (B + this.B) | 0;
C = (C + this.C) | 0;
D = (D + this.D) | 0;
E = (E + this.E) | 0;
F = (F + this.F) | 0;
G = (G + this.G) | 0;
H = (H + this.H) | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {SHA256_W.fill(0);}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
export const sha256 = wrapConstructor(() => new SHA256());
// BEGIN INLINE [email protected]
const transform=(()=>{
const HELPERS = {
interopRequireWildcard: `
function interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
return newObj;
}
}
`,
interopRequireDefault: `
function interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
`,
createNamedExportFrom: `
function createNamedExportFrom(obj, localName, importedName) {
Object.defineProperty(exports, localName, {enumerable: true, get: () => obj[importedName]});
}
`,
// Note that TypeScript and Babel do this differently; TypeScript does a simple existence
// check in the exports object and does a plain assignment, whereas Babel uses
// defineProperty and builds an object of explicitly-exported names so that star exports can
// always take lower precedence. For now, we do the easier TypeScript thing.
createStarExport: `
function createStarExport(obj) {
Object.keys(obj)
.filter((key) => key !== "default" && key !== "__esModule")
.forEach((key) => {
if (exports.hasOwnProperty(key)) {
return;
}
Object.defineProperty(exports, key, {enumerable: true, get: () => obj[key]});
});
}
`,
nullishCoalesce: `
function nullishCoalesce(lhs, rhsFn) {
if (lhs != null) {
return lhs;
} else {
return rhsFn();
}
}
`,
asyncNullishCoalesce: `
async function asyncNullishCoalesce(lhs, rhsFn) {
if (lhs != null) {
return lhs;
} else {
return await rhsFn();
}
}
`,
optionalChain: `
function optionalChain(ops) {
let lastAccessLHS = undefined;
let value = ops[0];
let i = 1;
while (i < ops.length) {
const op = ops[i];
const fn = ops[i + 1];
i += 2;
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
return undefined;
}
if (op === 'access' || op === 'optionalAccess') {
lastAccessLHS = value;
value = fn(value);
} else if (op === 'call' || op === 'optionalCall') {
value = fn((...args) => value.call(lastAccessLHS, ...args));
lastAccessLHS = undefined;
}
}
return value;
}
`,
asyncOptionalChain: `
async function asyncOptionalChain(ops) {
let lastAccessLHS = undefined;
let value = ops[0];
let i = 1;
while (i < ops.length) {
const op = ops[i];
const fn = ops[i + 1];
i += 2;
if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
return undefined;
}
if (op === 'access' || op === 'optionalAccess') {
lastAccessLHS = value;
value = await fn(value);