Skip to content

Commit

Permalink
Fix identifier checking
Browse files Browse the repository at this point in the history
  • Loading branch information
lxsmnsyc committed Mar 17, 2023
1 parent 59b6756 commit bd157e3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
7 changes: 3 additions & 4 deletions packages/seroval/src/tree/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
markRef,
} from '../context';
import quote from '../quote';
import { isValidIdentifier } from './shared';
import { SYMBOL_STRING } from './symbols';
import {
SerovalAggregateErrorNode,
Expand Down Expand Up @@ -191,8 +192,6 @@ function isReferenceInStack(
return node.t === SerovalNodeType.Reference && ctx.stack.includes(node.i);
}

const IDENTIFIER_CHECK = /^([$A-Z_][0-9A-Z_$]*)$/i;

function serializeNodeList(
ctx: SerializationContext,
node: SerovalArrayNode | SerovalIterableNode | SerovalAggregateErrorNode,
Expand Down Expand Up @@ -262,7 +261,7 @@ function serializeProperties(
check = Number(key);
// Test if key is a valid number or JS identifier
// so that we don't have to serialize the key and wrap with brackets
isIdentifier = check >= 0 || IDENTIFIER_CHECK.test(key);
isIdentifier = check >= 0 || isValidIdentifier(key);
if (isReferenceInStack(ctx, val)) {
refParam = getRefParam(ctx, val.i);
if (isIdentifier && Number.isNaN(check)) {
Expand Down Expand Up @@ -320,7 +319,7 @@ function serializeAssignments(
ctx.assignments = mainAssignments;
// Test if key is a valid number or JS identifier
// so that we don't have to serialize the key and wrap with brackets
isIdentifier = check >= 0 || IDENTIFIER_CHECK.test(key);
isIdentifier = check >= 0 || isValidIdentifier(key);
if (isIdentifier && Number.isNaN(check)) {
createObjectAssign(ctx, sourceID, key, refParam);
} else {
Expand Down
12 changes: 12 additions & 0 deletions packages/seroval/src/tree/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,15 @@ export function getTypedArrayConstructor(name: string) {
throw new Error(`Unknown TypedArray "${name}"`);
}
}

const IDENTIFIER_CHECK = /^[$A-Z_][0-9A-Z_$]*$/i;

export function isValidIdentifier(name: string) {
const char = name[0];
return (
char === '$'
|| char === '_'
|| (char >= 'A' && char <= 'Z')
|| (char >= 'a' && char <= 'z')
) && IDENTIFIER_CHECK.test(name);
}

0 comments on commit bd157e3

Please sign in to comment.