-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
342 lines (291 loc) · 8.37 KB
/
index.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
import vm from 'node:vm'
import { pathToFileURL, fileURLToPath } from 'node:url'
import { join, sep } from 'node:path'
import createEventSource from '@rangermauve/fetch-event-source'
// TODO: Add more APIs (like localStorage)
import { GLOBAL_LIST } from './globals.js'
const DEFAULT_ROOT = pathToFileURL(process.cwd()).href
export class ProtocolRegistry {
handlers = new Map()
register (protocol, fetch) {
if (this.handlers.has(protocol)) {
throw new Error(`Protocol scheme already registered: ${protocol}`)
}
this.handlers.set(protocol, fetch)
}
registerLazy (protocol, getFetch) {
let fetch = null
let loading = null
async function getAndFetch (...args) {
if (loading) {
await loading
} else if (!fetch) {
loading = getFetch()
fetch = await loading
loading = null
}
return fetch(...args)
}
this.register(protocol, getAndFetch)
}
get (protocol) {
if (!this.handlers.has(protocol)) {
throw new Error(`Unknown protocol: ${protocol}`)
}
return this.handlers.get(protocol)
}
alias (originalProtol, newProtool) {
const aliased = (...args) => this.get(originalProtol)(...args)
this.register(newProtool, aliased)
}
fetch (url, init = {}) {
if (typeof url !== 'string') {
throw new TypeError('Must normalize first parameter to `fetch` to be a URL')
}
const { protocol } = new URL(url)
if (!this.handlers.has(protocol)) {
throw new Error(`Protocol scheme invalid: ${protocol}`)
}
return this.handlers.get(protocol)(url, init)
}
}
export class GlobalRegistry {
globals = new Map()
constructor () {
for (const name of GLOBAL_LIST) {
this.register(name, globalThis[name])
}
}
// TODO: Can we figure out lazy loading?
register (name, value) {
if (typeof name === 'object') {
for (const entry of Object.entries(name)) {
this.register(...entry)
}
} else {
if (this.globals.has(name)) throw new Error(`Global already registered: ${name}`)
this.globals.set(name, value)
}
}
createContext () {
const context = {}
for (const [key, value] of this.globals) {
context[key] = value
}
return vm.createContext(context)
}
}
export default class Agregore {
context = null
root = null
modules = new Map()
moduleLoaders = new Map()
protocols = new ProtocolRegistry()
globals = new GlobalRegistry()
onbeforeunload = []
closed = false
constructor ({
root = DEFAULT_ROOT,
https = true,
http = true,
hyper = { storage: false },
ipfs = {
silent: true,
repo: join(fileURLToPath(root), '.ipfs'),
preload: {
enabled: false
},
config: {
Ipns: {
UsePubsub: true
},
Pubsub: {
Enabled: true
},
Addresses: {
API: '/ip4/127.0.0.1/tcp/2473',
Gateway: '/ip4/127.0.0.1/tcp/2474',
Swarm: [
// '/ip4/0.0.0.0/tcp/2475',
// '/ip6/::/tcp/2475',
'/ip4/0.0.0.0/udp/2475/quic',
'/ip6/::/udp/2475/quic'
]
},
// We don't need a gateway running. 🤷
Gateway: null
}
},
gemini = {}
} = {}) {
this.root = root
if (http) {
this.protocols.register('http:', globalThis.fetch)
}
if (https) {
this.protocols.register('https:', globalThis.fetch)
}
if (gemini) {
this.protocols.registerLazy('gemini:', async () => {
const { default: makeFetch } = await import('gemini-fetch')
const fetch = await makeFetch(gemini)
return fetch
})
}
if (hyper) {
this.protocols.registerLazy('hyper:', async () => {
const { default: makeHyper } = await import('hypercore-fetch')
const SDK = await import('hyper-sdk')
const sdk = await SDK.create(hyper)
const fetch = await makeHyper({
sdk,
writable: true
})
this.addBeforeUnload(() => sdk.close())
return fetch
})
}
if (ipfs) {
this.protocols.registerLazy('ipfs:', async () => {
const { default: makeFetch } = await import('js-ipfs-fetch')
const ipfsHttpModule = await import('ipfs-http-client')
const Ctl = await import('ipfsd-ctl')
const { default: GoIPFS } = await import('go-ipfs')
const ipfsBin = GoIPFS
.path()
.replace(`.asar${sep}`, `.asar.unpacked${sep}`)
const ipfsdOpts = {
ipfsOptions: ipfs,
type: 'go',
disposable: false,
test: false,
remote: false,
ipfsHttpModule,
ipfsBin
}
const ipfsd = await Ctl.createController(ipfsdOpts)
await ipfsd.init({ ipfsOptions: ipfs })
await ipfsd.version()
await ipfsd.start()
await ipfsd.api.id()
const fetch = await makeFetch({
ipfs: ipfsd.api
})
this.addBeforeUnload(() => ipfsd.stop())
return fetch
})
this.protocols.alias('ipfs:', 'ipns:')
this.protocols.alias('ipfs:', 'ipld:')
this.protocols.alias('ipfs:', 'pubsub:')
}
const fetch = (...args) => this.fetch(...args)
this.globals.register('fetch', fetch)
this.globals.register('close', () => this.close())
const {
EventSource,
ErrorEvent,
CloseEvent,
OpenEvent
} = createEventSource(fetch)
this.globals.register({
EventSource,
ErrorEvent,
CloseEvent,
OpenEvent
})
}
#initCheck () {
if (this.closed) {
throw new Error('Cannot invoke code, Agregore has already been uninitialized with close()')
}
if (!this.context) {
throw new Error('Agregore was not initialized, use await agregore.init() before doing any evaluation')
}
}
resolveURL (url) {
return new URL(url, this.root).href
}
async init () {
// This is where we can register any async-loaded globals?
this.context = this.globals.createContext()
}
addBeforeUnload (fn) {
this.onbeforeunload.unshift(fn)
}
async close () {
if (this.closed) return
this.closed = true
for (const fn of this.onbeforeunload) {
await fn()
}
}
fetch (urlOrRequest, init = {}) {
this.#initCheck()
if (!urlOrRequest) throw new Error('Must specify URL or request to fetch')
// TODO: Normalize URL if it's relative
let url = urlOrRequest
let finalInit = init
if (typeof urlOrRequest === 'object') {
url = urlOrRequest.url
finalInit = { ...urlOrRequest, ...init }
delete finalInit.url
}
const resolved = this.resolveURL(url)
return this.protocols.fetch(resolved, finalInit)
}
eval (code) {
this.#initCheck()
const importModuleDynamically = (url) => this.importModule(url)
const script = new vm.Script(code, {
filename: '<eval>',
importModuleDynamically
})
return script.runInContext(this.context)
}
async import (url) {
const module = await this.importModule(url)
return module.namespace
}
async importModule (url) {
this.#initCheck()
const parsed = new URL(url, this.root)
parsed.hash = ''
const sanitized = parsed.href
if (this.modules.has(sanitized)) {
return this.modules.get(sanitized)
} else if (this.moduleLoaders.has(sanitized)) {
return this.moduleLoaders.get(sanitized)
} else {
const loader = this.#loadModule(sanitized)
this.moduleLoaders.set(sanitized, loader)
const module = await loader
this.modules.set(sanitized, module)
this.moduleLoaders.delete(sanitized)
return module
}
}
async #loadModule (url) {
this.#initCheck()
const sourceRequest = await this.fetch(url)
if (!sourceRequest.ok) {
const reason = await sourceRequest.text()
throw new Error(`Unable to download module source: ${reason}`)
}
const source = await sourceRequest.text()
const initializeImportMeta = (meta, module) => {
meta.url = module.identifier
}
const importModuleDynamically = (specifier, module) => {
const resolved = new URL(specifier, module.identifier).href
return this.importModule(resolved)
}
const module = new vm.SourceTextModule(source, {
identifier: url,
context: this.context,
initializeImportMeta
})
await module.link(importModuleDynamically)
await module.evaluate()
return module
}
}