Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support raw conversion in envs without Buffer #364

Merged
merged 5 commits into from
Dec 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,13 @@ export function stringify(value: any): string {
throw new Error("[unstorage] Cannot stringify value!");
}

function checkBufferSupport() {
if (typeof Buffer === "undefined") {
throw new TypeError("[unstorage] Buffer is not supported!");
}
}

export const BASE64_PREFIX = "base64:";

export function serializeRaw(value: any) {
if (typeof value === "string") {
return value;
}
checkBufferSupport();
const base64 = Buffer.from(value).toString("base64");
return BASE64_PREFIX + base64;
return BASE64_PREFIX + base64Encode(value);
}

export function deserializeRaw(value: any) {
Expand All @@ -72,6 +64,22 @@ export function deserializeRaw(value: any) {
// Return unknown strings as-is
return value;
}
checkBufferSupport();
return Buffer.from(value.slice(BASE64_PREFIX.length), "base64");
return base64Decode(value.slice(BASE64_PREFIX.length));
}

function base64Decode(input: string) {
if (globalThis.Buffer) {
return Buffer.from(input, "base64");
}
return Uint8Array.from(
globalThis.atob(input),
(c) => c.codePointAt(0) as number
);
}

function base64Encode(input: Uint8Array) {
if (globalThis.Buffer) {
return Buffer.from(input).toString("base64");
}
return globalThis.btoa(String.fromCodePoint(...input));
}
Loading