Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

fs-write.ts

35 lines1.1 KB

1/**
2 * Build in-container `sh -c` commands that write a file without putting the
3 * whole payload on one argv.
4 *
5 * Linux `MAX_ARG_STRLEN` is 128 KiB for a single argument. A snapshot restore
6 * of a lockfile or generated source exceeds that when the bytes are quoted
7 * into `printf`.
8 */
9​
10/** Stay well under `MAX_ARG_STRLEN` after base64 and quoting. */
11export const FS_WRITE_BYTE_CHUNK = 32_768
12​
13function quote(value: string): string {
14 return `'${value.replace(/'/g, `'\\''`)}'`
16​
17export function fsWriteCommands(
18 abs: string,
19 data: string | Uint8Array,
20): Array<string> {
21 const bytes =
22 typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data)
23 const dir = abs.replace(/\/[^/]*$/, '') || '/'
24 const commands = [`mkdir -p ${quote(dir)} && : > ${quote(abs)}`]
25 for (
26 let offset = 0;
27 offset < bytes.byteLength;
28 offset += FS_WRITE_BYTE_CHUNK
29 ) {
30 const slice = bytes.subarray(offset, offset + FS_WRITE_BYTE_CHUNK)
31 const b64 = Buffer.from(slice).toString('base64')
32 commands.push(`printf %s ${quote(b64)} | base64 -d >> ${quote(abs)}`)
33 }
34 return commands