Skip to content

Commit

Permalink
Add json and jsonz fragment methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jcreedcmu committed Mar 20, 2024
1 parent d2efe0e commit aad68a6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
23 changes: 20 additions & 3 deletions src/encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,22 @@ export function encodeWithV1(text: string): string {
}

export async function encodeWithV2(text: string): Promise<string> {
const x1 = bytesOfString(text);
const encoded = encodeURIComponent(base64OfBytes(await compressedOf(bytesOfString(text))).str);
return 'v2/' + encoded;
}

export function encodeWithJson(action: FragmentAction): string {
const encoded = encodeURIComponent(base64OfBytes(bytesOfString(JSON.stringify(action))).str);
return 'json/' + encoded;
}

export async function encodeWithJsonz(action: FragmentAction): Promise<string> {
const encoded = encodeURIComponent(base64OfBytes(await compressedOf(bytesOfString(JSON.stringify(action)))).str);
return 'jsonz/' + encoded;
}

export async function encode(text: string): Promise<string> {
return encodeWithV2(text);
return encodeWithJsonz({ t: 'setTextAndExec', text });
}

export type FragmentAction =
Expand All @@ -46,7 +55,15 @@ export type FragmentAction =

export async function decode(fragment: string): Promise<FragmentAction> {
const uridecoded = decodeURIComponent(fragment);
if (uridecoded.match(/^v2\//)) {
if (uridecoded.match(/^json\//)) {
const stripPrefix = uridecoded.replace(/json\//, '');
return JSON.parse(stringOfBytes(bytesOfBase64({ t: 'base64', str: stripPrefix }))) as FragmentAction;
}
else if (uridecoded.match(/^jsonz\//)) {
const stripPrefix = uridecoded.replace(/jsonz\//, '');
return JSON.parse(stringOfBytes(await decompressedOf(bytesOfBase64({ t: 'base64', str: stripPrefix }))));
}
else if (uridecoded.match(/^v2\//)) {
const stripPrefix = uridecoded.replace(/v2\//, '');
return {
t: 'setTextAndExec',
Expand Down
6 changes: 5 additions & 1 deletion tests/test-encoding.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { decode, encodeWithV1, encodeWithV2 } from "../src/encoding";
import { decode, encodeWithJson, encodeWithV1, encodeWithV2 } from "../src/encoding";


const exampleTwelf = `
Expand All @@ -11,6 +11,10 @@ describe('url encoding', () => {
expect(await decode(encodeWithV1(exampleTwelf))).toEqual({ t: 'setTextAndExec', text: exampleTwelf });
});

test('should roundtrip with json', async () => {
expect(await decode(encodeWithJson({ t: 'setTextAndExec', text: exampleTwelf }))).toEqual({ t: 'setTextAndExec', text: exampleTwelf });
});

// I'd like to test v2 in nodejs, but I need to figure out a strategy
// for polyfilling Blob and CompressionStream

Expand Down

0 comments on commit aad68a6

Please sign in to comment.