UNPKG

jsonc-simple-parser

Version:

A simple JSON parser that supports comments and optional trailing commas.

53 lines (52 loc) 1.6 kB
/* IMPORT */ import Utils from '../utils.js'; import Context from './context.js'; /* HELPERS */ const makeChild = (type) => (values) => { const source = values[0]; Context.offset += source.length; return { type, source }; }; const makeParent = (type) => (values) => { const children = values.flat(); return { type, children }; }; /* MAIN */ const Tokens = { EarlyReturn: () => { if (Context.offset > Context.offsetMax) return []; }, Insufficient: (values) => { if (values[0].length) Tokens.Invalid(values); throw new SyntaxError('Unexpected end of JSONC input'); }, Invalid: (values) => { throw new SyntaxError(`Unexpected token ${values[0]} in JSONC at position ${Context.offset}`); }, Passthrough: (values) => { return values.flat().filter(Utils.isToken); }, Newline: makeChild('Newline'), Whitespace: makeChild('Whitespace'), CommentLine: makeChild('CommentLine'), CommentBlock: makeChild('CommentBlock'), Comma: makeChild('Comma'), CommaTrailing: makeChild('CommaTrailing'), Colon: makeChild('Colon'), Null: makeChild('Null'), True: makeChild('True'), False: makeChild('False'), Number: makeChild('Number'), String: makeChild('String'), ArrayOpen: makeChild('ArrayOpen'), ArrayClose: makeChild('ArrayClose'), Array: makeParent('Array'), ObjectOpen: makeChild('ObjectOpen'), ObjectClose: makeChild('ObjectClose'), Object: makeParent('Object'), Root: makeParent('Root') }; /* EXPORT */ export default Tokens;