@tinyshed/tinystore 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +262 -0
- package/bin/tinystore.js +50 -0
- package/dist/background.d.ts +30 -0
- package/dist/background.js +93 -0
- package/dist/blobs.d.ts +98 -0
- package/dist/blobs.js +299 -0
- package/dist/cancel.d.ts +14 -0
- package/dist/cancel.js +22 -0
- package/dist/clock.d.ts +21 -0
- package/dist/clock.js +35 -0
- package/dist/config.d.ts +60 -0
- package/dist/config.js +417 -0
- package/dist/connection.d.ts +78 -0
- package/dist/connection.js +405 -0
- package/dist/console.d.ts +48 -0
- package/dist/console.js +195 -0
- package/dist/errors.d.ts +103 -0
- package/dist/errors.js +158 -0
- package/dist/handles.d.ts +28 -0
- package/dist/handles.js +37 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +7 -0
- package/dist/jobs.d.ts +304 -0
- package/dist/jobs.js +684 -0
- package/dist/kv.d.ts +283 -0
- package/dist/kv.js +815 -0
- package/dist/limiter.d.ts +45 -0
- package/dist/limiter.js +68 -0
- package/dist/logger.d.ts +96 -0
- package/dist/logger.js +243 -0
- package/dist/metrics.d.ts +249 -0
- package/dist/metrics.js +610 -0
- package/dist/once.d.ts +31 -0
- package/dist/once.js +116 -0
- package/dist/quota.d.ts +44 -0
- package/dist/quota.js +98 -0
- package/dist/records.d.ts +182 -0
- package/dist/records.js +346 -0
- package/dist/runtime/bun.d.ts +2 -0
- package/dist/runtime/bun.js +164 -0
- package/dist/runtime/node.d.ts +2 -0
- package/dist/runtime/node.js +157 -0
- package/dist/runtime/shared.d.ts +25 -0
- package/dist/runtime/shared.js +45 -0
- package/dist/runtime.d.ts +48 -0
- package/dist/runtime.js +4 -0
- package/dist/schema.d.ts +39 -0
- package/dist/schema.js +21 -0
- package/dist/session.d.ts +120 -0
- package/dist/session.js +546 -0
- package/dist/sql.d.ts +121 -0
- package/dist/sql.js +342 -0
- package/dist/store.d.ts +103 -0
- package/dist/store.js +153 -0
- package/dist/time.d.ts +35 -0
- package/dist/time.js +44 -0
- package/dist/trace.d.ts +18 -0
- package/dist/trace.js +22 -0
- package/dist/wire/codec.d.ts +90 -0
- package/dist/wire/codec.js +383 -0
- package/dist/wire/frame.d.ts +41 -0
- package/dist/wire/frame.js +102 -0
- package/dist/wire/messages.d.ts +1403 -0
- package/dist/wire/messages.js +472 -0
- package/dist/wire/msgpack.d.ts +93 -0
- package/dist/wire/msgpack.js +680 -0
- package/package.json +40 -0
- package/src/background.ts +108 -0
- package/src/blobs.ts +437 -0
- package/src/cancel.ts +26 -0
- package/src/clock.ts +45 -0
- package/src/config.ts +501 -0
- package/src/connection.ts +512 -0
- package/src/console.ts +228 -0
- package/src/errors.ts +211 -0
- package/src/handles.ts +68 -0
- package/src/index.ts +92 -0
- package/src/jobs.ts +963 -0
- package/src/kv.ts +1093 -0
- package/src/limiter.ts +99 -0
- package/src/logger.ts +326 -0
- package/src/metrics.ts +896 -0
- package/src/once.ts +142 -0
- package/src/quota.ts +137 -0
- package/src/records.ts +537 -0
- package/src/runtime/bun.ts +190 -0
- package/src/runtime/node.ts +177 -0
- package/src/runtime/shared.ts +61 -0
- package/src/runtime.ts +57 -0
- package/src/schema.ts +69 -0
- package/src/session.ts +665 -0
- package/src/sql.ts +478 -0
- package/src/store.ts +219 -0
- package/src/time.ts +87 -0
- package/src/trace.ts +32 -0
- package/src/wire/codec.ts +445 -0
- package/src/wire/frame.ts +139 -0
- package/src/wire/messages.ts +562 -0
- package/src/wire/msgpack.ts +712 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// The runtime of Bun: sockets through Bun.connect, a Windows named pipe
|
|
2
|
+
// through node:net, which Bun implements, and a private child through
|
|
3
|
+
// Bun.spawn. Nothing here touches Bun until it is called, so that Node can
|
|
4
|
+
// load this file beside its own.
|
|
5
|
+
|
|
6
|
+
import net from 'node:net'
|
|
7
|
+
|
|
8
|
+
import manifest from '../../package.json' with { type: 'json' }
|
|
9
|
+
import { ClosedError } from '../errors.ts'
|
|
10
|
+
import type { PrivateChild, Runtime, TlsOptions, Transport, TransportEvents } from '../runtime.ts'
|
|
11
|
+
import { address, exitedWith, spawnDetached, stderrKept } from './shared.ts'
|
|
12
|
+
|
|
13
|
+
export const bunRuntime: Runtime = {
|
|
14
|
+
get client() {
|
|
15
|
+
return `tinystore-js/${manifest.version} bun/${Bun.version}`
|
|
16
|
+
},
|
|
17
|
+
windows: process.platform === 'win32',
|
|
18
|
+
connect,
|
|
19
|
+
spawnPrivate,
|
|
20
|
+
spawnDetached,
|
|
21
|
+
readFile: async path => {
|
|
22
|
+
const file = Bun.file(path)
|
|
23
|
+
try {
|
|
24
|
+
return await file.bytes()
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if ((err as { code?: string }).code === 'ENOENT') {
|
|
27
|
+
return undefined
|
|
28
|
+
}
|
|
29
|
+
throw err
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
which: name => Bun.which(name) ?? undefined,
|
|
33
|
+
packagedBinary,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function connect(
|
|
37
|
+
endpoint: string,
|
|
38
|
+
events: TransportEvents,
|
|
39
|
+
tls?: TlsOptions,
|
|
40
|
+
): Promise<Transport> {
|
|
41
|
+
const at = address(endpoint)
|
|
42
|
+
switch (at.kind) {
|
|
43
|
+
case 'pipe':
|
|
44
|
+
return connectPipe(at.path, events)
|
|
45
|
+
case 'unix': {
|
|
46
|
+
const path = at.path
|
|
47
|
+
return connectSocket(socket => Bun.connect({ unix: path, socket }), events)
|
|
48
|
+
}
|
|
49
|
+
case 'tcp': {
|
|
50
|
+
const { host, port } = at
|
|
51
|
+
return connectSocket(socket => Bun.connect({ hostname: host, port, socket }), events)
|
|
52
|
+
}
|
|
53
|
+
case 'tls': {
|
|
54
|
+
const { host, port } = at
|
|
55
|
+
const verify = {
|
|
56
|
+
serverName: tls?.serverName ?? host,
|
|
57
|
+
...(tls?.ca === undefined ? {} : { ca: tls.ca }),
|
|
58
|
+
}
|
|
59
|
+
return connectSocket(
|
|
60
|
+
socket => Bun.connect({ hostname: host, port, tls: verify, socket }),
|
|
61
|
+
events,
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type Socket = Awaited<ReturnType<typeof Bun.connect>>
|
|
68
|
+
|
|
69
|
+
interface Handlers {
|
|
70
|
+
data(socket: Socket, data: Uint8Array): void
|
|
71
|
+
drain(socket: Socket): void
|
|
72
|
+
end(socket: Socket): void
|
|
73
|
+
close(socket: Socket, err?: Error): void
|
|
74
|
+
error(socket: Socket, err: Error): void
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A socket's write may take part of the bytes: the rest waits for its drain,
|
|
79
|
+
* in order, so the session hands a whole frame over and forgets it.
|
|
80
|
+
*/
|
|
81
|
+
async function connectSocket(
|
|
82
|
+
dial: (handlers: Handlers) => Promise<Socket>,
|
|
83
|
+
events: TransportEvents,
|
|
84
|
+
): Promise<Transport> {
|
|
85
|
+
const waiting: Uint8Array[] = []
|
|
86
|
+
let ended = false
|
|
87
|
+
const end = (err: Error) => {
|
|
88
|
+
if (!ended) {
|
|
89
|
+
ended = true
|
|
90
|
+
events.end(err)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
let socket: Socket | undefined
|
|
94
|
+
const pump = () => {
|
|
95
|
+
while (socket !== undefined && waiting.length > 0) {
|
|
96
|
+
const bytes = waiting[0]!
|
|
97
|
+
const wrote = socket.write(bytes)
|
|
98
|
+
if (wrote === bytes.length) {
|
|
99
|
+
waiting.shift()
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
waiting[0] = bytes.subarray(Math.max(wrote, 0))
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
socket = await dial({
|
|
107
|
+
data: (_, data) => events.data(data),
|
|
108
|
+
drain: () => pump(),
|
|
109
|
+
end: () => end(new ClosedError('the server ended the connection')),
|
|
110
|
+
close: (_, err) => end(err ?? new ClosedError('the connection closed')),
|
|
111
|
+
error: (_, err) => end(err),
|
|
112
|
+
})
|
|
113
|
+
return {
|
|
114
|
+
write: bytes => {
|
|
115
|
+
waiting.push(bytes)
|
|
116
|
+
if (waiting.length === 1) {
|
|
117
|
+
pump()
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
close: () => socket?.end(),
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function connectPipe(path: string, events: TransportEvents): Promise<Transport> {
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
const socket = net.createConnection(path)
|
|
127
|
+
let connected = false
|
|
128
|
+
let ended = false
|
|
129
|
+
const end = (err: Error) => {
|
|
130
|
+
if (!ended) {
|
|
131
|
+
ended = true
|
|
132
|
+
events.end(err)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
socket.once('connect', () => {
|
|
136
|
+
connected = true
|
|
137
|
+
resolve({ write: bytes => socket.write(bytes), close: () => socket.end() })
|
|
138
|
+
})
|
|
139
|
+
socket.on('data', (data: Uint8Array) => events.data(data))
|
|
140
|
+
socket.on('error', err => (connected ? end(err) : reject(err)))
|
|
141
|
+
socket.on('close', () => end(new ClosedError('the pipe closed')))
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function spawnPrivate(argv: string[], events: TransportEvents): PrivateChild {
|
|
146
|
+
const proc = Bun.spawn(argv, { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', windowsHide: true })
|
|
147
|
+
let kept = ''
|
|
148
|
+
// a pipe nobody drains stops the server once it fills, so stderr is read to its end
|
|
149
|
+
const draining = (async () => {
|
|
150
|
+
const decoder = new TextDecoder()
|
|
151
|
+
for await (const chunk of proc.stderr) {
|
|
152
|
+
kept = (kept + decoder.decode(chunk, { stream: true })).slice(-stderrKept)
|
|
153
|
+
}
|
|
154
|
+
})()
|
|
155
|
+
void (async () => {
|
|
156
|
+
try {
|
|
157
|
+
for await (const chunk of proc.stdout) {
|
|
158
|
+
events.data(chunk)
|
|
159
|
+
}
|
|
160
|
+
} finally {
|
|
161
|
+
await draining.catch(() => {})
|
|
162
|
+
events.end(exitedWith(await proc.exited, kept))
|
|
163
|
+
}
|
|
164
|
+
})()
|
|
165
|
+
return {
|
|
166
|
+
transport: {
|
|
167
|
+
write: bytes => {
|
|
168
|
+
proc.stdin.write(bytes)
|
|
169
|
+
void proc.stdin.flush()
|
|
170
|
+
},
|
|
171
|
+
close: () => {
|
|
172
|
+
void proc.stdin.end()
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
exited: proc.exited,
|
|
176
|
+
kill: () => proc.kill(),
|
|
177
|
+
stderr: () => kept,
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The platform's package of the server binary, installed beside this one. */
|
|
182
|
+
function packagedBinary(): string | undefined {
|
|
183
|
+
const name = `@tinyshed/tinystore-${process.platform}-${process.arch}`
|
|
184
|
+
const binary = process.platform === 'win32' ? 'tinystore.exe' : 'tinystore'
|
|
185
|
+
try {
|
|
186
|
+
return Bun.resolveSync(`${name}/bin/${binary}`, import.meta.dir)
|
|
187
|
+
} catch {
|
|
188
|
+
return undefined
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// The runtime of Node: every transport through node:net and node:tls, a
|
|
2
|
+
// Windows named pipe and a Unix socket included, and a private child through
|
|
3
|
+
// node:child_process.
|
|
4
|
+
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { accessSync, constants, statSync } from 'node:fs'
|
|
7
|
+
import { readFile } from 'node:fs/promises'
|
|
8
|
+
import { createRequire } from 'node:module'
|
|
9
|
+
import net from 'node:net'
|
|
10
|
+
import { delimiter, join } from 'node:path'
|
|
11
|
+
import tls from 'node:tls'
|
|
12
|
+
|
|
13
|
+
import manifest from '../../package.json' with { type: 'json' }
|
|
14
|
+
import { ClosedError } from '../errors.ts'
|
|
15
|
+
import type { PrivateChild, Runtime, TlsOptions, Transport, TransportEvents } from '../runtime.ts'
|
|
16
|
+
import { address, exitedWith, spawnDetached, stderrKept } from './shared.ts'
|
|
17
|
+
|
|
18
|
+
export const nodeRuntime: Runtime = {
|
|
19
|
+
client: `tinystore-js/${manifest.version} node/${process.versions.node}`,
|
|
20
|
+
windows: process.platform === 'win32',
|
|
21
|
+
connect,
|
|
22
|
+
spawnPrivate,
|
|
23
|
+
spawnDetached,
|
|
24
|
+
readFile: async path => {
|
|
25
|
+
try {
|
|
26
|
+
return await readFile(path)
|
|
27
|
+
} catch (err) {
|
|
28
|
+
if ((err as { code?: string }).code === 'ENOENT') {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
throw err
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
which,
|
|
35
|
+
packagedBinary,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function connect(
|
|
39
|
+
endpoint: string,
|
|
40
|
+
events: TransportEvents,
|
|
41
|
+
options?: TlsOptions,
|
|
42
|
+
): Promise<Transport> {
|
|
43
|
+
const at = address(endpoint)
|
|
44
|
+
switch (at.kind) {
|
|
45
|
+
case 'pipe':
|
|
46
|
+
case 'unix':
|
|
47
|
+
return connected(net.createConnection(at.path), 'connect', events)
|
|
48
|
+
case 'tcp':
|
|
49
|
+
return connected(
|
|
50
|
+
net.createConnection({ host: at.host, port: at.port, noDelay: true }),
|
|
51
|
+
'connect',
|
|
52
|
+
events,
|
|
53
|
+
)
|
|
54
|
+
case 'tls':
|
|
55
|
+
return connected(connectTLS(at.host, at.port, options), 'secureConnect', events)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A TLS socket checking the certificate against the name asked for, or the
|
|
61
|
+
* host, and trusting the given certificates beside Node's own: Node's ca
|
|
62
|
+
* replaces them otherwise.
|
|
63
|
+
*/
|
|
64
|
+
function connectTLS(host: string, port: number, options?: TlsOptions): tls.TLSSocket {
|
|
65
|
+
const name = options?.serverName ?? host
|
|
66
|
+
const given = options?.ca === undefined ? [] : [options.ca].flat()
|
|
67
|
+
const socket = tls.connect({
|
|
68
|
+
host,
|
|
69
|
+
port,
|
|
70
|
+
// a server name is a DNS name: one that is an address is checked, not sent
|
|
71
|
+
...(net.isIP(name) === 0 ? { servername: name } : {}),
|
|
72
|
+
checkServerIdentity: (_, certificate) => tls.checkServerIdentity(name, certificate),
|
|
73
|
+
...(given.length === 0 ? {} : { ca: [...tls.rootCertificates, ...given] }),
|
|
74
|
+
})
|
|
75
|
+
return socket.setNoDelay(true)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A transport once the socket is ready: a socket's write queues what the
|
|
80
|
+
* kernel does not take yet, in order, so the session hands a whole frame over
|
|
81
|
+
* and forgets it.
|
|
82
|
+
*/
|
|
83
|
+
function connected(
|
|
84
|
+
socket: net.Socket,
|
|
85
|
+
ready: 'connect' | 'secureConnect',
|
|
86
|
+
events: TransportEvents,
|
|
87
|
+
): Promise<Transport> {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
let open = false
|
|
90
|
+
let ended = false
|
|
91
|
+
const end = (err: Error) => {
|
|
92
|
+
if (!ended) {
|
|
93
|
+
ended = true
|
|
94
|
+
events.end(err)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
socket.once(ready, () => {
|
|
98
|
+
open = true
|
|
99
|
+
resolve({ write: bytes => void socket.write(bytes), close: () => void socket.end() })
|
|
100
|
+
})
|
|
101
|
+
socket.on('data', (data: Uint8Array) => events.data(data))
|
|
102
|
+
socket.on('error', err => (open ? end(err) : reject(err)))
|
|
103
|
+
socket.on('end', () => end(new ClosedError('the server ended the connection')))
|
|
104
|
+
socket.on('close', () => end(new ClosedError('the connection closed')))
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function spawnPrivate(argv: string[], events: TransportEvents): PrivateChild {
|
|
109
|
+
const proc = spawn(argv[0]!, argv.slice(1), { stdio: 'pipe', windowsHide: true })
|
|
110
|
+
let kept = ''
|
|
111
|
+
// a pipe nobody drains stops the server once it fills, so stderr is read to its end
|
|
112
|
+
proc.stderr.setEncoding('utf8')
|
|
113
|
+
proc.stderr.on('data', (text: string) => {
|
|
114
|
+
kept = (kept + text).slice(-stderrKept)
|
|
115
|
+
})
|
|
116
|
+
proc.stdout.on('data', (data: Uint8Array) => events.data(data))
|
|
117
|
+
// a write to a child that has exited fails here; its exit says why
|
|
118
|
+
proc.stdin.on('error', () => {})
|
|
119
|
+
// close comes once the child has exited and its stdout and stderr have ended
|
|
120
|
+
const exited = new Promise<number>(resolve => {
|
|
121
|
+
proc.once('close', code => resolve(code ?? -1))
|
|
122
|
+
proc.once('error', err => {
|
|
123
|
+
kept += err.message
|
|
124
|
+
resolve(-1)
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
void exited.then(code => events.end(exitedWith(code, kept)))
|
|
128
|
+
return {
|
|
129
|
+
transport: {
|
|
130
|
+
write: bytes => void proc.stdin.write(bytes),
|
|
131
|
+
close: () => void proc.stdin.end(),
|
|
132
|
+
},
|
|
133
|
+
exited,
|
|
134
|
+
kill: () => void proc.kill(),
|
|
135
|
+
stderr: () => kept,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The executable a name finds on PATH, with an extension of PATHEXT on Windows. */
|
|
140
|
+
function which(name: string): string | undefined {
|
|
141
|
+
const windows = process.platform === 'win32'
|
|
142
|
+
const extensions = windows ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';') : ['']
|
|
143
|
+
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
|
|
144
|
+
for (const extension of dir === '' ? [] : extensions) {
|
|
145
|
+
const path = join(dir, name + extension)
|
|
146
|
+
if (executable(path, windows)) {
|
|
147
|
+
return path
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return undefined
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function executable(path: string, windows: boolean): boolean {
|
|
155
|
+
try {
|
|
156
|
+
if (!statSync(path).isFile()) {
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
if (!windows) {
|
|
160
|
+
accessSync(path, constants.X_OK)
|
|
161
|
+
}
|
|
162
|
+
return true
|
|
163
|
+
} catch {
|
|
164
|
+
return false
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The platform's package of the server binary, installed beside this one. */
|
|
169
|
+
function packagedBinary(): string | undefined {
|
|
170
|
+
const name = `@tinyshed/tinystore-${process.platform}-${process.arch}`
|
|
171
|
+
const binary = process.platform === 'win32' ? 'tinystore.exe' : 'tinystore'
|
|
172
|
+
try {
|
|
173
|
+
return createRequire(import.meta.url).resolve(`${name}/bin/${binary}`)
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// What Bun's runtime and Node's do alike: an endpoint read into an address, a
|
|
2
|
+
// sidecar started through node:child_process, which both implement, and the
|
|
3
|
+
// last lines of a child's stderr.
|
|
4
|
+
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
|
|
7
|
+
import { ClosedError } from '../errors.ts'
|
|
8
|
+
import type { Child } from '../runtime.ts'
|
|
9
|
+
|
|
10
|
+
/** Where an endpoint named in SERVE, or given to connect, is. */
|
|
11
|
+
export type Address =
|
|
12
|
+
| { kind: 'unix'; path: string }
|
|
13
|
+
| { kind: 'pipe'; path: string }
|
|
14
|
+
| { kind: 'tcp' | 'tls'; host: string; port: number }
|
|
15
|
+
|
|
16
|
+
export function address(endpoint: string): Address {
|
|
17
|
+
if (endpoint.startsWith('unix://')) {
|
|
18
|
+
return { kind: 'unix', path: endpoint.slice('unix://'.length) }
|
|
19
|
+
}
|
|
20
|
+
if (endpoint.startsWith('pipe:')) {
|
|
21
|
+
return { kind: 'pipe', path: `\\\\.\\pipe\\${endpoint.slice('pipe:'.length)}` }
|
|
22
|
+
}
|
|
23
|
+
const remote = /^(tcp|tls):\/\/(\[[^\]]+\]|[^:/]+):(\d+)$/.exec(endpoint)
|
|
24
|
+
if (remote === null) {
|
|
25
|
+
throw new ClosedError(`no transport for the endpoint ${endpoint}`)
|
|
26
|
+
}
|
|
27
|
+
const host = remote[2]!.replace(/^\[|\]$/g, '')
|
|
28
|
+
return { kind: remote[1] as 'tcp' | 'tls', host, port: Number(remote[3]) }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Starts a sidecar that outlives this process, through node:child_process in
|
|
33
|
+
* Bun too, since Bun.spawn starts no process that outlives a Ctrl-C of its
|
|
34
|
+
* parent's group.
|
|
35
|
+
*/
|
|
36
|
+
export function spawnDetached(argv: string[]): Child {
|
|
37
|
+
const child = spawn(argv[0]!, argv.slice(1), {
|
|
38
|
+
detached: true,
|
|
39
|
+
stdio: 'ignore',
|
|
40
|
+
windowsHide: true,
|
|
41
|
+
})
|
|
42
|
+
const exited = new Promise<number>(resolve => {
|
|
43
|
+
child.once('exit', code => resolve(code ?? -1))
|
|
44
|
+
child.once('error', () => resolve(-1))
|
|
45
|
+
})
|
|
46
|
+
child.unref()
|
|
47
|
+
return { exited, kill: () => child.kill() }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** How much of a child's stderr is kept, its last lines, to say why it ended. */
|
|
51
|
+
export const stderrKept = 16 << 10
|
|
52
|
+
|
|
53
|
+
export function lastLines(text: string, n = 5): string {
|
|
54
|
+
return text.trimEnd().split('\n').slice(-n).join('\n')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function exitedWith(code: number, stderr: string): ClosedError {
|
|
58
|
+
return new ClosedError(
|
|
59
|
+
`the private server exited with ${code}${stderr === '' ? '' : `: ${lastLines(stderr)}`}`,
|
|
60
|
+
)
|
|
61
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// What the SDK needs of the runtime it runs in: a byte stream to a server, a
|
|
2
|
+
// child process, a file, a random byte. Everything else is plain TypeScript
|
|
3
|
+
// over Uint8Array, so a runtime other than Bun is one file implementing this.
|
|
4
|
+
|
|
5
|
+
/** What a transport tells the session reading it. */
|
|
6
|
+
export interface TransportEvents {
|
|
7
|
+
data(bytes: Uint8Array): void
|
|
8
|
+
/** the stream ended, cleanly or not; called once */
|
|
9
|
+
end(err: Error): void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A byte stream to a server: a socket, a pipe, or a child's stdin and stdout. */
|
|
13
|
+
export interface Transport {
|
|
14
|
+
/** Writes bytes whole and in order; what the stream does not take yet waits for it. */
|
|
15
|
+
write(bytes: Uint8Array): void
|
|
16
|
+
/** Ends the stream: a socket's close, or a child's stdin, which is its end. */
|
|
17
|
+
close(): void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TlsOptions {
|
|
21
|
+
/** the certificates to trust besides the system's, PEM */
|
|
22
|
+
ca?: string | string[]
|
|
23
|
+
/** the name the certificate must carry, the endpoint's host when absent */
|
|
24
|
+
serverName?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A process the SDK started. */
|
|
28
|
+
export interface Child {
|
|
29
|
+
/** its exit code once it has exited */
|
|
30
|
+
readonly exited: Promise<number>
|
|
31
|
+
kill(): void
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A private server: a child whose stdin and stdout are the connection. */
|
|
35
|
+
export interface PrivateChild extends Child {
|
|
36
|
+
readonly transport: Transport
|
|
37
|
+
/** the last lines it wrote to stderr, which say why it ended */
|
|
38
|
+
stderr(): string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface Runtime {
|
|
42
|
+
/** a name and version for the server's logs: tinystore-js on bun/1.4.2 */
|
|
43
|
+
readonly client: string
|
|
44
|
+
readonly windows: boolean
|
|
45
|
+
/** Connects to an endpoint: unix://path, pipe:name, tcp://host:port or tls://host:port. */
|
|
46
|
+
connect(endpoint: string, events: TransportEvents, tls?: TlsOptions): Promise<Transport>
|
|
47
|
+
/** Starts a private server whose stdin and stdout carry the frames. */
|
|
48
|
+
spawnPrivate(argv: string[], events: TransportEvents): PrivateChild
|
|
49
|
+
/** Starts a process that outlives this one, with no stdio to read. */
|
|
50
|
+
spawnDetached(argv: string[]): Child
|
|
51
|
+
/** A file's bytes, opened, read and closed at once; undefined when it is not there. */
|
|
52
|
+
readFile(path: string): Promise<Uint8Array | undefined>
|
|
53
|
+
/** The executable a name finds on PATH. */
|
|
54
|
+
which(name: string): string | undefined
|
|
55
|
+
/** The server binary a package of this runtime carries for this platform. */
|
|
56
|
+
packagedBinary(): string | undefined
|
|
57
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Standard Schema, https://standardschema.dev: the interface zod, valibot and
|
|
2
|
+
// arktype each implement, copied here as the spec asks rather than depended on.
|
|
3
|
+
|
|
4
|
+
/** A schema that checks a value and may give back one of another type. */
|
|
5
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
6
|
+
readonly '~standard': StandardSchemaV1.Props<Input, Output>
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export declare namespace StandardSchemaV1 {
|
|
10
|
+
export interface Props<Input = unknown, Output = Input> {
|
|
11
|
+
readonly version: 1
|
|
12
|
+
readonly vendor: string
|
|
13
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>
|
|
14
|
+
readonly types?: Types<Input, Output> | undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type Result<Output> = SuccessResult<Output> | FailureResult
|
|
18
|
+
|
|
19
|
+
export interface SuccessResult<Output> {
|
|
20
|
+
readonly value: Output
|
|
21
|
+
readonly issues?: undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface FailureResult {
|
|
25
|
+
readonly issues: ReadonlyArray<Issue>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Issue {
|
|
29
|
+
readonly message: string
|
|
30
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PathSegment {
|
|
34
|
+
readonly key: PropertyKey
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Types<Input = unknown, Output = Input> {
|
|
38
|
+
readonly input: Input
|
|
39
|
+
readonly output: Output
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<
|
|
43
|
+
Schema['~standard']['types']
|
|
44
|
+
>['output']
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isSchema(value: unknown): value is StandardSchemaV1 {
|
|
48
|
+
return typeof value === 'object' && value !== null && '~standard' in value
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The value a schema gives back, or the issues it found, spelled as one line. */
|
|
52
|
+
export async function check<T>(
|
|
53
|
+
schema: StandardSchemaV1<unknown, T>,
|
|
54
|
+
value: unknown,
|
|
55
|
+
): Promise<{ value: T } | { issues: string }> {
|
|
56
|
+
const result = await schema['~standard'].validate(value)
|
|
57
|
+
if (result.issues === undefined) {
|
|
58
|
+
return { value: result.value }
|
|
59
|
+
}
|
|
60
|
+
const issues = result.issues
|
|
61
|
+
.map(issue => {
|
|
62
|
+
const path = issue.path
|
|
63
|
+
?.map(segment => String(typeof segment === 'object' ? segment.key : segment))
|
|
64
|
+
.join('.')
|
|
65
|
+
return path === undefined || path === '' ? issue.message : `${path}: ${issue.message}`
|
|
66
|
+
})
|
|
67
|
+
.join('; ')
|
|
68
|
+
return { issues }
|
|
69
|
+
}
|