Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions error.mjs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export class SendScriptError extends Error {}
export class SendScriptReferenceError extends SendScriptError {}
export class SendScriptSerializationError extends SendScriptError {}
21 changes: 20 additions & 1 deletion index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { test } from 'tap'
import Stringify from './stringify.mjs'
import references from './references.mjs'
import Parse from './parse.mjs'
import { SendScriptSerializationError } from './error.mjs'

const order = []

Expand Down Expand Up @@ -225,12 +226,30 @@ test('should evaluate basic expressions correctly', async (t) => {
t.end()
})

t.test('throws if stringify returns undefined', t => {
// This is to prevent accidentally sending payloads that make little sense.

// Check if it throw the expected error type.
try {
run(undefined)
} catch (error) {
t.ok(error instanceof SendScriptSerializationError)
}

t.throws(() => run(undefined))
t.throws(() => run(new Set()))
t.throws(() => run(identity(undefined)))
t.throws(() => run(() => {}))

t.end()
})

t.test('basic types and identity', (t) => {
t.equal(run(identity(null)), null)
t.equal(run(identity(undefined)), null)
t.equal(run(noop()), undefined)
t.equal(run(identity(1)), 1)
t.strictSame(run(identity([])), [])
t.strictSame(run(identity({})), {})
t.strictSame(run(identity([identity(1), 2, 3])), [1, 2, 3])
t.strictSame(run(always('hello')()), 'hello')
t.end()
Expand Down
13 changes: 12 additions & 1 deletion stringify.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Debug from './debug.mjs'
import { SendScriptSerializationError } from './error.mjs'
import {
awaitSymbol,
call,
Expand Down Expand Up @@ -69,7 +70,17 @@ function transformValue (value, leafSerializer) {
return ['leaf', leafSerializer(value)]
}

export default function stringify (leafSerializer = JSON.stringify) {
function strictStringify (x) {
const typeOf = typeof x

if (typeOf === 'object' || typeOf === 'function' || x === undefined) {
throw new SendScriptSerializationError(`Cannot and should not attempt to serialize ${x}`)
}

return JSON.stringify(x)
}

export default function stringify (leafSerializer = strictStringify) {
function stringify (program) {
return JSON.stringify(transformValue(program, leafSerializer))
}
Expand Down