-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathendpoints.ts
More file actions
486 lines (419 loc) · 15.9 KB
/
Copy pathendpoints.ts
File metadata and controls
486 lines (419 loc) · 15.9 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
import { Router } from '@well-known-components/http-server'
import * as path from 'path'
import { Readable } from 'stream'
import { WearableJson } from '@dcl/schemas/dist/sdk'
import { Entity, EntityType, Locale, Wearable } from '@dcl/schemas'
import { v4 as uuidv4 } from 'uuid'
import { PreviewComponents } from '../types'
import { fetchEntityByPointer } from '../../../logic/catalyst-requests'
import { CliComponents } from '../../../components'
import {
b64HashingFunction,
getProjectPublishableFilesWithHashes,
machineId,
projectFilesToContentMappings
} from '../../../logic/project-files'
import { getCatalystBaseUrl, getInstalledPackageVersion } from '../../../logic/config'
import { Workspace } from '../../../logic/workspace-validations'
import { ProjectUnion, WearableProject } from '../../../logic/project-validations'
type LambdasWearable = Wearable & {
baseUrl: string
}
export async function setupEcs6Endpoints(
components: CliComponents,
router: Router<PreviewComponents>,
workspace: Workspace
) {
const catalystUrl = new URL(await getCatalystBaseUrl(components))
// handle old preview scene.json DEPRECATED
router.get('/scene.json', async () => {
return {
headers: { 'content-type': 'application/json' },
body: components.fs.createReadStream(path.join(workspace.projects[0].workingDirectory, 'scene.json'))
}
})
router.get('/lambdas/explore/realms', async (ctx) => {
return {
body: [
{
serverName: 'localhost',
url: `http://${ctx.url.host}`,
layer: 'stub',
usersCount: 0,
maxUsers: 100,
userParcels: []
}
]
}
})
router.get('/lambdas/contracts/servers', async (ctx) => {
return {
body: [
{
address: `http://${ctx.url.host}`,
owner: '0x0000000000000000000000000000000000000000',
id: '0x0000000000000000000000000000000000000000000000000000000000000000'
}
]
}
})
router.get('/lambdas/profiles', async (ctx, next) => {
const baseUrl = `${ctx.url.protocol}//${ctx.url.host}/content/contents`
try {
const previewWearables = await getAllPreviewWearables(components, workspace, {
baseUrl
})
if (previewWearables.length === 1) {
const u = new URL(ctx.url.toString())
u.host = catalystUrl.host
u.protocol = catalystUrl.protocol
u.port = catalystUrl.port
const req = await components.fetch.fetch(u.toString(), {
headers: {
connection: 'close'
},
method: ctx.request.method,
body: ctx.request.method === 'get' ? undefined : (ctx.request.body as any),
duplex: 'half'
})
const deployedProfile = (await req.json()) as any[]
if (deployedProfile?.length === 1) {
deployedProfile[0].avatars[0].avatar.wearables.push(...previewWearables.map(($) => $.id))
return {
headers: {
'content-type': req.headers.get('content-type') || 'application/binary'
},
body: deployedProfile
}
}
}
} catch (err: any) {
components.logger.warn(`Failed to catch profile and fill with preview wearables.`)
components.logger.error(err)
}
return next()
})
router.all('/lambdas/:path+', async (ctx) => {
const u = new URL(ctx.url.toString())
u.host = catalystUrl.host
u.protocol = catalystUrl.protocol
u.port = catalystUrl.port
const req = await components.fetch.fetch(u.toString(), {
headers: {
connection: 'close'
},
method: ctx.request.method,
body: ctx.request.method === 'get' ? undefined : (ctx.request.body as any),
duplex: 'half'
})
return {
headers: {
'content-type': req.headers.get('content-type') || 'application/binary'
},
// `req.body` is a web ReadableStream; convert it to a Node stream so the
// http-server can pipe it (it only handles Node streams / Buffers / strings).
body: req.body ? Readable.fromWeb(req.body as any) : undefined
}
})
router.post('/content/entities', async (ctx) => {
const res = await components.fetch.fetch(`${catalystUrl.toString()}/content/entities`, {
method: 'post',
body: ctx.request.body as any,
duplex: 'half'
})
// undici decompresses the body but leaves the original content-encoding /
// content-length headers in place; forwarding them would make the client
// re-decode (or truncate to the compressed length) the already-decoded body.
// fetch() responses carry immutable Headers, so filter instead of delete.
const headers = Object.fromEntries(res.headers)
delete headers['content-encoding']
delete headers['content-length']
return {
status: res.status,
headers,
body: res.body ? Readable.fromWeb(res.body as any) : undefined
}
})
router.all('/explorer/:path+', async (ctx) => {
const u = new URL(ctx.url.toString())
u.host = catalystUrl.host
u.protocol = catalystUrl.protocol
u.port = catalystUrl.port
const req = await components.fetch.fetch(u.toString(), {
headers: { connection: 'close' },
method: ctx.request.method,
body: ctx.request.method === 'get' ? undefined : (ctx.request.body as any),
duplex: 'half'
})
return {
headers: {
'content-type': req.headers.get('content-type') || 'application/json'
},
// `req.body` is a web ReadableStream; convert it to a Node stream so the
// http-server can pipe it (it only handles Node streams / Buffers / strings).
body: req.body ? Readable.fromWeb(req.body as any) : undefined
}
})
router.get('/feature-flags/:file', async (ctx) => {
const res = await components.fetch.fetch(`https://feature-flags.decentraland.zone/${ctx.params.file}`, {
headers: {
connection: 'close'
}
})
return {
body: await res.arrayBuffer()
}
})
// TODO: get workspace scenes & wearables...
await serveFolders(components, router, workspace)
}
async function serveFolders(
components: Pick<CliComponents, 'fs' | 'logger' | 'fetch' | 'config'>,
router: Router<PreviewComponents>,
workspace: Workspace
) {
const catalystUrl = await getCatalystBaseUrl(components)
router.get('/content/contents/:hash', async (ctx, next) => {
if (ctx.params.hash && ctx.params.hash.startsWith('b64-')) {
const decoded = Buffer.from(ctx.params.hash.replace(/^b64-/, ''), 'base64').toString('utf8')
// Strip the machineId suffix that was added during encoding
const fullPath = path.resolve(decoded.slice(0, -(machineId.length + 1)))
// find a project that we are talking about. NOTE: this filter is not exhaustive
// relative paths should be used instead
const baseProject = workspace.projects.find((project) => fullPath.startsWith(project.workingDirectory))
// only return files IF the file is within a baseFolder
if (!baseProject) {
return next()
}
if (path.resolve(fullPath) === path.resolve(baseProject.workingDirectory)) {
// if we are talking about the root directory, then we must return the json of the entity
const entity = await fakeEntityV3FromProject(components, baseProject, async ($) => b64HashingFunction($))
if (!entity) return { status: 404 }
return {
headers: {
'x-timestamp': Date.now().toString(),
'x-sent': 'true',
'cache-control': 'no-cache,private,max-age=1'
},
body: entity
}
}
if (!(await components.fs.fileExists(fullPath))) return { status: 404 }
if (await components.fs.directoryExists(fullPath)) return { status: 404 }
return {
headers: {
'x-timestamp': Date.now().toString(),
'x-sent': 'true',
'cache-control': 'no-cache,private,max-age=1'
},
body: components.fs.createReadStream(fullPath)
}
}
return next()
})
async function pointerRequestHandler(pointers: string[]): Promise<Entity[]> {
if (!pointers || pointers.length === 0) {
return []
}
const requestedPointers = new Set<string>(
pointers && typeof pointers === 'string' ? [pointers as string] : (pointers as string[])
)
const resultEntities = await getSceneJson(components, workspace, Array.from(requestedPointers))
const remote = await fetchEntityByPointer(
components,
catalystUrl.toString(),
pointers.filter(($: string) => !$.match(/-?\d+,-?\d+/))
)
const serverEntities = Array.isArray(remote.deployments) ? remote.deployments : []
return [...resultEntities, ...serverEntities]
}
// REVIEW RESPONSE FORMAT
router.get('/content/entities/scene', async (ctx) => {
return {
body: await pointerRequestHandler(ctx.url.searchParams.getAll('pointer'))
}
})
// REVIEW RESPONSE FORMAT
router.post('/content/entities/active', async (ctx) => {
const body = await ctx.request.json()
return {
body: await pointerRequestHandler(body.pointers)
}
})
router.get('/preview-wearables/:id', async (ctx) => {
const baseUrl = `${ctx.url.protocol}//${ctx.url.host}/content/contents`
const wearables = await getAllPreviewWearables(components, workspace, {
baseUrl
})
const wearableId = ctx.params.id
return {
body: {
ok: true,
data: wearables.filter((wearable) => wearable.id === wearableCache.get(wearableId))
}
}
})
router.get('/preview-wearables', async (ctx) => {
const baseUrl = `${ctx.url.protocol}//${ctx.url.host}/content/contents`
return {
body: {
ok: true,
data: await getAllPreviewWearables(components, workspace, { baseUrl })
}
}
})
}
async function getAllPreviewWearables(
components: Pick<CliComponents, 'fs' | 'logger'>,
workspace: Workspace,
{ baseUrl }: { baseUrl: string }
) {
// NOTE: the explorers should use the /entities/active endpoint to retrieve the wearables. This endpoint should be removed
const wearablePathArray: string[] = []
for (const project of workspace.projects) {
if (project.kind === 'smart-wearable') {
const wearableJsonPath = path.resolve(project.workingDirectory, 'wearable.json')
if (await components.fs.fileExists(wearableJsonPath)) {
wearablePathArray.push(wearableJsonPath)
}
}
}
const ret: LambdasWearable[] = []
for (const project of workspace.projects) {
try {
if (project.kind === 'smart-wearable') ret.push(await serveWearable(components, project, baseUrl))
} catch (err) {
components.logger.error(
`Couldn't mock the wearable ${project.workingDirectory}. Please verify the correct format and scheme.` + err
)
}
}
return ret
}
const wearableCache = new Map<string, string>()
async function serveWearable(
components: Pick<CliComponents, 'fs' | 'logger'>,
project: WearableProject,
baseUrl: string
): Promise<LambdasWearable> {
const wearableJsonPath = path.join(project.workingDirectory, 'wearable.json')
const wearableJson = JSON.parse((await components.fs.readFile(wearableJsonPath)).toString())
if (!WearableJson.validate(wearableJson)) {
const errors = (WearableJson.validate.errors || []).map((a) => `${a.data} ${a.message}`).join('')
components.logger.error(`Unable to validate wearable.json properly, please check it.` + errors)
throw new Error(`Invalid wearable.json (${wearableJsonPath})`)
}
const projectFiles = await getProjectPublishableFilesWithHashes(components, project.workingDirectory, async ($) =>
b64HashingFunction($)
)
const contentFiles = projectFilesToContentMappings(project.workingDirectory, projectFiles)
const thumbnailFiltered = contentFiles.filter(($) => $.file === 'thumbnail.png')
const thumbnail =
thumbnailFiltered.length > 0 && thumbnailFiltered[0]!.hash && `${baseUrl}/${thumbnailFiltered[0].hash}`
// Set wearable ID.
const sceneHash = b64HashingFunction(project.workingDirectory)
const wearableId = wearableCache.get(sceneHash) ?? `urn:${uuidv4()}`
wearableCache.set(sceneHash, wearableId)
const representations = wearableJson.data.representations.map((representation) => ({
...representation,
mainFile: `male/${representation.mainFile}`,
contents: contentFiles.map(($) => ({
key: `male/${$?.file}`,
url: `${baseUrl}/${$?.hash}`,
hash: $?.hash
}))
}))
return {
id: wearableId,
rarity: wearableJson.rarity,
i18n: [{ code: 'en' as Locale, text: wearableJson.name }],
description: wearableJson.description,
thumbnail: thumbnail || '',
image: thumbnail || '',
collectionAddress: '0x0',
baseUrl: `${baseUrl}/`,
name: wearableJson.name || '',
data: {
category: wearableJson.data.category,
replaces: [],
hides: [],
tags: [],
representations: representations as any
// scene: hashedFiles as any,
}
}
}
async function getSceneJson(
components: Pick<CliComponents, 'fs' | 'logger'>,
workspace: Workspace,
pointers: string[]
): Promise<Entity[]> {
const requestedPointers = new Set<string>(pointers)
const resultEntities: Entity[] = []
const allDeployments = await Promise.all(
workspace.projects.map((project) =>
fakeEntityV3FromProject(components, project, async ($) => b64HashingFunction($))
)
)
for (const pointer of Array.from(requestedPointers)) {
// get deployment by pointer
const theDeployment = allDeployments.find(($) => $ && $.pointers.includes(pointer))
if (theDeployment) {
// remove all the required pointers from the requestedPointers set
// to prevent sending duplicated entities
theDeployment.pointers.forEach(($) => requestedPointers.delete($))
// add the deployment to the results
resultEntities.push(theDeployment)
}
}
return resultEntities
}
async function fakeEntityV3FromProject(
components: Pick<CliComponents, 'fs' | 'logger'>,
project: ProjectUnion,
hashingFunction: (filePath: string) => Promise<string>
): Promise<Entity | null> {
const projectFiles = await getProjectPublishableFilesWithHashes(components, project.workingDirectory, hashingFunction)
const contentFiles = projectFilesToContentMappings(project.workingDirectory, projectFiles)
if (project.kind === 'scene') {
const sceneJsonPath = path.resolve(project.workingDirectory, 'scene.json')
const sdkVersion = await getInstalledPackageVersion(components, '@dcl/sdk', project.workingDirectory)
const sceneJson = { sdkVersion, ...JSON.parse(await components.fs.readFile(sceneJsonPath, 'utf-8')) }
const { base, parcels }: { base: string; parcels: string[] } = sceneJson.scene
const pointers = new Set<string>()
pointers.add(base)
parcels.forEach(($) => pointers.add($))
return {
version: 'v3',
type: EntityType.SCENE,
id: await hashingFunction(project.workingDirectory),
pointers: Array.from(pointers),
timestamp: Date.now(),
metadata: sceneJson,
content: contentFiles
}
} else if (project.kind === 'smart-wearable') {
const wearableJsonPath = path.resolve(project.workingDirectory, 'wearable.json')
try {
const wearableJson = JSON.parse(await components.fs.readFile(wearableJsonPath, 'utf-8'))
if (!WearableJson.validate(wearableJson)) {
const errors = (WearableJson.validate.errors || []).map((a) => `${a.data} ${a.message}`).join('')
components.logger.error(`Unable to validate wearable.json properly, please check its schema.` + errors)
components.logger.error(`Invalid wearable.json (${wearableJsonPath})`)
}
return {
version: 'v3',
type: EntityType.WEARABLE,
id: await hashingFunction(project.workingDirectory),
pointers: Array.from([await hashingFunction(project.workingDirectory)]),
timestamp: Date.now(),
metadata: wearableJson,
content: contentFiles
}
} catch (err: any) {
components.logger.error(`Unable to load wearable.json`)
components.logger.error(err)
}
}
return null
}