Skip to content

Commit

Permalink
feat: feature complete 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
weiran committed Aug 24, 2023
0 parents commit 07b6566
Show file tree
Hide file tree
Showing 16 changed files with 494 additions and 0 deletions.
45 changes: 45 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: CI
on:
push:
branches:
- main
- node
- node-ts
pull_request:
branches:
- main
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16.x'
- name: Install dependencies
run: npm install
- name: Lint files
run: npm run lint
test:
name: Test
strategy:
matrix:
os: [ubuntu-latest]
node: [17.x, 16.x, 14.x, 12.x, "12.22.0"]
include:
- os: windows-latest
node: "16.x"
- os: macOS-latest
node: "16.x"
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node }}
- name: Install dependencies
run: npm install
- name: Run tests
run: npm run test
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/node_modules
dist
coverage/
npm-debug.log
.DS_Store
.idea
*.iml
.cache
.sublimelinterrc
.eslintcache
5 changes: 5 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
npx lint-staged
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# set to true if you are developing an app.
package-lock=false
3 changes: 3 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"recommendations": ["dbaeumer.vscode-eslint"]
}
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.experimental.useFlatConfig": true,
}
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

### [0.0.3](https://git.dian.so/weiren/safe-json-parser/compare/v0.0.2...v0.0.3) (2023-08-21)


### Bug Fixes

* parse floating number ([8457fb3](https://git.dian.so/weiren/safe-json-parser/commit/8457fb3e45bd6daa6f7fbc7ddf157c485e91773d))

### [0.0.2](https://git.dian.so/weiren/safe-json-parser/compare/v0.0.1...v0.0.2) (2023-08-16)


### Bug Fixes

* stringify bigint ([3ebc513](https://git.dian.so/weiren/safe-json-parser/commit/3ebc5136a5a37bd53a1ee43dc13bac5175012735))

### 0.0.1 (2023-08-15)


### Features

* add ts support ([7ee0054](https://git.dian.so/weiren/safe-json-parser/commit/7ee005400b3eea8158d30403fb06964fbda35ee7))
* first impl ([9d97b20](https://git.dian.so/weiren/safe-json-parser/commit/9d97b204f44ee09915352d2a433828caed50cc2d))
* init repo ([255d82e](https://git.dian.so/weiren/safe-json-parser/commit/255d82e7a582908133da66adec380eee6de06fbc))
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 唯然

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15 changes: 15 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import jsPlugin from '@eslint/js'
import esmConfig from 'eslint-plugin-n/configs/recommended-module.js'
import cjsConfig from 'eslint-plugin-n/configs/recommended-script.js'

export default [
jsPlugin.configs.recommended,
{
files: ['**/*.{js,mjs}'],
...esmConfig,
},
{
files: ['**/*.cjs'],
...cjsConfig,
},
]
71 changes: 71 additions & 0 deletions lib/jsonb.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* @fileoverview JSONB parser and stringifier
* @author 唯然<[email protected]>
*/
'use strict'
const { parseJson } = require('@ton.js/json-parser')
const isBNSupported = typeof BigInt !== 'undefined'
const BN = isBNSupported ? BigInt : (x) => x

function parse(s) {
function reviver(k, v, ctx) {
let isSafe = true

const isInt = typeof v === 'number' && /^(-)?\d+$/.test(ctx.source)
// 如果是整数的话,也要检查是否超过了安全整数范围
if (isInt) {
isSafe = Number.isSafeInteger(v)
}

return isSafe ? v : BN(ctx.source)
}

return parseJson(s, reviver)
}

function stringify(data) {
if (data === undefined) return undefined
if (data === null) return 'null'
if (Number.isNaN(data)) return 'null'
if (data === Infinity) return 'null'
if (data.constructor === String) return '"' + data.replace(/"/g, '\\"') + '"'
if (data.constructor === Number) return String(data)
if (isBNSupported && data.constructor === BigInt) return String(data) // 避免bigint精度丢失
if (data.constructor === Boolean) return data ? 'true' : 'false'
if (data.constructor === Array)
return (
'[' +
data
.reduce((acc, v) => {
if (
v === undefined ||
Number.isNaN(v) ||
v === Infinity ||
v === -Infinity
)
return [...acc, 'null']
else return [...acc, stringify(v)]
}, [])
.join(',') +
']'
)

if (data.constructor === Object)
return (
'{' +
Object.keys(data)
.reduce((acc, k) => {
if (data[k] === undefined) return acc
else return [...acc, stringify(k) + ':' + stringify(data[k])]
}, [])
.join(',') +
'}'
)

return ''
}

module.exports = {
parse,
stringify,
}
6 changes: 6 additions & 0 deletions lib/jsonb.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function parse<T>(s: string, bn?: any[]): T
export function stringify(obj: any): string
export namespace JSONB {
export { parse }
export { stringify }
}
67 changes: 67 additions & 0 deletions lib/jsonb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* @fileoverview JSONB parser and stringifier
* @author 唯然<[email protected]>
*/
import { parseJson } from '@ton.js/json-parser'
const isBNSupported = typeof BigInt !== 'undefined'
const BN = isBNSupported ? BigInt : (x) => x

export function parse(s) {
function reviver(k, v, ctx) {
let isSafe = true

const isInt = typeof v === 'number' && /^(-)?\d+$/.test(ctx.source)
// 如果是整数的话,也要检查是否超过了安全整数范围
if (isInt) {
isSafe = Number.isSafeInteger(v)
}

return isSafe ? v : BN(ctx.source)
}

return parseJson(s, reviver)
}

function stringify(data) {
if (data === undefined) return undefined
if (data === null) return 'null'
if (Number.isNaN(data)) return 'null'
if (data === Infinity || data === -Infinity) return 'null'
if (data.constructor === String) return '"' + data.replace(/"/g, '\\"') + '"'
if (data.constructor === Number) return String(data)
if (isBNSupported && data.constructor === BigInt) return String(data) // 避免bigint精度丢失
if (data.constructor === Boolean) return data ? 'true' : 'false'
if (data.constructor === Array)
return (
'[' +
data
.reduce((acc, v) => {
if (
v === undefined ||
Number.isNaN(v) ||
v === Infinity ||
v === -Infinity
)
return [...acc, 'null']
else return [...acc, stringify(v)]
}, [])
.join(',') +
']'
)

if (data.constructor === Object)
return (
'{' +
Object.keys(data)
.reduce((acc, k) => {
if (data[k] === undefined) return acc
else return [...acc, stringify(k) + ':' + stringify(data[k])]
}, [])
.join(',') +
'}'
)

throw new Error(`Unsupported type: ${data.constructor.name}`)
}

export default { parse, stringify }
99 changes: 99 additions & 0 deletions lib/jsonb.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import test from 'node:test'
import { strict as assert } from 'node:assert'
import JSONB from './jsonb.js'

test('parse jsonb: obj', () => {
const content = '{ "foo": { "bar": { "value": 12345678901234567890 } } }'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed.foo.bar.value, 'bigint')
assert.strictEqual(parsed.foo.bar.value, 12345678901234567890n)
})

test('parse jsonb: neg', () => {
const content = '{ "value": -12345678901234567890 }'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed.value, 'bigint')
assert.strictEqual(parsed.value, -12345678901234567890n)
})

test('parse jsonb: floating', () => {
const content = '{ "value": 1.0 }'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed.value, 'number')
assert.strictEqual(parsed.value, 1.0)
})

test('parse jsonb: arr', () => {
const content = '[ 1, 12345678901234567890 ]'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed[0], 'number')
assert.strictEqual(parsed[0], 1)

assert.strictEqual(typeof parsed[1], 'bigint')
assert.strictEqual(parsed[1], 12345678901234567890n)
})

test('parse jsonb: str', () => {
const content = '{"value": "foo"}'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed.value, 'string')
assert.strictEqual(parsed.value, 'foo')
})

test('parse jsonb: bool', () => {
const content = '{"value": true}'
const parsed = JSONB.parse(content)

assert.strictEqual(typeof parsed.value, 'boolean')
assert.strictEqual(parsed.value, true)
})

test('stringify jsonb', () => {
const obj = { foo: { bar: { value: 12345678901234567890n } } }
const str = JSONB.stringify(obj)

assert.strictEqual(str, '{"foo":{"bar":{"value":12345678901234567890}}}')
})

test('stringify jsonb: arr', () => {
const obj = [1, 12345678901234567890n]
const str = JSONB.stringify(obj)

assert.strictEqual(str, '[1,12345678901234567890]')
})

test('stringify jsonb: bool', () => {
const obj = true
const str = JSONB.stringify(obj)

assert.strictEqual(str, 'true')
})

test('stringify jsonb: number', () => {
const obj = 123
const str = JSONB.stringify(obj)

assert.strictEqual(str, '123')
})

test('stringify jsonb: neg number', () => {
const obj = -123
const str = JSONB.stringify(obj)

assert.strictEqual(str, '-123')
})

test('stringify jsonb: obj', () => {
const obj = { foo: true, bar: 1n, quz: true, baz: [-1, 2, 3n], qux: null }
const str = JSONB.stringify(obj)

assert.strictEqual(
str,
'{"foo":true,"bar":1,"quz":true,"baz":[-1,2,3],"qux":null}',
)
})
Loading

0 comments on commit 07b6566

Please sign in to comment.