Skip to content

Commit

Permalink
Remove usage of assert.invariant
Browse files Browse the repository at this point in the history
This reduces dependencies when building for the browser target, since
the assert module is a Node.js dependency. Simply replacing them with
an `if` statement is sufficient.
  • Loading branch information
eliandoran committed Jun 30, 2024
1 parent 4973436 commit 51d8735
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import invariant from 'assert'
import { isInteger, getByteLength } from './helpers'

function getClassNamespace(item: any, scope: Record<string, any>) {
Expand Down Expand Up @@ -59,7 +58,9 @@ export default function serialize(
const constructorName = getClassNamespace(item, scope)
if (typeof item.serialize === 'function') {
const serialized = item.serialize()
invariant(typeof serialized === 'string', `${item.constructor.name}.serialize should return a string`)
if (typeof serialized !== 'string') {
throw new Error(`${item.constructor.name}.serialize should return a string`);
}
return `C:${constructorName.length}:"${constructorName}":${getByteLength(serialized, options)}:{${serialized}}`
}
return `O:${constructorName.length}:"${constructorName}":${serializeObject(item, scope)}`
Expand Down
9 changes: 6 additions & 3 deletions src/unserialize.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import invariant from 'assert'
// eslint-disable-next-line import/no-cycle
import Parser from './parser'
import { isInteger, getClass, getIncompleteClass, __PHP_Incomplete_Class } from './helpers'
Expand All @@ -11,7 +10,9 @@ export type Options = {
function getClassReference(className: string, scope: Record<string, any>, strict: boolean): any {
let container: any
const classReference = scope[className]
invariant(classReference || !strict, `Class ${className} not found in given scope`)
if (!classReference && strict) {
throw new Error(`Class ${className} not found in given scope`);
}
if (classReference) {
// @ts-ignore
container = new (getClass(classReference.prototype))()
Expand Down Expand Up @@ -93,7 +94,9 @@ function unserializeItem(parser: Parser, scope: Record<string, any>, options: Op
const payload = parser.getByLength('{', '}', length => parser.readAhead(length))
const result = getClassReference(name, scope, options.strict)
if (!(result instanceof __PHP_Incomplete_Class)) {
invariant(result.unserialize, `unserialize not found on class when processing '${name}'`)
if (!result.unserialize) {
throw new Error(`unserialize not found on class when processing '${name}'`);
}
result.unserialize(payload)
}
return result
Expand Down

0 comments on commit 51d8735

Please sign in to comment.