-
Notifications
You must be signed in to change notification settings - Fork 340
/
blobs.ts
75 lines (61 loc) · 1.9 KB
/
blobs.ts
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
import { Buffer } from 'buffer'
import path from 'path'
import { BlobsServer } from '@netlify/blobs/server'
import { v4 as uuidv4 } from 'uuid'
import { log, NETLIFYDEVLOG } from '../../utils/command-helpers.js'
import { getPathInProject } from '../settings.js'
let hasPrintedLocalBlobsNotice = false
export const BLOBS_CONTEXT_VARIABLE = 'NETLIFY_BLOBS_CONTEXT'
export interface BlobsContext {
deployID: string
edgeURL: string
siteID: string
token: string
}
const printLocalBlobsNotice = () => {
if (hasPrintedLocalBlobsNotice) {
return
}
hasPrintedLocalBlobsNotice = true
log(
`${NETLIFYDEVLOG} Netlify Blobs running in sandbox mode for local development. Refer to https://ntl.fyi/local-blobs for more information.`,
)
}
const startBlobsServer = async (debug: boolean, projectRoot: string, token: string) => {
const directory = path.resolve(projectRoot, getPathInProject(['blobs-serve']))
const server = new BlobsServer({
debug,
directory,
onRequest: () => {
printLocalBlobsNotice()
},
token,
})
const { port } = await server.start()
return { port }
}
interface GetBlobsContextOptions {
debug: boolean
projectRoot: string
siteID: string
}
/**
* Starts a local Blobs server and returns a context object that lets functions
* connect to it.
*/
export const getBlobsContext = async ({ debug, projectRoot, siteID }: GetBlobsContextOptions) => {
const token = uuidv4()
const { port } = await startBlobsServer(debug, projectRoot, token)
const context: BlobsContext = {
deployID: '0',
edgeURL: `http://localhost:${port}`,
siteID,
token,
}
return context
}
/**
* Returns a Base-64, JSON-encoded representation of the Blobs context. This is
* the format that the `@netlify/blobs` package expects to find the context in.
*/
export const encodeBlobsContext = (context: BlobsContext) => Buffer.from(JSON.stringify(context)).toString('base64')