the editable site (validation-lab)
This commit is contained in:
commit
3ac81d5a52
13454 files changed
+2227005
No files matched your search
+24
@@ -0,0 +1,24 @@
|
||||
Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+605
@@ -0,0 +1,605 @@
|
||||
# smol-toml
|
||||
[](https://toml.io/en/v1.1.0)
|
||||
[](https://github.com/squirrelchat/smol-toml/blob/mistress/LICENSE)
|
||||
[](https://npmx.dev/smol-toml)
|
||||
[](https://github.com/squirrelchat/smol-toml/actions/workflows/build.yaml)
|
||||
|
||||
[](https://github.com/sponsors/cyyynthia)
|
||||
[](https://npmx.dev/smol-toml)
|
||||
[](https://npmx.dev/smol-toml)
|
||||
|
||||
A small, fast, and correct TOML parser and serializer. smol-toml is fully spec-compliant with TOML v1.1.0, passing
|
||||
all[^toml-test-asterisk] tests from the [official `toml-test` suite](https://github.com/toml-lang/toml-test).
|
||||
|
||||
[^toml-test-asterisk]: By default, certain invalid datetimes (e.g. `2020-02-30`) are gracefully accepted. Due to
|
||||
JavaScript's lax handling of Unicode, some invalid byte sequences are accepted. Requires using the `integersAsBigInt`
|
||||
option for full type preservation. Use the `run-toml-test.bash` script to run the tests.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> - By default, the behaviour regarding integers doesn't preserve type information, nor does it allow deserializing
|
||||
> integers larger than 53 bits. See [Integers](#integers).
|
||||
> - The library currently uses the legacy `Date` object by default. See [Date, Time, and Datetime](#date-time-and-datetime).
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { parse, stringify } from 'smol-toml'
|
||||
|
||||
const doc = '...'
|
||||
const parsed = parse(doc)
|
||||
console.log(parsed)
|
||||
|
||||
const toml = stringify(parsed)
|
||||
console.log(toml)
|
||||
```
|
||||
|
||||
Alternatively, if you prefer something similar to the JSON global, you can import the library as follows
|
||||
```js
|
||||
import * as TOML from 'smol-toml'
|
||||
|
||||
TOML.stringify({ ... })
|
||||
```
|
||||
|
||||
A few notes on the `stringify` function:
|
||||
- `undefined` and `null` values on objects are ignored (they do not produce a key/value).
|
||||
- `undefined` and `null` values in arrays are **rejected**.
|
||||
- Functions, classes and symbols are **rejected**.
|
||||
- By default, floats will be serialized as integers if they don't have a decimal part.
|
||||
- i.e. `stringify(parse('a = 1.0'))` will produce `a = 1`, despite the source value being a float.
|
||||
- See [Integers](#integers) for end-to-end type preservation using `BigInt`.
|
||||
- JS `Date` will be serialized as an Offset Date-Time in UTC.
|
||||
- Use the [Temporal API] for representing other types (or alternatively the legacy [`TomlDate` object](#tomldate-object)).
|
||||
|
||||
### Options
|
||||
|
||||
Both `parse` and `stringify` accept an options object as 2nd argument.
|
||||
|
||||
#### Parse options
|
||||
|
||||
| Option | Type | Default | Description | Introduced in |
|
||||
|----------------------|-------------------------------|----------|-----------------------------------------------------------------------------------------------------------------|---------------|
|
||||
| `integersAsBigInt` | `boolean \| 'asNeeded'` | `false` | Parse integers as `BigInt`. See [Integers](#integers). | 1.4.0 |
|
||||
| `useLegacyDate` | `boolean` | `true` | Use the legacy `TomlDate` instead of the Temporal API. See [Date, Time, and Datetime](#date-time-and-datetime). | 1.9.0 |
|
||||
| `unsafeKeyBehaviour` | `'keep' \| 'drop' \| 'throw'` | `'keep'` | Reject potentially dangerous keys such as `__proto__` or `constructor`. See [Key safety](#key-safety). | 1.9.0 |
|
||||
|
||||
##### Key safety
|
||||
|
||||
Internally, `smol-toml` is protected against prototype pollution and will correctly assign a plain property named e.g.
|
||||
`__proto__` on the object, similar to what JavaScript-native `JSON.parse` does.
|
||||
|
||||
However, careless use of the object returned by the parser in your application code may lead to prototype pollution.
|
||||
This is for instance the case in this example taken from Fastify's `secure-json-parse` helper which exists to address
|
||||
this caveat.
|
||||
|
||||
```js
|
||||
import { parse } from 'smol-toml'
|
||||
|
||||
const a = parse('__proto__.b = 5')
|
||||
console.log(a.b) // ~> undefined
|
||||
|
||||
const b = Object.assign({}, a)
|
||||
console.log(b.b) // ~> 5
|
||||
```
|
||||
|
||||
Similarly to `secure-json-parse`, the library offers 3 modes to deal with these keys:
|
||||
- `keep` (default): preserve potentially unsafe properties and return the object as-is.
|
||||
- `drop`: silently drop potentially unsafe properties, returning the object as if the properties were not there.
|
||||
- `throw`: reject documents with potentially unsafe properties and throw a `TomlError`.
|
||||
|
||||
#### Stringify options
|
||||
|
||||
| Option | Type | Default | Description | Introduced in |
|
||||
|------------------|-----------|------------|--------------------------------------------------------------------------------------------------------------------------------|---------------|
|
||||
| `numbersAsFloat` | `boolean` | `false` | Always render plain numbers as floating point values. See [Type preservation](#type-preservation). | 1.4.0 |
|
||||
| `strictTemporal` | `boolean` | `false` | Reject Temporal values with an IANA timezone or a calendar. See [IANA timezones and calendars](#iana-timezones-and-calendars). | 1.9.0 |
|
||||
|
||||
## Dealing with values
|
||||
|
||||
### Integers
|
||||
|
||||
When parsing, both integers and floats are parsed as plain JavaScript numbers by default, which are double-precision
|
||||
floating point numbers. That means that the library does not preserve type information between e.g. `1.0` and `1`, and
|
||||
that it is not able to parse integers beyond 53 bits.
|
||||
|
||||
While this is sufficient for the vast majority of use-cases, if support of larger integers is needed, it is possible
|
||||
to [enable BigInt support](#enabling-bigint).
|
||||
|
||||
When serializing, numbers without a decimal part are serialized as integers (except if they're outside of the safe
|
||||
range; i.e. they cannot be represented as a signed 53-bit integer). This is generally a good enough heuristic for most
|
||||
usages, but it is possible to leverage BigInts for [full type preservation](#type-preservation).
|
||||
|
||||
#### Enabling BigInt
|
||||
|
||||
To parse integers beyond 53 bits, it's possible to tell the parser to return all integers as BigInt. This will
|
||||
therefore preserve the type information at the cost of using a more expensive container (approx. 5% slowdown).
|
||||
|
||||
```js
|
||||
import { parse } from 'smol-toml'
|
||||
|
||||
const doc = '...'
|
||||
const parsed = parse(doc, { integersAsBigInt: true })
|
||||
```
|
||||
|
||||
If you want to only use BigInt for numbers that cannot safely be represented as plain JavaScript numbers, you can pass
|
||||
`"asNeeded"` instead.
|
||||
|
||||
##### Type preservation
|
||||
|
||||
To get end-to-end type preservation, you can tell the serializer to always treat numbers as floating point numbers.
|
||||
Then, only BigInts will be serialized as integers and numbers without a decimal part will still be serialized as float.
|
||||
|
||||
```js
|
||||
import { stringify } from 'smol-toml'
|
||||
|
||||
const obj = { ... }
|
||||
const toml = stringify(obj, { numbersAsFloat: true })
|
||||
```
|
||||
|
||||
### Date, Time, and Datetime
|
||||
|
||||
`smol-toml` can emit time-related types in 2 ways: the modern [Temporal API], or the legacy (_but currently default_)
|
||||
`Date` object, using a custom [`TomlDate` object](#tomldate-object).
|
||||
|
||||
> [!NOTE]
|
||||
> While `TomlDate` is 2-3x faster than Temporal in microbenchmarks, the performance difference in practice on parse
|
||||
> time is insignificant (or even slower[^temporal-slow-or-fast]) for `smol-toml`. See the [benchmarks](#benchmarks).
|
||||
>
|
||||
> `TomlDate` is limited to millisecond precision and has a more lax behaviour. It gracefully accepts certain invalid
|
||||
> inputs, such as "the 30th of February", converting it to the 2nd (or 1st) of March. The Temporal implementation is
|
||||
> stricter and properly rejects these invalid dates.
|
||||
>
|
||||
> The next major version of the library will use Temporal by default.
|
||||
|
||||
[^temporal-slow-or-fast]: The `Temporal` implementation dispatches more instructions to the CPU; however, it is much
|
||||
more friendly to the branch predictor. At the microarchitecture level, this allows the CPU
|
||||
to reach a higher number of _instructions per clock_, which results in a net positive
|
||||
performance impact. The CPU has to do _more_, but it can do it _faster_.
|
||||
|
||||
The different TOML types and Temporal types are mapped as described below.
|
||||
|
||||
#### TOML type to Temporal mapping
|
||||
|
||||
| TOML type | Temporal type |
|
||||
|----------------------------------------------------------------|----------------------------|
|
||||
| [Offset Date-Time](https://toml.io/en/v1.1.0#offset-date-time) | [`Temporal.ZonedDateTime`] |
|
||||
| [Local Date-Time](https://toml.io/en/v1.1.0#local-date-time) | [`Temporal.PlainDateTime`] |
|
||||
| [Local Date](https://toml.io/en/v1.1.0#local-date) | [`Temporal.PlainDate`] |
|
||||
| [Local Time](https://toml.io/en/v1.1.0#local-time) | [`Temporal.PlainTime`] |
|
||||
|
||||
#### Temporal to TOML type mapping
|
||||
|
||||
| Temporal type | TOML type | Notes |
|
||||
|-----------------------------|----------------------------------------------------------------|----------------------------------------------------------------------------------|
|
||||
| [`Temporal.Duration`] | **Unsupported** (throws) | There is an ongoing [feature request][toml-lang/toml#514] and an [active proposal][toml-lang/toml#1105]. Note that the current draft does not allow multi-part values (e.g. `1min 20sec`), making it likely that `Duration` will not always be convertible to a TOML value. |
|
||||
| [`Temporal.Instant`] | [Offset Date-Time](https://toml.io/en/v1.1.0#offset-date-time) | Always in UTC. |
|
||||
| [`Temporal.PlainDate`] | [Local Date](https://toml.io/en/v1.1.0#local-date) | Calendar info lost, [see below](#iana-timezones-and-calendars). |
|
||||
| [`Temporal.PlainDateTime`] | [Local Date-Time](https://toml.io/en/v1.1.0#local-date-time) | Calendar info lost, [see below](#iana-timezones-and-calendars). |
|
||||
| [`Temporal.PlainMonthDay`] | **Unsupported** (throws) | |
|
||||
| [`Temporal.PlainTime`] | [Local Time](https://toml.io/en/v1.1.0#local-time) | |
|
||||
| [`Temporal.PlainYearMonth`] | **Unsupported** (throws) | |
|
||||
| [`Temporal.ZonedDateTime`] | [Offset Date-Time](https://toml.io/en/v1.1.0#offset-date-time) | IANA timezone and calendar info lost, [see below](#iana-timezones-and-calendars). |
|
||||
|
||||
##### IANA timezones and calendars
|
||||
|
||||
`ZonedDateTime` objects may have 2 different types of timezone identifier attached to them: either an offset such as
|
||||
`+02:00`, or an [IANA Time Zone Identifier](https://www.iana.org/time-zones) such as `Europe/Paris`. The latter carries
|
||||
information about the currently observed offset in that region, daylight savings policies, and other timekeeping quirks
|
||||
such as leap seconds. It is a much more precise information than the offset alone. Additionally, `ZonedDateTime` allows
|
||||
keeping track of a specific calendar to use, such as for example the *Japanese imperial era*.
|
||||
|
||||
TOML can only represent offsets, not precise timezones nor a calendar[^tz-request]. As such, when serializing a
|
||||
`ZonedDateTime`, this information is **lost** and only the offset is preserved; effectively treating the `ZonedDateTime`
|
||||
as if it were an `Instant`. To prevent silent loss of timezone information, the `strictTemporal` option can be
|
||||
enabled to throw an error instead. Timezones that aren't simple offsets, or objects using a calendar that isn't
|
||||
the default ISO 8601 will be rejected.
|
||||
|
||||
[^tz-request]: There was a request to support the [RFC 9557] syntax, but it has been rejected. See [toml-lang/toml#1034].
|
||||
|
||||
#### TomlDate object
|
||||
> [!NOTE]
|
||||
> This object is not formally deprecated yet, but it is a legacy API. It will be deprecated in v2 and removed in v3.
|
||||
|
||||
The object directly inherits the JavaScript `Date` object, with a handful of extra APIs for distinguishing between
|
||||
different types of time components.
|
||||
|
||||
`TomlDate` preserves the offset, whereas the native `Date` object usually normalises everything to UTC.
|
||||
|
||||
> [!CAUTION]
|
||||
> Unlike the [Temporal API] which supports nanosecond precision, `Date` is limited to millisecond precision.
|
||||
|
||||
```js
|
||||
import { TomlDate } from 'smol-toml'
|
||||
|
||||
// Offset Date Time
|
||||
const date = new TomlDate('1979-05-27T07:32:00.000-08:00')
|
||||
console.log(date.isDateTime(), date.isDate(), date.isTime(), date.isLocal()) // ~> true, false, false, false
|
||||
console.log(date.toISOString()) // ~> 1979-05-27T07:32:00.000-08:00
|
||||
|
||||
// Local Date Time
|
||||
const date = new TomlDate('1979-05-27T07:32:00.000')
|
||||
console.log(date.isDateTime(), date.isDate(), date.isTime(), date.isLocal()) // ~> true, false, false, true
|
||||
console.log(date.toISOString()) // ~> 1979-05-27T07:32:00.000
|
||||
|
||||
// Local Date
|
||||
const date = new TomlDate('1979-05-27')
|
||||
console.log(date.isDateTime(), date.isDate(), date.isTime(), date.isLocal()) // ~> false, true, false, true
|
||||
console.log(date.toISOString()) // ~> 1979-05-27
|
||||
|
||||
// Local Time
|
||||
const date = new TomlDate('07:32:00')
|
||||
console.log(date.isDateTime(), date.isDate(), date.isTime(), date.isLocal()) // ~> false, false, true, true
|
||||
console.log(date.toISOString()) // ~> 07:32:00.000
|
||||
```
|
||||
|
||||
You can also wrap a native `Date` object and specify using different methods depending on the type of date you wish
|
||||
to represent:
|
||||
|
||||
```js
|
||||
import { TomlDate } from 'smol-toml'
|
||||
|
||||
const jsDate = new Date()
|
||||
|
||||
const offsetDateTime = TomlDate.wrapAsOffsetDateTime(jsDate)
|
||||
const localDateTime = TomlDate.wrapAsLocalDateTime(jsDate)
|
||||
const localDate = TomlDate.wrapAsLocalDate(jsDate)
|
||||
const localTime = TomlDate.wrapAsLocalTime(jsDate)
|
||||
```
|
||||
|
||||
## Performance
|
||||
The benchmark is ran using [mitata](https://github.com/evanwashere/mitata). See the sources in `bench`.
|
||||
|
||||
> [!NOTE]
|
||||
> - The output of `smol-toml` with Temporal *disabled* is used as the starting value for stringify benchmarks.
|
||||
> - The TOML generator used to create the 5MB test file can be found [here](https://gist.github.com/cyyynthia/e77c744cb6494dabe37d0182506526b9).
|
||||
|
||||
### Results
|
||||
- [Parse, spec example](#parse-spec-example)
|
||||
- [Parse, 5MB randomly generated file](#parse-5mb-randomly-generated)
|
||||
- [Stringify, spec example](#parse-spec-example)
|
||||
- [Stringify, 5MB randomly generated file](#parse-5mb-randomly-generated)
|
||||
|
||||
#### Parse, spec example
|
||||
|
||||
| | Library | Performance | Slowdown | Notes |
|
||||
|:--:|------------------------------------------|---------------|----------|-------|
|
||||
| 🥇 | smol-toml@1.9.0 (Date) | 2.98 µs/iter | 1x | |
|
||||
| 🥈 | smol-toml@1.9.0 (Temporal) | 3.14 µs/iter | 1.06x | |
|
||||
| 🥉 | fast-toml@0.5.4 | 5.13 µs/iter | 1.72x | Unmaintained. No handling of special floats. Bad handling of some unicode escapes. Parses `nan` as `false`. |
|
||||
| 4 | @iarna/toml@3.0.0 | 12.66 µs/iter | 4.25x | Unmaintained. Has defects in datetime parsing. Uses `eval`. |
|
||||
| 5 | @decimalturn/toml-patch@3.1.2 (Date) | 19.60 µs/iter | 6.58x | Special-purpose: designed for non-destructive document edition. |
|
||||
| 6 | @decimalturn/toml-patch@3.1.2 (Temporal) | 20.98 µs/iter | 7.04x | Special-purpose: designed for non-destructive document edition. |
|
||||
| 7 | @std/toml@1.0.11 | 22.81 µs/iter | 7.66x | |
|
||||
| 8 | js-toml@2.0.1 | 23.00 µs/iter | 7.72x | |
|
||||
| 9 | @ltd/j-toml@1.38.0 | 31.25 µs/iter | 10.49x | Unmaintained. Has defects in number parsing when disabling `bigint`. |
|
||||
| 10 | toml@5.0.0 (Temporal) | 33.04 µs/iter | 11.09x | |
|
||||
| 11 | toml@5.0.0 (Date/string) | 33.20 µs/iter | 11.15x | |
|
||||
|
||||
#### Parse, 5MB randomly generated file
|
||||
|
||||
| | Library | Performance | Slowdown | Notes |
|
||||
|:--:|------------------------------------------|----------------|----------|-------|
|
||||
| 🥇 | smol-toml@1.9.0 (Temporal) | 45.05 ms/iter | 1x | |
|
||||
| 🥈 | smol-toml@1.9.0 (Date) | 47.71 ms/iter | 1.06x | |
|
||||
| 🥉 | fast-toml@0.5.4 | 92.50 ms/iter | 2.05x | Unmaintained. No handling of special floats. Bad handling of some unicode escapes. Parses `nan` as `false`. |
|
||||
| 4 | @ltd/j-toml@1.38.0 | 186.47 ms/iter | 4.14x | Unmaintained. Has defects in number parsing when disabling `bigint`. |
|
||||
| 5 | @decimalturn/toml-patch@3.1.2 (Date) | 207.09 ms/iter | 4.6x | Special-purpose: designed for non-destructive document edition. |
|
||||
| 6 | @decimalturn/toml-patch@3.1.2 (Temporal) | 219.53 ms/iter | 4.87x | Special-purpose: designed for non-destructive document edition. |
|
||||
| 7 | js-toml@2.0.1 | 280.63 ms/iter | 6.23x | |
|
||||
| 8 | @std/toml@1.0.11 | 428.34 ms/iter | 9.51x | |
|
||||
| 9 | toml@5.0.0 (Date/string) | 557.91 ms/iter | 12.38x | |
|
||||
| 10 | toml@5.0.0 (Temporal) | 587.43 ms/iter | 13.04x | |
|
||||
| - | @iarna/toml@3.0.0 | **DNF** | **DNF** | Unmaintained. Has defects in datetime parsing. Uses `eval`. |
|
||||
|
||||
#### Stringify, spec example
|
||||
|
||||
| | Library | Performance | Slowdown | Notes |
|
||||
|:-:|-------------------------------|---------------|----------|-------|
|
||||
| 🥇 | smol-toml@1.9.0 | 2.68 µs/iter | 1x | |
|
||||
| 🥈 | @std/toml@1.0.11 | 4.86 µs/iter | 1.81x | |
|
||||
| 🥉 | js-toml@2.0.1 | 5.76 µs/iter | 2.15x | |
|
||||
| 4 | @iarna/toml@3.0.0 | 9.71 µs/iter | 3.62x | Unmaintained. |
|
||||
| 5 | @ltd/j-toml@1.38.0 | 48.15 µs/iter | 17.96x | Unmaintained. |
|
||||
| 6 | @decimalturn/toml-patch@3.1.2 | 59.57 µs/iter | 22.22x | Special-purpose: designed for non-destructive document edition. |
|
||||
|
||||
#### Stringify, 5MB randomly generated file
|
||||
|
||||
| | Library | Performance | Slowdown | Notes |
|
||||
|:-:|-------------------------------|----------------|----------|-------|
|
||||
| 🥇 | smol-toml@1.9.0 | 43.72 ms/iter | 1x | |
|
||||
| 🥈 | @std/toml@1.0.11 | 71.01 ms/iter | 1.62x | |
|
||||
| 🥉 | js-toml@2.0.1 | 107.22 ms/iter | 2.45x | |
|
||||
| 4 | @iarna/toml@3.0.0 | 134.59 ms/iter | 3.08x | Unmaintained. |
|
||||
| 5 | @ltd/j-toml@1.38.0 | 383.10 ms/iter | 8.76x | Unmaintained. |
|
||||
| 6 | @decimalturn/toml-patch@3.1.2 | 543.69 ms/iter | 12.44x | Special-purpose: designed for non-destructive document edition. |
|
||||
|
||||
### Detailed benchmark data
|
||||
|
||||
<details>
|
||||
<summary>Detailed benchmark data</summary>
|
||||
|
||||
```
|
||||
node --expose-gc bench/parse.bench.ts
|
||||
clk: ~5.39 GHz
|
||||
cpu: AMD Ryzen 9 9950X3D 16-Core Processor
|
||||
runtime: node 26.10.0 (x64-linux)
|
||||
|
||||
benchmark avg (min … max) p75 / p99 (min … top 1%)
|
||||
------------------------------------------------- -------------------------------
|
||||
• spec document
|
||||
------------------------------------------------- -------------------------------
|
||||
smol-toml (Date) 2.98 µs/iter 2.93 µs █
|
||||
(2.81 µs … 98.78 µs) 4.21 µs █▂
|
||||
(440.00 b … 236.20 kb) 12.70 kb ▁██▃▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
4.46 ipc ( 99.06% cache) 16.97 branch misses
|
||||
16.79k cycles 74.80k instructions 2.21k c-refs 20.71 c-misses
|
||||
|
||||
smol-toml (Temporal) 3.14 µs/iter 3.16 µs █
|
||||
(3.10 µs … 3.20 µs) 3.20 µs ▇▇ ▂ ▅█▅▂▂
|
||||
( 4.60 kb … 4.62 kb) 4.61 kb ██▇█▇▁▁▄▄▇▄█████▄▄▇▄▄
|
||||
4.47 ipc ( 99.22% cache) 12.39 branch misses
|
||||
17.24k cycles 77.01k instructions 2.32k c-refs 18.12 c-misses
|
||||
|
||||
@iarna/toml 12.66 µs/iter 12.51 µs █
|
||||
(12.09 µs … 104.09 µs) 16.70 µs █
|
||||
(192.00 b … 454.46 kb) 24.09 kb ▄██▃▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.87 ipc ( 99.63% cache) 84.59 branch misses
|
||||
70.08k cycles 271.21k instructions 11.96k c-refs 44.06 c-misses
|
||||
|
||||
@ltd/j-toml 31.25 µs/iter 30.76 µs ▄██▂
|
||||
(29.69 µs … 851.32 µs) 34.20 µs ████
|
||||
(760.00 b … 537.88 kb) 27.54 kb ▁▅████▇▃▂▁▁▂▁▂▁▁▁▁▁▁▁
|
||||
3.35 ipc ( 99.48% cache) 293.85 branch misses
|
||||
172.79k cycles 578.79k instructions 31.46k c-refs 165.17 c-misses
|
||||
|
||||
fast-toml 5.13 µs/iter 5.10 µs █
|
||||
(4.96 µs … 89.84 µs) 6.09 µs ▃█
|
||||
(400.00 b … 376.82 kb) 12.63 kb ▁██▅▃▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
4.49 ipc ( 99.53% cache) 13.42 branch misses
|
||||
28.68k cycles 128.90k instructions 3.91k c-refs 18.52 c-misses
|
||||
|
||||
@std/toml 22.81 µs/iter 22.71 µs █
|
||||
(21.45 µs … 148.45 µs) 29.40 µs █
|
||||
(120.00 b … 498.46 kb) 64.90 kb ▁▄▇█▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.75 ipc ( 99.54% cache) 105.52 branch misses
|
||||
125.75k cycles 471.96k instructions 24.08k c-refs 110.15 c-misses
|
||||
|
||||
toml (Date/string) 33.20 µs/iter 31.60 µs █
|
||||
(30.38 µs … 3.01 ms) 51.14 µs █
|
||||
(952.00 b … 1.56 mb) 108.82 kb ▆█▃▃▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.96 ipc ( 99.06% cache) 181.78 branch misses
|
||||
177.03k cycles 700.26k instructions 30.31k c-refs 286.20 c-misses
|
||||
|
||||
toml (Temporal) 33.04 µs/iter 31.76 µs █
|
||||
(31.47 µs … 47.08 µs) 33.37 µs █▂ ▂
|
||||
( 6.40 kb … 8.14 kb) 6.98 kb ██▁█▁▆▁▁▁▁▁▁▁▁▁▁▁▁▁▁▆
|
||||
3.94 ipc ( 99.13% cache) 176.95 branch misses
|
||||
177.43k cycles 699.67k instructions 31.56k c-refs 274.71 c-misses
|
||||
|
||||
js-toml 23.00 µs/iter 21.48 µs █
|
||||
(20.32 µs … 2.18 ms) 32.27 µs █▆
|
||||
( 0.99 kb … 1.45 mb) 92.46 kb ▂██▃▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
4.10 ipc ( 98.16% cache) 178.29 branch misses
|
||||
122.97k cycles 504.24k instructions 20.34k c-refs 374.28 c-misses
|
||||
|
||||
@decimalturn/toml-patch (Date) 19.60 µs/iter 19.09 µs █
|
||||
(18.53 µs … 841.76 µs) 26.77 µs █
|
||||
(608.00 b … 607.52 kb) 60.02 kb ▃█▄▂▂▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.54 ipc ( 99.33% cache) 104.70 branch misses
|
||||
107.96k cycles 382.10k instructions 23.95k c-refs 160.21 c-misses
|
||||
|
||||
@decimalturn/toml-patch (Temporal) 20.98 µs/iter 20.24 µs ██ █
|
||||
(20.12 µs … 29.49 µs) 20.51 µs ██▅█▅ ▅ ▅ ▅
|
||||
( 2.55 kb … 4.41 kb) 2.86 kb █████▁█▁▁█▁▁▁▁▁▁▁▁▁▁█
|
||||
3.52 ipc ( 99.29% cache) 106.72 branch misses
|
||||
114.13k cycles 401.87k instructions 25.31k c-refs 179.37 c-misses
|
||||
|
||||
summary
|
||||
smol-toml (Date)
|
||||
1.06x faster than smol-toml (Temporal)
|
||||
1.72x faster than fast-toml
|
||||
4.25x faster than @iarna/toml
|
||||
6.58x faster than @decimalturn/toml-patch (Date)
|
||||
7.04x faster than @decimalturn/toml-patch (Temporal)
|
||||
7.66x faster than @std/toml
|
||||
7.72x faster than js-toml
|
||||
10.49x faster than @ltd/j-toml
|
||||
11.09x faster than toml (Temporal)
|
||||
11.15x faster than toml (Date/string)
|
||||
|
||||
• 5MB document
|
||||
------------------------------------------------- -------------------------------
|
||||
smol-toml (Date) 47.71 ms/iter 50.08 ms █
|
||||
(44.72 ms … 50.16 ms) 50.09 ms █
|
||||
( 27.91 mb … 37.81 mb) 33.32 mb █▁█▁████▁▁▁▁▁▁▁▁▁▁▁██
|
||||
3.05 ipc ( 96.95% cache) 1.95M branch misses
|
||||
249.63M cycles 760.48M instructions 23.70M c-refs 723.86k c-misses
|
||||
|
||||
smol-toml (Temporal) 45.05 ms/iter 46.17 ms █
|
||||
(43.04 ms … 47.19 ms) 47.06 ms ▅█ ▅▅ ▅ ▅ ▅▅▅ ▅
|
||||
( 25.17 mb … 36.61 mb) 31.28 mb ██▁██▁▁▁▁█▁▁▁█▁███▁▁█
|
||||
3.09 ipc ( 97.25% cache) 1.52M branch misses
|
||||
244.27M cycles 754.78M instructions 29.60M c-refs 813.69k c-misses
|
||||
|
||||
@iarna/toml error: Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z at row 5, col 45, pos 569:
|
||||
4: NfF6LuAerfn5mDPI7Cp 2qsrB4vGmJTyb5jNubOIBYYWrWlAsrw PX93S57gjb5GEhR8qOU5blDQmwfVJTA YvmJ9cE3cUZU NAJQgAbIdpZLhc4lOs4ZhMEWehhZqXCsVD1YP1vN2GEoM2WX''', 1986-05-27T18:36:13Z, -5460, "2ZAV3fYlb23hf7r7QoftVlicWE2iuwp", 4790.2253 ]
|
||||
5> SzeC4Me8T = [ 5928.9340, 1991-04-28 19:24:24, 7807, -782.4516, 0b1000011111, "YvXRZKBGle9d51sqE90t8hP" ]
|
||||
^
|
||||
6: SLMvBirT.pmpX1D.9PivpfFBo = 2010-09-29
|
||||
|
||||
@ltd/j-toml 186.47 ms/iter 184.10 ms ██ █
|
||||
(166.25 ms … 284.21 ms) 192.51 ms ▅ ██ █ ▅ ▅ ▅ ▅
|
||||
( 20.29 mb … 55.50 mb) 33.21 mb █▁▁▁██▁█▁▁▁▁█▁█▁▁█▁▁█
|
||||
2.38 ipc ( 97.97% cache) 3.93M branch misses
|
||||
1.04G cycles 2.47G instructions 164.91M c-refs 3.35M c-misses
|
||||
|
||||
fast-toml 92.50 ms/iter 92.90 ms █ █ █
|
||||
(88.55 ms … 101.67 ms) 97.51 ms ▅█ █ █▅ ▅ ▅ ▅
|
||||
( 13.48 mb … 34.99 mb) 24.13 mb ██▁▁▁█▁██▁█▁▁█▁▁▁▁▁▁█
|
||||
2.82 ipc ( 98.12% cache) 2.40M branch misses
|
||||
516.21M cycles 1.45G instructions 67.12M c-refs 1.26M c-misses
|
||||
|
||||
@std/toml 428.34 ms/iter 434.32 ms █
|
||||
(410.50 ms … 446.83 ms) 442.42 ms ▅ ▅█ ▅▅ ▅▅▅ ▅ ▅
|
||||
(181.70 mb … 204.21 mb) 194.10 mb █▁▁▁██▁▁▁██▁▁███▁█▁▁█
|
||||
3.08 ipc ( 96.60% cache) 6.52M branch misses
|
||||
2.41G cycles 7.42G instructions 243.62M c-refs 8.29M c-misses
|
||||
|
||||
toml (Date/string) 557.91 ms/iter 562.12 ms █
|
||||
(535.21 ms … 581.06 ms) 577.25 ms █
|
||||
( 34.09 mb … 84.96 mb) 64.32 mb █▁█▁▁█▁▁███▁▁█▁▁█▁▁▁█
|
||||
4.17 ipc ( 96.50% cache) 6.35M branch misses
|
||||
3.07G cycles 12.80G instructions 237.61M c-refs 8.32M c-misses
|
||||
|
||||
toml (Temporal) 587.43 ms/iter 597.17 ms █
|
||||
(570.22 ms … 607.53 ms) 606.15 ms █ █ █
|
||||
( 2.54 mb … 92.29 mb) 56.92 mb █▁▁█▁▁▁█▁▁▁▁▁███▁▁▁▁█
|
||||
4.08 ipc ( 96.20% cache) 6.59M branch misses
|
||||
3.20G cycles 13.03G instructions 261.00M c-refs 9.91M c-misses
|
||||
|
||||
js-toml 280.63 ms/iter 305.16 ms █
|
||||
(248.43 ms … 358.30 ms) 322.18 ms █
|
||||
(268.55 mb … 282.47 mb) 272.11 mb ████▁█▁▁▁▁█▁▁▁▁█▁█▁▁█
|
||||
2.17 ipc ( 94.73% cache) 5.06M branch misses
|
||||
1.49G cycles 3.23G instructions 127.90M c-refs 6.74M c-misses
|
||||
|
||||
@decimalturn/toml-patch (Date) 207.09 ms/iter 212.85 ms █
|
||||
(195.68 ms … 235.57 ms) 219.92 ms ██
|
||||
( 5.63 mb … 47.95 mb) 28.68 mb ███▁▁▁▁▁▁▁▁██▁██▁▁▁▁█
|
||||
2.94 ipc ( 97.40% cache) 4.09M branch misses
|
||||
1.13G cycles 3.33G instructions 144.65M c-refs 3.77M c-misses
|
||||
|
||||
@decimalturn/toml-patch (Temporal) 219.53 ms/iter 217.17 ms ██
|
||||
(214.02 ms … 236.49 ms) 233.70 ms ███
|
||||
( 11.24 mb … 56.44 mb) 25.17 mb ████▁▁▁▁▁▁▁▁▁▁█▁▁▁▁▁█
|
||||
2.89 ipc ( 97.08% cache) 4.38M branch misses
|
||||
1.21G cycles 3.50G instructions 166.38M c-refs 4.86M c-misses
|
||||
|
||||
summary
|
||||
smol-toml (Temporal)
|
||||
1.06x faster than smol-toml (Date)
|
||||
2.05x faster than fast-toml
|
||||
4.14x faster than @ltd/j-toml
|
||||
4.6x faster than @decimalturn/toml-patch (Date)
|
||||
4.87x faster than @decimalturn/toml-patch (Temporal)
|
||||
6.23x faster than js-toml
|
||||
9.51x faster than @std/toml
|
||||
12.38x faster than toml (Date/string)
|
||||
13.04x faster than toml (Temporal)
|
||||
|
||||
node --expose-gc bench/stringify.bench.ts
|
||||
clk: ~5.38 GHz
|
||||
cpu: AMD Ryzen 9 9950X3D 16-Core Processor
|
||||
runtime: node 26.10.0 (x64-linux)
|
||||
|
||||
benchmark avg (min … max) p75 / p99 (min … top 1%)
|
||||
------------------------------------------- -------------------------------
|
||||
• spec document
|
||||
------------------------------------------- -------------------------------
|
||||
smol-toml 2.68 µs/iter 2.68 µs █
|
||||
(2.61 µs … 2.91 µs) 2.89 µs ▅█▇▂
|
||||
( 4.29 kb … 4.39 kb) 4.30 kb ▇████▅▄▄▁▁▁▁▂▂▁▁▁█▂▁▂
|
||||
4.41 ipc ( 99.57% cache) 6.85 branch misses
|
||||
14.77k cycles 65.13k instructions 1.43k c-refs 6.19 c-misses
|
||||
|
||||
@iarna/toml 9.71 µs/iter 9.66 µs █
|
||||
(9.31 µs … 132.37 µs) 11.48 µs ▄█▆
|
||||
(232.00 b … 681.09 kb) 26.28 kb ▁███▆▃▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.85 ipc ( 99.49% cache) 33.76 branch misses
|
||||
55.12k cycles 212.42k instructions 8.62k c-refs 43.87 c-misses
|
||||
|
||||
@ltd/j-toml 48.15 µs/iter 47.84 µs █▇
|
||||
(38.21 µs … 312.67 µs) 66.76 µs ██
|
||||
( 2.72 kb … 382.48 kb) 35.59 kb ▁▁▁▂▂▁██▄▂▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.86 ipc ( 99.59% cache) 322.22 branch misses
|
||||
270.56k cycles 1.04M instructions 27.49k c-refs 113.85 c-misses
|
||||
|
||||
@std/toml 4.86 µs/iter 4.60 µs █
|
||||
(4.25 µs … 178.46 µs) 8.94 µs █
|
||||
(440.00 b … 521.36 kb) 18.02 kb ▄█▅▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.46 ipc ( 99.31% cache) 21.73 branch misses
|
||||
26.86k cycles 92.81k instructions 4.73k c-refs 32.73 c-misses
|
||||
|
||||
js-toml 5.76 µs/iter 5.77 µs ▃█
|
||||
(5.69 µs … 5.83 µs) 5.81 µs ▂ ▇▂██
|
||||
( 1.94 kb … 7.02 kb) 2.16 kb ▆▁▁▁▁▆▁▆█▆████▆▆▁▆▁▆▆
|
||||
4.34 ipc ( 99.16% cache) 34.91 branch misses
|
||||
32.34k cycles 140.35k instructions 3.29k c-refs 27.55 c-misses
|
||||
|
||||
@decimalturn/toml-patch 59.57 µs/iter 57.71 µs █
|
||||
(53.70 µs … 630.39 µs) 110.05 µs █
|
||||
( 4.04 kb … 1.10 mb) 108.22 kb ▅█▆▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
3.94 ipc ( 98.84% cache) 787.33 branch misses
|
||||
333.69k cycles 1.32M instructions 48.19k c-refs 561.33 c-misses
|
||||
|
||||
summary
|
||||
smol-toml
|
||||
1.81x faster than @std/toml
|
||||
2.15x faster than js-toml
|
||||
3.62x faster than @iarna/toml
|
||||
17.96x faster than @ltd/j-toml
|
||||
22.22x faster than @decimalturn/toml-patch
|
||||
|
||||
• 5MB document
|
||||
------------------------------------------- -------------------------------
|
||||
smol-toml 43.72 ms/iter 47.53 ms █ █
|
||||
(40.14 ms … 48.06 ms) 47.98 ms █ █ █
|
||||
( 9.39 mb … 35.40 mb) 12.82 mb ███▁▁▁▁▁█▁▁▁▁▁▁▁▁▁▁██
|
||||
2.28 ipc ( 95.29% cache) 1.68M branch misses
|
||||
225.53M cycles 513.97M instructions 15.50M c-refs 730.62k c-misses
|
||||
|
||||
@iarna/toml 134.59 ms/iter 138.20 ms █
|
||||
(126.83 ms … 143.64 ms) 138.71 ms █ █
|
||||
( 28.96 mb … 54.84 mb) 42.86 mb █▁▁▁█▁▁█▁▁█▁▁▁██▁▁▁██
|
||||
2.65 ipc ( 97.36% cache) 4.43M branch misses
|
||||
710.95M cycles 1.88G instructions 84.80M c-refs 2.24M c-misses
|
||||
|
||||
@ltd/j-toml 383.10 ms/iter 388.05 ms █
|
||||
(366.11 ms … 390.91 ms) 389.63 ms █ █ █
|
||||
( 21.44 mb … 22.42 mb) 21.75 mb █▁▁▁▁▁▁▁▁█▁▁██▁▁█▁▁██
|
||||
3.81 ipc ( 99.05% cache) 4.10M branch misses
|
||||
2.08G cycles 7.93G instructions 182.50M c-refs 1.74M c-misses
|
||||
|
||||
@std/toml 71.01 ms/iter 72.24 ms █
|
||||
(62.44 ms … 81.12 ms) 79.64 ms █
|
||||
( 29.44 mb … 62.92 mb) 37.36 mb █▁██▁▁▁██▁██▁▁▁█▁▁▁▁█
|
||||
2.19 ipc ( 95.42% cache) 1.85M branch misses
|
||||
347.81M cycles 761.47M instructions 31.77M c-refs 1.46M c-misses
|
||||
|
||||
js-toml 107.22 ms/iter 110.20 ms █
|
||||
(99.03 ms … 114.64 ms) 112.12 ms █ █ █
|
||||
( 18.56 mb … 48.98 mb) 42.88 mb █▁▁▁▁▁▁▁▁█▁▁▁▁█▁██▁██
|
||||
2.50 ipc ( 96.46% cache) 3.18M branch misses
|
||||
573.52M cycles 1.43G instructions 50.22M c-refs 1.78M c-misses
|
||||
|
||||
@decimalturn/toml-patch 543.69 ms/iter 570.96 ms █
|
||||
(515.23 ms … 583.43 ms) 578.06 ms █
|
||||
(112.55 mb … 144.20 mb) 122.09 mb █▁██▁██▁█▁▁▁▁▁▁▁▁▁███
|
||||
3.30 ipc ( 94.93% cache) 7.55M branch misses
|
||||
2.91G cycles 9.59G instructions 234.01M c-refs 11.85M c-misses
|
||||
|
||||
summary
|
||||
smol-toml
|
||||
1.62x faster than @std/toml
|
||||
2.45x faster than js-toml
|
||||
3.08x faster than @iarna/toml
|
||||
8.76x faster than @ltd/j-toml
|
||||
12.44x faster than @decimalturn/toml-patch
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
[Temporal API]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal
|
||||
[`Temporal.Duration`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration
|
||||
[`Temporal.Instant`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Instant
|
||||
[`Temporal.PlainDate`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate
|
||||
[`Temporal.PlainDateTime`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime
|
||||
[`Temporal.PlainMonthDay`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainMonthDay
|
||||
[`Temporal.PlainTime`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime
|
||||
[`Temporal.PlainYearMonth`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth
|
||||
[`Temporal.ZonedDateTime`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime
|
||||
|
||||
[toml-lang/toml#514]: https://github.com/toml-lang/toml/issues/514
|
||||
[toml-lang/toml#1034]: https://github.com/toml-lang/toml/issues/1034
|
||||
[toml-lang/toml#1105]: https://github.com/toml-lang/toml/issues/1105
|
||||
|
||||
[RFC 9557]: https://www.rfc-editor.org/info/rfc9557
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
export declare class TomlDate extends Date {
|
||||
#private;
|
||||
constructor(date: string | Date);
|
||||
isDateTime(): boolean;
|
||||
isLocal(): boolean;
|
||||
isDate(): boolean;
|
||||
isTime(): boolean;
|
||||
isValid(): boolean;
|
||||
toISOString(): string;
|
||||
static wrapAsOffsetDateTime(jsDate: Date, offset?: string): TomlDate;
|
||||
static wrapAsLocalDateTime(jsDate: Date): TomlDate;
|
||||
static wrapAsLocalDate(jsDate: Date): TomlDate;
|
||||
static wrapAsLocalTime(jsDate: Date): TomlDate;
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
|
||||
export class TomlDate extends Date {
|
||||
#hasDate = false;
|
||||
#hasTime = false;
|
||||
#offset = null;
|
||||
constructor(date, fasttype, unsafeDelim) {
|
||||
let hasDate = true;
|
||||
let hasTime = true;
|
||||
let offset = 'Z';
|
||||
let c;
|
||||
if (typeof date === 'string') {
|
||||
if (fasttype)
|
||||
prep: {
|
||||
// Date-time
|
||||
if (fasttype < 3) {
|
||||
if (+date.slice(11, 13) > 23) {
|
||||
date = '';
|
||||
break prep;
|
||||
}
|
||||
// Local
|
||||
if (fasttype === 2) {
|
||||
offset = null;
|
||||
date += 'Z';
|
||||
}
|
||||
// Offset; keep track of offset if not Z
|
||||
else if ((c = date.charCodeAt(date.length - 1)) !== 0x5a /* Z */ && c !== 0x7a /* z */) {
|
||||
offset = date.slice(date.length - 6);
|
||||
}
|
||||
if (unsafeDelim)
|
||||
date = date.slice(0, 10) + 'T' + date.slice(11);
|
||||
}
|
||||
// Time
|
||||
else if (fasttype === 4) {
|
||||
date = +date.slice(0, 2) > 23 ? '' : `0000-01-01T${date}Z`;
|
||||
}
|
||||
hasDate = fasttype !== 4;
|
||||
hasTime = fasttype !== 3;
|
||||
}
|
||||
else {
|
||||
let match = date.match(DATE_TIME_RE);
|
||||
if (match) {
|
||||
if (!match[1]) {
|
||||
hasDate = false;
|
||||
date = `0000-01-01T${date}`;
|
||||
}
|
||||
hasTime = !!match[2];
|
||||
// Make sure to use T instead of a space. Breaks in case of extreme values otherwise.
|
||||
hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));
|
||||
// Do not allow rollover hours.
|
||||
if (match[2] && +match[2] > 23) {
|
||||
date = '';
|
||||
}
|
||||
else {
|
||||
offset = match[3] || null;
|
||||
if (!offset && hasTime)
|
||||
date += 'Z';
|
||||
}
|
||||
}
|
||||
else {
|
||||
date = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
super(date);
|
||||
if (!isNaN(this.getTime())) {
|
||||
this.#hasDate = hasDate;
|
||||
this.#hasTime = hasTime;
|
||||
this.#offset = offset;
|
||||
}
|
||||
}
|
||||
isDateTime() {
|
||||
return this.#hasDate && this.#hasTime;
|
||||
}
|
||||
isLocal() {
|
||||
return !this.#hasDate || !this.#hasTime || !this.#offset;
|
||||
}
|
||||
isDate() {
|
||||
return this.#hasDate && !this.#hasTime;
|
||||
}
|
||||
isTime() {
|
||||
return this.#hasTime && !this.#hasDate;
|
||||
}
|
||||
isValid() {
|
||||
return this.#hasDate || this.#hasTime;
|
||||
}
|
||||
toISOString() {
|
||||
let iso = super.toISOString();
|
||||
// Local Date
|
||||
if (this.isDate())
|
||||
return iso.slice(0, 10);
|
||||
// Local Time
|
||||
if (this.isTime())
|
||||
return iso.slice(11, 23);
|
||||
// Local DateTime
|
||||
if (this.#offset === null)
|
||||
return iso.slice(0, -1);
|
||||
// Offset DateTime
|
||||
if (this.#offset === 'Z' || this.#offset === 'z')
|
||||
return iso;
|
||||
// This part is quite annoying: JS strips the original timezone from the ISO string representation
|
||||
// Instead of using a "modified" date and "Z", we restore the representation "as authored"
|
||||
let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));
|
||||
offset = this.#offset[0] === '-' ? offset : -offset;
|
||||
let offsetDate = new Date(this.getTime() - (offset * 60e3));
|
||||
return offsetDate.toISOString().slice(0, -1) + this.#offset;
|
||||
}
|
||||
static wrapAsOffsetDateTime(jsDate, offset = 'Z') {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#offset = offset;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalDateTime(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalDate(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#hasTime = false;
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalTime(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#hasDate = false;
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
export type TomlErrorOptions = ErrorOptions & {
|
||||
toml: string;
|
||||
ptr: number;
|
||||
};
|
||||
export declare class TomlError extends Error {
|
||||
line: number;
|
||||
column: number;
|
||||
codeblock: string;
|
||||
constructor(message: string, options: TomlErrorOptions);
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
function getLineColFromPtr(string, ptr) {
|
||||
let lines = string.slice(0, ptr).split(/\r?\n/);
|
||||
return [lines.length, lines.pop().length + 1];
|
||||
}
|
||||
function makeCodeBlock(string, line, column) {
|
||||
let lines = string.split(/\r?\n/);
|
||||
let codeblock = '';
|
||||
let numberLen = (Math.log10(line + 1) | 0) + 1;
|
||||
for (let i = line - 1; i <= line + 1; i++) {
|
||||
let l = lines[i - 1];
|
||||
if (!l)
|
||||
continue;
|
||||
codeblock += i.toString().padEnd(numberLen, ' ');
|
||||
codeblock += ': ';
|
||||
codeblock += l;
|
||||
codeblock += '\n';
|
||||
if (i === line) {
|
||||
codeblock += ' '.repeat(numberLen + column + 2);
|
||||
codeblock += '^\n';
|
||||
}
|
||||
}
|
||||
return codeblock;
|
||||
}
|
||||
export class TomlError extends Error {
|
||||
line;
|
||||
column;
|
||||
codeblock;
|
||||
constructor(message, options) {
|
||||
const [line, column] = getLineColFromPtr(options.toml, options.ptr);
|
||||
const codeblock = makeCodeBlock(options.toml, line, column);
|
||||
super(`Invalid TOML document: ${message}\n\n${codeblock}`, options);
|
||||
this.line = line;
|
||||
this.column = column;
|
||||
this.codeblock = codeblock;
|
||||
}
|
||||
/** @internal */
|
||||
static x(message, ctx, ptr) {
|
||||
throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
|
||||
}
|
||||
}
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { parseString } from './primitive.js';
|
||||
import { parseArray, parseInlineTable } from './struct.js';
|
||||
import { TomlError } from './error.js';
|
||||
import { TomlDate } from './date.js';
|
||||
function isDigit(char, base = 10) {
|
||||
return base === 16
|
||||
? (char > 0x2f && char < 0x3a) || (char > 0x40 && char < 0x47) || (char > 0x60 && char < 0x67)
|
||||
: (char > 0x2f && char < 0x30 + base);
|
||||
}
|
||||
function isEndOfValue(char, delim) {
|
||||
// Whitespace -- we're permissive on `\r` for performance; it'll be dealt with later anyway
|
||||
return char === 0x20 || char === 0x9 /* \t */ || char === 0xa /* \n */ || char === 0xd /* \r */ ||
|
||||
// Structure end or next value delimiter
|
||||
(delim && (char === delim || char === 0x2c /* , */)) ||
|
||||
// Comment
|
||||
char === 0x23; /* # */
|
||||
}
|
||||
/** @internal */
|
||||
export function extractValue(ctx, end) {
|
||||
let errPtr = ctx.p;
|
||||
let c = ctx.s.charCodeAt(ctx.p);
|
||||
// Structs
|
||||
if (c === 0x5b /* [ */ || c === 0x7b /* { */) {
|
||||
ctx.d-- || TomlError.x('document contains excessively nested structures. aborting.', ctx);
|
||||
let value = c === 0x5b /* [ */
|
||||
? parseArray(ctx)
|
||||
: parseInlineTable(ctx);
|
||||
ctx.d++;
|
||||
return value;
|
||||
}
|
||||
// Strings
|
||||
if (c === 0x22 /* " */ || c === 0x27 /* ' */) {
|
||||
return parseString(ctx);
|
||||
}
|
||||
// Booleans
|
||||
// We can fast-path because the first character is enough to know the only possible value
|
||||
if (c === 0x74 /* t */) { // Only possible valid value is `true`
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 0x72 || ctx.s.charCodeAt(++ctx.p) !== 0x75 || ctx.s.charCodeAt(++ctx.p) !== 0x65)
|
||||
TomlError.x('invalid value', ctx, errPtr);
|
||||
return ctx.p++, true;
|
||||
}
|
||||
if (c === 0x66 /* f */) { // Only possible valid value is `false`
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6c || ctx.s.charCodeAt(++ctx.p) !== 0x73 || ctx.s.charCodeAt(++ctx.p) !== 0x65)
|
||||
TomlError.x('invalid value', ctx, errPtr);
|
||||
return ctx.p++, false;
|
||||
}
|
||||
if (c === 0x2b /* + */ || c === 0x2d /* - */) {
|
||||
return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 0x2c - c, end);
|
||||
}
|
||||
// Rough heuristic, but `parseDate` falls back to number parsing if it's a false positive.
|
||||
// e.g.: `a = 1\n-------------- = 1` would match this heuristic, but gracefully fallback to numbers.
|
||||
if (ctx.s.charCodeAt(ctx.p + 4) === 0x2d /* - */ && ctx.s.charCodeAt(ctx.p + 7) === 0x2d /* - */) {
|
||||
return parseDate(ctx, c, end);
|
||||
}
|
||||
// Same logic as above; `parseTime` falls back to number parsing if it's a false positive.
|
||||
if (ctx.s.charCodeAt(ctx.p + 2) === 0x3a /* : */) {
|
||||
return parseTime(ctx, c, end);
|
||||
}
|
||||
return parseNumber(ctx, ctx.p, c, 0, end);
|
||||
}
|
||||
// State:
|
||||
// 0: init
|
||||
// 1: integer
|
||||
// 2: fractional dot
|
||||
// 3: fractional
|
||||
// 4: exponent letter
|
||||
// 5: exponent
|
||||
// 6: exponent sign
|
||||
// 7: exponent with sign
|
||||
// >9: underscore; see below
|
||||
// -> 12: was integer
|
||||
// -> 14: was fractional
|
||||
// -> 16: was exponent
|
||||
// states 2-5, 14, 16 are ONLY permitted iif base === 10
|
||||
function parseNumber(ctx, startPtr, startChr, sign, endChr) {
|
||||
let c = startChr;
|
||||
let state = 0;
|
||||
let hasUnderscores = false;
|
||||
// (+/-)inf
|
||||
if (c === 0x69 /* i */) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 0x6e || ctx.s.charCodeAt(++ctx.p) !== 0x66)
|
||||
TomlError.x('invalid value', ctx, startPtr);
|
||||
return ctx.p++, (sign || 1) / 0;
|
||||
}
|
||||
// (+/-)nan
|
||||
if (c === 0x6e /* n */) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6e)
|
||||
TomlError.x('invalid value', ctx, startPtr);
|
||||
return ctx.p++, NaN;
|
||||
}
|
||||
// Leading zero
|
||||
// Only allowed cases: `0<EOV>`, `0.(...)`, `0e(...)`, `0x(...)`, `0b(...)`, `0o(...)`
|
||||
// FWIW, `0e(...)` is a stupid case, but it's not banned per-se so we have to parse it
|
||||
if (c === 0x30 /* 0 */) {
|
||||
if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
|
||||
return ctx.bi === true ? 0n : 0; // note: conveniently deals with `-0`
|
||||
if (!sign) {
|
||||
if (c === 0x78 /* x */)
|
||||
return parseIntegerBaseN(ctx, startPtr, 16, endChr);
|
||||
else if (c === 0x62 /* b */)
|
||||
return parseIntegerBaseN(ctx, startPtr, 2, endChr);
|
||||
else if (c === 0x6f /* o */)
|
||||
return parseIntegerBaseN(ctx, startPtr, 8, endChr);
|
||||
}
|
||||
if (c === 0x2e /* . */)
|
||||
state = 2;
|
||||
else if (c === 0x65 /* e */ || c === 0x45 /* E */)
|
||||
state = 4;
|
||||
else
|
||||
TomlError.x('illegal leading zero', ctx, startPtr);
|
||||
}
|
||||
// If the 1st char is not a digit by now, then it's not a valid TOML value at all
|
||||
else if (!isDigit(c))
|
||||
TomlError.x('invalid value', ctx, startPtr);
|
||||
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
|
||||
if (!state)
|
||||
state = 1; // Detects single-digit numbers we can use a fast parse path for
|
||||
// The way the states are numbered is not random: underscores are always permitted in odd-numbered states and
|
||||
// never permitted in even-numbered ones.
|
||||
if (c === 0x5f /* _ */) {
|
||||
if (!(state & 1))
|
||||
TomlError.x('illegal underscore', ctx);
|
||||
state += 11; // 11 is a marker that makes the state even and greater than 9; see the numbering + rationale above
|
||||
hasUnderscores = true;
|
||||
}
|
||||
// Transition to fractional part.
|
||||
else if (state === 1 && c === 0x2e /* . */)
|
||||
state = 2;
|
||||
// Transition to exponent part.
|
||||
else if ((state === 1 || state === 3) && (c === 0x65 /* e */ || c === 0x45 /* E */))
|
||||
state = 4;
|
||||
// + and - are permitted in state 4 only (handled before entering the function for state 0)
|
||||
else if (state === 4 && (c === 0x2b /* + */ || c === 0x2d /* - */)) {
|
||||
state = 6;
|
||||
}
|
||||
// All special cases have been handled; only digits are allowed here
|
||||
else if (!isDigit(c))
|
||||
TomlError.x(`illegal character in numeric literal`, ctx);
|
||||
// Clear state flags
|
||||
else if (state > 9)
|
||||
state -= 11;
|
||||
else if (!(state & 1))
|
||||
state++;
|
||||
}
|
||||
// Single-char number; we can fast-path these very easily.
|
||||
if (!state) {
|
||||
let val = (startChr - 0x30 /* 0 */) * (sign || 1);
|
||||
return ctx.bi === true ? BigInt(val) : val;
|
||||
}
|
||||
// Even-numbered states absolutely require a digit next; not even end of value is permitted
|
||||
if (!(state & 1))
|
||||
TomlError.x('unfinished numeric value', ctx, startPtr);
|
||||
let str = ctx.s.slice(startPtr, ctx.p);
|
||||
if (hasUnderscores)
|
||||
str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex
|
||||
return state > 1
|
||||
? parseFloat(str)
|
||||
: parseInteger(ctx, str, 10, startPtr);
|
||||
}
|
||||
function parseIntegerBaseN(ctx, startPtr, base, endChr) {
|
||||
let c, underscore = 1;
|
||||
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
|
||||
if (c === 0x5f /* _ */) {
|
||||
if (underscore & 1)
|
||||
TomlError.x('illegal underscore', ctx);
|
||||
underscore = 3;
|
||||
}
|
||||
// We only need to check if the number is a valid digit, nothing else is permitted
|
||||
else if (!isDigit(c, base))
|
||||
TomlError.x(`illegal character in numeric literal`, ctx);
|
||||
// Clear underscore flag
|
||||
else if (underscore & 1)
|
||||
underscore--;
|
||||
}
|
||||
// Trailing underscore is not allowed
|
||||
if (underscore & 1)
|
||||
TomlError.x('unfinished numeric value', ctx);
|
||||
let str = ctx.s.slice(startPtr + 2, ctx.p);
|
||||
if (underscore)
|
||||
str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex
|
||||
return parseInteger(ctx, str, base, startPtr);
|
||||
}
|
||||
function parseInteger(ctx, str, base, startPtr) {
|
||||
if (ctx.bi !== true)
|
||||
int: {
|
||||
let val = parseInt(str, base);
|
||||
if (!Number.isSafeInteger(val)) {
|
||||
if (ctx.bi)
|
||||
break int;
|
||||
TomlError.x('integer value cannot be represented losslessly', ctx, startPtr);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
return base === 10 ? BigInt(str) : BigInt((base === 2 ? '0b' : base === 8 ? '0o' : '0x') + str);
|
||||
}
|
||||
function parseDate(ctx, c, endChr) {
|
||||
let startPtr = ctx.p++, unsafeSeparator;
|
||||
if (!isDigit(c) ||
|
||||
!isDigit(ctx.s.charCodeAt(ctx.p++)) ||
|
||||
!isDigit(ctx.s.charCodeAt(ctx.p++)) ||
|
||||
!isDigit(ctx.s.charCodeAt(ctx.p++))) {
|
||||
return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
|
||||
}
|
||||
ctx.p += 5;
|
||||
if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
|
||||
TomlError.x('invalid date-time: date part is malformed', ctx, startPtr);
|
||||
if (ctx.p >= ctx.s.length || (((c = ctx.s.charCodeAt(ctx.p)) !== 0x20 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 0x54 /* T */ && c !== 0x74 /* t */)) {
|
||||
let t = ctx.s.slice(startPtr, ctx.p);
|
||||
return readDate(ctx, t, 3, false, startPtr);
|
||||
}
|
||||
if (ctx.s.charCodeAt(ctx.p += 3) !== 0x3a /* : */)
|
||||
TomlError.x('invalid date-time: time part is malformed', ctx, startPtr);
|
||||
if (ctx.s.charCodeAt(ctx.p += 3) === 0x3a /* : */)
|
||||
ctx.p += 3;
|
||||
if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)
|
||||
while (isDigit(ctx.s.charCodeAt(++ctx.p)))
|
||||
;
|
||||
if (c = ctx.s.charCodeAt(ctx.p)) {
|
||||
if (c === 0x5a /* Z */ || c === 0x7a /* z */) {
|
||||
let t = ctx.s.slice(startPtr, ++ctx.p);
|
||||
return readDate(ctx, t, 1, unsafeSeparator, startPtr, '[+00:00]');
|
||||
}
|
||||
if (c === 0x2b /* + */ || c === 0x2d /* - */) {
|
||||
// Temporal's ZonedDateTime is weird asf when it comes to dealing with traditional offsets...
|
||||
// It's 1.2x faster to allocate a new string to pass to ZDT than use Instant.toZonedDateTimeISO
|
||||
let t = ctx.s.slice(startPtr, ctx.p += 6);
|
||||
return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && ('[' + ctx.s.slice(ctx.p - 6, ctx.p) + ']'));
|
||||
}
|
||||
}
|
||||
let t = ctx.s.slice(startPtr, ctx.p);
|
||||
return readDate(ctx, t, 2, unsafeSeparator, startPtr);
|
||||
}
|
||||
function parseTime(ctx, c, endChr) {
|
||||
let start = ctx.p;
|
||||
if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
|
||||
return parseNumber(ctx, --ctx.p, c, 0, endChr);
|
||||
}
|
||||
if (ctx.s.charCodeAt(ctx.p += 4) === 0x3a /* : */)
|
||||
ctx.p += 3;
|
||||
if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)
|
||||
while (isDigit(ctx.s.charCodeAt(++ctx.p)))
|
||||
;
|
||||
let t = ctx.s.slice(start, ctx.p);
|
||||
return readDate(ctx, t, 4, false, start);
|
||||
}
|
||||
function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
|
||||
if (ctx.ld) {
|
||||
let date = new TomlDate(str, type, unsafeDelim);
|
||||
if (!date.isValid())
|
||||
TomlError.x('invalid date', ctx, errPtr);
|
||||
return date;
|
||||
}
|
||||
try {
|
||||
if (temporalSuffix)
|
||||
str += temporalSuffix;
|
||||
switch (type) {
|
||||
case 1: return Temporal.ZonedDateTime.from(str);
|
||||
case 2: return Temporal.PlainDateTime.from(str);
|
||||
case 3: return Temporal.PlainDate.from(str);
|
||||
case 4: return Temporal.PlainTime.from(str);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
TomlError.x(e instanceof Error ? e.message : '' + e, ctx, errPtr);
|
||||
}
|
||||
}
|
||||
+771
@@ -0,0 +1,771 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
"use strict";
|
||||
Object.defineProperties(exports, {
|
||||
__esModule: { value: true },
|
||||
[Symbol.toStringTag]: { value: "Module" }
|
||||
});
|
||||
//#region src/error.ts
|
||||
function getLineColFromPtr(string, ptr) {
|
||||
let lines = string.slice(0, ptr).split(/\r?\n/);
|
||||
return [lines.length, lines.pop().length + 1];
|
||||
}
|
||||
function makeCodeBlock(string, line, column) {
|
||||
let lines = string.split(/\r?\n/);
|
||||
let codeblock = "";
|
||||
let numberLen = (Math.log10(line + 1) | 0) + 1;
|
||||
for (let i = line - 1; i <= line + 1; i++) {
|
||||
let l = lines[i - 1];
|
||||
if (!l) continue;
|
||||
codeblock += i.toString().padEnd(numberLen, " ");
|
||||
codeblock += ": ";
|
||||
codeblock += l;
|
||||
codeblock += "\n";
|
||||
if (i === line) {
|
||||
codeblock += " ".repeat(numberLen + column + 2);
|
||||
codeblock += "^\n";
|
||||
}
|
||||
}
|
||||
return codeblock;
|
||||
}
|
||||
var TomlError = class TomlError extends Error {
|
||||
line;
|
||||
column;
|
||||
codeblock;
|
||||
constructor(message, options) {
|
||||
const [line, column] = getLineColFromPtr(options.toml, options.ptr);
|
||||
const codeblock = makeCodeBlock(options.toml, line, column);
|
||||
super(`Invalid TOML document: ${message}\n\n${codeblock}`, options);
|
||||
this.line = line;
|
||||
this.column = column;
|
||||
this.codeblock = codeblock;
|
||||
}
|
||||
/** @internal */
|
||||
static x(message, ctx, ptr) {
|
||||
throw new TomlError(message, {
|
||||
toml: ctx.s,
|
||||
ptr: ptr ?? ctx.p
|
||||
});
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
//#region src/primitive.ts
|
||||
/** @internal */
|
||||
function parseString(ctx) {
|
||||
let startPtr = ctx.p;
|
||||
let c = ctx.s.charCodeAt(ctx.p++);
|
||||
let first = c;
|
||||
let isLiteral = c === 39;
|
||||
let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
|
||||
if (isMultiline) {
|
||||
if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10) ctx.p++;
|
||||
else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) ctx.p += 2;
|
||||
}
|
||||
let parsed = "";
|
||||
let sliceStart = ctx.p;
|
||||
let state = 0;
|
||||
for (; ctx.p < ctx.s.length; ctx.p++) {
|
||||
c = ctx.s.charCodeAt(ctx.p);
|
||||
if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) state = state && 3;
|
||||
else if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in strings", ctx);
|
||||
else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
|
||||
if (isMultiline) {
|
||||
if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
|
||||
if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
|
||||
}
|
||||
if (!state) {
|
||||
let s = ctx.s.slice(sliceStart, ctx.p);
|
||||
parsed = parsed ? parsed + s : s;
|
||||
}
|
||||
ctx.p += isMultiline ? 3 : 1;
|
||||
return parsed;
|
||||
} else if (!state) {
|
||||
if (!isLiteral && c === 92) {
|
||||
parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
|
||||
state = 1;
|
||||
}
|
||||
} else if (state === 1) {
|
||||
if (c === 120 || c === 117 || c === 85) {
|
||||
let errPtr = ctx.p++ - 1;
|
||||
let value = 0;
|
||||
let len = c === 120 ? 2 : c === 117 ? 4 : 8;
|
||||
for (let j = 0; j < len; j++, ctx.p++) {
|
||||
let hex = ctx.s.charCodeAt(ctx.p);
|
||||
let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
|
||||
if (digit < 0) TomlError.x("invalid non-hex character in unicode escape", ctx);
|
||||
value = value << 4 | digit;
|
||||
}
|
||||
if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) TomlError.x("invalid unicode escape", ctx, errPtr);
|
||||
parsed += String.fromCodePoint(value);
|
||||
sliceStart = ctx.p--;
|
||||
state = 0;
|
||||
} else if (isMultiline && (c === 32 || c === 9)) state = 2;
|
||||
else {
|
||||
if (c === 98) parsed += "\b";
|
||||
else if (c === 116) parsed += " ";
|
||||
else if (c === 110) parsed += "\n";
|
||||
else if (c === 102) parsed += "\f";
|
||||
else if (c === 114) parsed += "\r";
|
||||
else if (c === 101) parsed += "\x1B";
|
||||
else if (c === 34) parsed += "\"";
|
||||
else if (c === 92) parsed += "\\";
|
||||
else TomlError.x("unrecognised escape sequence", ctx);
|
||||
sliceStart = ctx.p + 1;
|
||||
state = 0;
|
||||
}
|
||||
} else if (c !== 32 && c !== 9) {
|
||||
if (state === 2) TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
|
||||
state = !isLiteral && c === 92 ? 1 : 0;
|
||||
sliceStart = ctx.p;
|
||||
}
|
||||
}
|
||||
TomlError.x("unfinished string", ctx, startPtr);
|
||||
}
|
||||
//#endregion
|
||||
//#region src/date.ts
|
||||
let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
|
||||
var TomlDate = class TomlDate extends Date {
|
||||
#hasDate = false;
|
||||
#hasTime = false;
|
||||
#offset = null;
|
||||
constructor(date, fasttype, unsafeDelim) {
|
||||
let hasDate = true;
|
||||
let hasTime = true;
|
||||
let offset = "Z";
|
||||
let c;
|
||||
if (typeof date === "string") {
|
||||
if (fasttype) prep: {
|
||||
if (fasttype < 3) {
|
||||
if (+date.slice(11, 13) > 23) {
|
||||
date = "";
|
||||
break prep;
|
||||
}
|
||||
if (fasttype === 2) {
|
||||
offset = null;
|
||||
date += "Z";
|
||||
} else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) offset = date.slice(date.length - 6);
|
||||
if (unsafeDelim) date = date.slice(0, 10) + "T" + date.slice(11);
|
||||
} else if (fasttype === 4) date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
|
||||
hasDate = fasttype !== 4;
|
||||
hasTime = fasttype !== 3;
|
||||
}
|
||||
else {
|
||||
let match = date.match(DATE_TIME_RE);
|
||||
if (match) {
|
||||
if (!match[1]) {
|
||||
hasDate = false;
|
||||
date = `0000-01-01T${date}`;
|
||||
}
|
||||
hasTime = !!match[2];
|
||||
hasTime && date[10] === " " && (date = date.replace(" ", "T"));
|
||||
if (match[2] && +match[2] > 23) date = "";
|
||||
else {
|
||||
offset = match[3] || null;
|
||||
if (!offset && hasTime) date += "Z";
|
||||
}
|
||||
} else date = "";
|
||||
}
|
||||
}
|
||||
super(date);
|
||||
if (!isNaN(this.getTime())) {
|
||||
this.#hasDate = hasDate;
|
||||
this.#hasTime = hasTime;
|
||||
this.#offset = offset;
|
||||
}
|
||||
}
|
||||
isDateTime() {
|
||||
return this.#hasDate && this.#hasTime;
|
||||
}
|
||||
isLocal() {
|
||||
return !this.#hasDate || !this.#hasTime || !this.#offset;
|
||||
}
|
||||
isDate() {
|
||||
return this.#hasDate && !this.#hasTime;
|
||||
}
|
||||
isTime() {
|
||||
return this.#hasTime && !this.#hasDate;
|
||||
}
|
||||
isValid() {
|
||||
return this.#hasDate || this.#hasTime;
|
||||
}
|
||||
toISOString() {
|
||||
let iso = super.toISOString();
|
||||
if (this.isDate()) return iso.slice(0, 10);
|
||||
if (this.isTime()) return iso.slice(11, 23);
|
||||
if (this.#offset === null) return iso.slice(0, -1);
|
||||
if (this.#offset === "Z" || this.#offset === "z") return iso;
|
||||
let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
|
||||
offset = this.#offset[0] === "-" ? offset : -offset;
|
||||
return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
|
||||
}
|
||||
static wrapAsOffsetDateTime(jsDate, offset = "Z") {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#offset = offset;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalDateTime(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalDate(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#hasTime = false;
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
static wrapAsLocalTime(jsDate) {
|
||||
let date = new TomlDate(jsDate);
|
||||
date.#hasDate = false;
|
||||
date.#offset = null;
|
||||
return date;
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
//#region src/extract.ts
|
||||
function isDigit(char, base = 10) {
|
||||
return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
|
||||
}
|
||||
function isEndOfValue(char, delim) {
|
||||
return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
|
||||
}
|
||||
/** @internal */
|
||||
function extractValue(ctx, end) {
|
||||
let errPtr = ctx.p;
|
||||
let c = ctx.s.charCodeAt(ctx.p);
|
||||
if (c === 91 || c === 123) {
|
||||
ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
|
||||
let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
|
||||
ctx.d++;
|
||||
return value;
|
||||
}
|
||||
if (c === 34 || c === 39) return parseString(ctx);
|
||||
if (c === 116) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
|
||||
return ctx.p++, true;
|
||||
}
|
||||
if (c === 102) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
|
||||
return ctx.p++, false;
|
||||
}
|
||||
if (c === 43 || c === 45) return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
|
||||
if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) return parseDate(ctx, c, end);
|
||||
if (ctx.s.charCodeAt(ctx.p + 2) === 58) return parseTime(ctx, c, end);
|
||||
return parseNumber(ctx, ctx.p, c, 0, end);
|
||||
}
|
||||
function parseNumber(ctx, startPtr, startChr, sign, endChr) {
|
||||
let c = startChr;
|
||||
let state = 0;
|
||||
let hasUnderscores = false;
|
||||
if (c === 105) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102) TomlError.x("invalid value", ctx, startPtr);
|
||||
return ctx.p++, (sign || 1) / 0;
|
||||
}
|
||||
if (c === 110) {
|
||||
if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110) TomlError.x("invalid value", ctx, startPtr);
|
||||
return ctx.p++, NaN;
|
||||
}
|
||||
if (c === 48) {
|
||||
if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr)) return ctx.bi === true ? 0n : 0;
|
||||
if (!sign) {
|
||||
if (c === 120) return parseIntegerBaseN(ctx, startPtr, 16, endChr);
|
||||
else if (c === 98) return parseIntegerBaseN(ctx, startPtr, 2, endChr);
|
||||
else if (c === 111) return parseIntegerBaseN(ctx, startPtr, 8, endChr);
|
||||
}
|
||||
if (c === 46) state = 2;
|
||||
else if (c === 101 || c === 69) state = 4;
|
||||
else TomlError.x("illegal leading zero", ctx, startPtr);
|
||||
} else if (!isDigit(c)) TomlError.x("invalid value", ctx, startPtr);
|
||||
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
|
||||
if (!state) state = 1;
|
||||
if (c === 95) {
|
||||
if (!(state & 1)) TomlError.x("illegal underscore", ctx);
|
||||
state += 11;
|
||||
hasUnderscores = true;
|
||||
} else if (state === 1 && c === 46) state = 2;
|
||||
else if ((state === 1 || state === 3) && (c === 101 || c === 69)) state = 4;
|
||||
else if (state === 4 && (c === 43 || c === 45)) state = 6;
|
||||
else if (!isDigit(c)) TomlError.x(`illegal character in numeric literal`, ctx);
|
||||
else if (state > 9) state -= 11;
|
||||
else if (!(state & 1)) state++;
|
||||
}
|
||||
if (!state) {
|
||||
let val = (startChr - 48) * (sign || 1);
|
||||
return ctx.bi === true ? BigInt(val) : val;
|
||||
}
|
||||
if (!(state & 1)) TomlError.x("unfinished numeric value", ctx, startPtr);
|
||||
let str = ctx.s.slice(startPtr, ctx.p);
|
||||
if (hasUnderscores) str = str.replaceAll("_", "");
|
||||
return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
|
||||
}
|
||||
function parseIntegerBaseN(ctx, startPtr, base, endChr) {
|
||||
let c, underscore = 1;
|
||||
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) if (c === 95) {
|
||||
if (underscore & 1) TomlError.x("illegal underscore", ctx);
|
||||
underscore = 3;
|
||||
} else if (!isDigit(c, base)) TomlError.x(`illegal character in numeric literal`, ctx);
|
||||
else if (underscore & 1) underscore--;
|
||||
if (underscore & 1) TomlError.x("unfinished numeric value", ctx);
|
||||
let str = ctx.s.slice(startPtr + 2, ctx.p);
|
||||
if (underscore) str = str.replaceAll("_", "");
|
||||
return parseInteger(ctx, str, base, startPtr);
|
||||
}
|
||||
function parseInteger(ctx, str, base, startPtr) {
|
||||
if (ctx.bi !== true) int: {
|
||||
let val = parseInt(str, base);
|
||||
if (!Number.isSafeInteger(val)) {
|
||||
if (ctx.bi) break int;
|
||||
TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
|
||||
}
|
||||
function parseDate(ctx, c, endChr) {
|
||||
let startPtr = ctx.p++, unsafeSeparator;
|
||||
if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
|
||||
ctx.p += 5;
|
||||
if (!isDigit(ctx.s.charCodeAt(ctx.p++))) TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
|
||||
if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 3, false, startPtr);
|
||||
if (ctx.s.charCodeAt(ctx.p += 3) !== 58) TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
|
||||
if (ctx.s.charCodeAt(ctx.p += 3) === 58) ctx.p += 3;
|
||||
if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
|
||||
if (c = ctx.s.charCodeAt(ctx.p)) {
|
||||
if (c === 90 || c === 122) return readDate(ctx, ctx.s.slice(startPtr, ++ctx.p), 1, unsafeSeparator, startPtr, "[+00:00]");
|
||||
if (c === 43 || c === 45) return readDate(ctx, ctx.s.slice(startPtr, ctx.p += 6), 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
|
||||
}
|
||||
return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 2, unsafeSeparator, startPtr);
|
||||
}
|
||||
function parseTime(ctx, c, endChr) {
|
||||
let start = ctx.p;
|
||||
if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) return parseNumber(ctx, --ctx.p, c, 0, endChr);
|
||||
if (ctx.s.charCodeAt(ctx.p += 4) === 58) ctx.p += 3;
|
||||
if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
|
||||
return readDate(ctx, ctx.s.slice(start, ctx.p), 4, false, start);
|
||||
}
|
||||
function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
|
||||
if (ctx.ld) {
|
||||
let date = new TomlDate(str, type, unsafeDelim);
|
||||
if (!date.isValid()) TomlError.x("invalid date", ctx, errPtr);
|
||||
return date;
|
||||
}
|
||||
try {
|
||||
if (temporalSuffix) str += temporalSuffix;
|
||||
switch (type) {
|
||||
case 1: return Temporal.ZonedDateTime.from(str);
|
||||
case 2: return Temporal.PlainDateTime.from(str);
|
||||
case 3: return Temporal.PlainDate.from(str);
|
||||
case 4: return Temporal.PlainTime.from(str);
|
||||
}
|
||||
} catch (e) {
|
||||
TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/util.ts
|
||||
/** @internal */
|
||||
function skipComment(ctx) {
|
||||
for (; ctx.p < ctx.s.length; ctx.p++) {
|
||||
let c = ctx.s.charCodeAt(ctx.p);
|
||||
if (c === 10) break;
|
||||
if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
|
||||
ctx.p++;
|
||||
break;
|
||||
}
|
||||
if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in comments", ctx);
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
function skipVoid(ctx, banNewLines, banComments) {
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10))) ctx.p++;
|
||||
if (banComments || c !== 35) break;
|
||||
skipComment(ctx);
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/struct.ts
|
||||
/** @internal */
|
||||
function parseKey(ctx, end = 61) {
|
||||
let startPtr;
|
||||
let state = 0;
|
||||
let parsed = [];
|
||||
let sliceStart;
|
||||
let c = ctx.s.charCodeAt(startPtr = ctx.p);
|
||||
do
|
||||
if (c === end) {
|
||||
if (!state) TomlError.x("unexpected end of key", ctx);
|
||||
if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
return ctx.p++, parsed;
|
||||
} else if (c === 46) {
|
||||
if (!state) TomlError.x("illegal empty bare key", ctx);
|
||||
if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
state = 0;
|
||||
} else if (!state && (c === 34 || c === 39)) {
|
||||
if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2)) TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
|
||||
parsed.push(parseString(ctx));
|
||||
state = 2;
|
||||
ctx.p--;
|
||||
} else if (c === 32 || c === 9) {
|
||||
if (state === 1) {
|
||||
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
state = 2;
|
||||
}
|
||||
} else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) TomlError.x("illegal character in key", ctx);
|
||||
else if (!state) {
|
||||
state = 1;
|
||||
sliceStart = ctx.p;
|
||||
}
|
||||
while (c = ctx.s.charCodeAt(++ctx.p));
|
||||
TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
|
||||
}
|
||||
/** @internal */
|
||||
function parseInlineTable(ctx) {
|
||||
let startPtr = ctx.p++;
|
||||
let res = Object.create(null);
|
||||
let seen = /* @__PURE__ */ new Set();
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
|
||||
ctx.p++;
|
||||
return res;
|
||||
}
|
||||
let k;
|
||||
let t = res;
|
||||
let hasOwn = false;
|
||||
let errPtr = ctx.p;
|
||||
let key = parseKey(ctx);
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
if (i) t = hasOwn ? t[k] : t[k] = Object.create(null);
|
||||
k = key[i];
|
||||
if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
|
||||
let unsafe = k === "__proto__";
|
||||
if (ctx.uk && (unsafe || k === "constructor")) {
|
||||
t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
|
||||
break;
|
||||
}
|
||||
if (!hasOwn && unsafe) Object.defineProperty(t, k, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
}
|
||||
if (hasOwn) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
|
||||
skipVoid(ctx, true, true);
|
||||
let value = extractValue(ctx, 125);
|
||||
if (t && typeof (t[k] = value) === "object") seen.add(value);
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) return res;
|
||||
if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
|
||||
}
|
||||
TomlError.x("unfinished table", ctx, startPtr);
|
||||
}
|
||||
/** @internal */
|
||||
function parseArray(ctx) {
|
||||
let startPtr = ctx.p++;
|
||||
let res = [];
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
|
||||
ctx.p++;
|
||||
return res;
|
||||
}
|
||||
res.push(extractValue(ctx, 93));
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) return res;
|
||||
if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
|
||||
}
|
||||
TomlError.x("unfinished array", ctx, startPtr);
|
||||
}
|
||||
//#endregion
|
||||
//#region src/parse.ts
|
||||
function peekTable(ctx, key, table, meta, type) {
|
||||
let t = table;
|
||||
let m = meta;
|
||||
let k;
|
||||
let hasOwn = false;
|
||||
let state;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
if (i) {
|
||||
t = hasOwn ? t[k] : t[k] = Object.create(null);
|
||||
m = (state = m[k]).c;
|
||||
if (type === 0 && (state.t === 1 || state.t === 2)) return null;
|
||||
if (state.t === 2) {
|
||||
let l = t.length - 1;
|
||||
t = t[l];
|
||||
m = m[l].c;
|
||||
}
|
||||
}
|
||||
k = key[i];
|
||||
if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
|
||||
if (!hasOwn) {
|
||||
let unsafe = k === "__proto__";
|
||||
if (ctx.uk && (unsafe || k === "constructor")) return false;
|
||||
if (unsafe) {
|
||||
Object.defineProperty(t, k, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
Object.defineProperty(m, k, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
}
|
||||
m[k] = {
|
||||
t: i < key.length - 1 && type === 2 ? 3 : type,
|
||||
d: false,
|
||||
i: 0,
|
||||
c: Object.create(null)
|
||||
};
|
||||
}
|
||||
}
|
||||
state = m[k];
|
||||
if (state.t !== type && !(type === 1 && state.t === 3)) return null;
|
||||
if (type === 2) {
|
||||
if (!state.d) {
|
||||
state.d = true;
|
||||
t[k] = [];
|
||||
}
|
||||
t[k].push(t = Object.create(null));
|
||||
state.c[state.i++] = state = {
|
||||
t: 1,
|
||||
d: false,
|
||||
i: 0,
|
||||
c: Object.create(null)
|
||||
};
|
||||
}
|
||||
if (state.d) return null;
|
||||
state.d = true;
|
||||
if (type === 1) t = hasOwn ? t[k] : t[k] = Object.create(null);
|
||||
else if (type === 0 && hasOwn) return null;
|
||||
return [
|
||||
k,
|
||||
t,
|
||||
state.c
|
||||
];
|
||||
}
|
||||
function validateTablePeek(ctx, peek, ptr) {
|
||||
if (peek === null || ctx.uk === 2) TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
|
||||
}
|
||||
function parse(toml, options = {}) {
|
||||
let ctx = {
|
||||
s: toml,
|
||||
p: 0,
|
||||
d: options.maxDepth ?? 1e3,
|
||||
bi: options.integersAsBigInt ?? false,
|
||||
ld: options.useLegacyDate ?? true,
|
||||
uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
|
||||
};
|
||||
let res = Object.create(null);
|
||||
let meta = Object.create(null);
|
||||
let tmp;
|
||||
let skipping = false;
|
||||
let tbl = res;
|
||||
let m = meta;
|
||||
if (toml.charCodeAt(0) === 65279) ctx.p++;
|
||||
skipVoid(ctx);
|
||||
while (ctx.p < toml.length) {
|
||||
if (toml.charCodeAt(ctx.p) === 91) {
|
||||
let isTableArray = toml.charCodeAt(++ctx.p) === 91;
|
||||
tmp = ctx.p += +isTableArray;
|
||||
skipping = false;
|
||||
let k = parseKey(ctx, 93);
|
||||
if (isTableArray) {
|
||||
if (toml.charCodeAt(ctx.p) !== 93) TomlError.x("expected end of table array declaration", ctx);
|
||||
ctx.p++;
|
||||
}
|
||||
let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
|
||||
if (!p) {
|
||||
validateTablePeek(ctx, p, tmp);
|
||||
skipping = true;
|
||||
} else {
|
||||
m = p[2];
|
||||
tbl = p[1];
|
||||
}
|
||||
} else {
|
||||
tmp = ctx.p;
|
||||
let p = peekTable(ctx, parseKey(ctx), tbl, m, 0);
|
||||
if (!p && !skipping) validateTablePeek(ctx, p, tmp);
|
||||
skipVoid(ctx, true, true);
|
||||
let v = extractValue(ctx, void 0);
|
||||
if (p && !skipping) p[1][p[0]] = v;
|
||||
}
|
||||
skipVoid(ctx, true);
|
||||
if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
|
||||
skipVoid(ctx);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/stringify.ts
|
||||
let BARE_KEY = /^[a-z0-9-_]+$/i;
|
||||
let HAS_WELLFORMED = !!"".isWellFormed;
|
||||
function extendedTypeOf(obj) {
|
||||
let type = typeof obj;
|
||||
if (type === "object") {
|
||||
if (Array.isArray(obj)) return "array";
|
||||
if (typeof obj.getUTCDate === "function" && obj instanceof Date) return "date";
|
||||
if (globalThis.Temporal) {
|
||||
if (obj.until) {
|
||||
if (obj instanceof Temporal.ZonedDateTime) return "temporal/tz+uc";
|
||||
if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate) return "temporal/uc";
|
||||
if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant) return "temporal";
|
||||
if (obj instanceof Temporal.PlainYearMonth) return "temporal/x";
|
||||
} else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) return "temporal/x";
|
||||
}
|
||||
}
|
||||
return type;
|
||||
}
|
||||
function isArrayOfTables(obj) {
|
||||
for (let i = 0; i < obj.length; i++) if (extendedTypeOf(obj[i]) !== "object") return false;
|
||||
return obj.length != 0;
|
||||
}
|
||||
function formatWellFormedStringUnchecked(s) {
|
||||
return JSON.stringify(s).replaceAll("", "\\u007f");
|
||||
}
|
||||
function formatString(s) {
|
||||
return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
|
||||
}
|
||||
function formatKey(s) {
|
||||
if (BARE_KEY.test(s)) return s;
|
||||
if (HAS_WELLFORMED && !s.isWellFormed()) throw new RangeError("key contains illegal lone surrogates");
|
||||
return formatWellFormedStringUnchecked(s);
|
||||
}
|
||||
function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
|
||||
switch (type) {
|
||||
case "number":
|
||||
if (isNaN(val)) return "nan";
|
||||
if (val === Infinity) return "inf";
|
||||
if (val === -Infinity) return "-inf";
|
||||
if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val))) return val.toFixed(1);
|
||||
case "bigint":
|
||||
case "boolean":
|
||||
case "temporal": return val.toString();
|
||||
case "string": return formatString(val);
|
||||
case "date":
|
||||
if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
|
||||
return val.toISOString();
|
||||
case "object": return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
|
||||
case "array": return stringifyArray(val, depth, numberAsFloat, strictTemporal);
|
||||
case "temporal/tz+uc": if (strictTemporal) {
|
||||
let tz = val.timeZoneId;
|
||||
let tzc = tz.charCodeAt(0);
|
||||
if (tzc !== 43 && tzc !== 45 && (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || tz !== "UTC" && tz !== "UCT" && tz !== "Universal" && tz !== "Zulu" && !tz.startsWith("GMT") && tz !== "Greenwich" && !tz.startsWith("Etc/"))) throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
|
||||
}
|
||||
case "temporal/uc":
|
||||
if (strictTemporal && val.calendarId !== "iso8601") throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
|
||||
return val.toString({
|
||||
calendarName: "never",
|
||||
timeZoneName: "never"
|
||||
});
|
||||
case "temporal/x": throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
|
||||
}
|
||||
}
|
||||
function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
|
||||
let keys = Object.keys(obj);
|
||||
if (keys.length === 0) return "{}";
|
||||
let res = "{ ";
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let k = keys[i];
|
||||
if (i) res += ", ";
|
||||
res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res + " }";
|
||||
}
|
||||
function stringifyArray(array, depth, numberAsFloat, strictTemporal) {
|
||||
if (array.length === 0) return "[]";
|
||||
let res = "[ ";
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (i) res += ", ";
|
||||
if (array[i] === null || array[i] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
|
||||
res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res + " ]";
|
||||
}
|
||||
function stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
|
||||
let res = "";
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
res += `${res && "\n"}[[${key}]]\n`;
|
||||
res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
|
||||
let preamble = "";
|
||||
let tables = "";
|
||||
let keys = Object.keys(obj);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let k = keys[i];
|
||||
if (obj[k] !== null && obj[k] !== void 0) {
|
||||
let type = extendedTypeOf(obj[k]);
|
||||
if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
|
||||
let key = formatKey(k);
|
||||
if (type === "array" && isArrayOfTables(obj[k])) tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
|
||||
else if (type === "object") {
|
||||
let tblKey = prefix ? `${prefix}.${key}` : key;
|
||||
tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
|
||||
} else {
|
||||
preamble += key;
|
||||
preamble += " = ";
|
||||
preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
|
||||
preamble += "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tableKey && (preamble || !tables)) preamble = preamble ? `[${tableKey}]\n${preamble}` : `[${tableKey}]`;
|
||||
return preamble && tables ? `${preamble}\n${tables}` : preamble || tables;
|
||||
}
|
||||
function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
|
||||
if (extendedTypeOf(obj) !== "object") throw new TypeError("stringify can only be called with an object");
|
||||
let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
|
||||
if (str[str.length - 1] !== "\n") return str + "\n";
|
||||
return str;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/index.ts
|
||||
/** @deprecated use `import * as ... from 'smol-toml'` instead */
|
||||
var src_default = {
|
||||
parse,
|
||||
stringify,
|
||||
TomlDate,
|
||||
TomlError
|
||||
};
|
||||
//#endregion
|
||||
exports.TomlDate = TomlDate;
|
||||
exports.TomlError = TomlError;
|
||||
exports.default = src_default;
|
||||
exports.parse = parse;
|
||||
exports.stringify = stringify;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { parse } from './parse.js';
|
||||
import { stringify } from './stringify.js';
|
||||
import { TomlDate } from './date.js';
|
||||
import { TomlError } from './error.js';
|
||||
export type { TomlValue, TomlTable, TomlValueWithoutBigInt, TomlTableWithoutBigInt } from './util.js';
|
||||
export { parse, stringify, TomlDate, TomlError };
|
||||
export type {
|
||||
/** @deprecated use {@link TomlValue} instead */
|
||||
TomlValue as TomlPrimitive, } from './util.js';
|
||||
/** @deprecated use `import * as ... from 'smol-toml'` instead */
|
||||
declare const _default: {
|
||||
parse: typeof parse;
|
||||
stringify: typeof stringify;
|
||||
TomlDate: typeof TomlDate;
|
||||
TomlError: typeof TomlError;
|
||||
};
|
||||
export default _default;
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { parse } from './parse.js';
|
||||
import { stringify } from './stringify.js';
|
||||
import { TomlDate } from './date.js';
|
||||
import { TomlError } from './error.js';
|
||||
export { parse, stringify, TomlDate, TomlError };
|
||||
/** @deprecated use `import * as ... from 'smol-toml'` instead */
|
||||
export default { parse, stringify, TomlDate, TomlError };
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { type IntegersAsBigInt, type TomlTable, type TomlTableWithoutBigInt } from './util.js';
|
||||
export type UnsafeKeyBehaviour =
|
||||
/** Preserve the unsafe key in the final object. */
|
||||
'keep'
|
||||
/** Silently drop the unsafe key from the final object. */
|
||||
| 'drop'
|
||||
/** Reject documents with unsafe keys. */
|
||||
| 'throw';
|
||||
export interface ParseOptions {
|
||||
/**
|
||||
* Whether to parse integers as {@link BigInt} or not.
|
||||
*
|
||||
* Use the special value `"asNeeded"` to only use {@link BigInt} for
|
||||
* integers that cannot be safely represented as JavaScript numbers.
|
||||
*
|
||||
* @defaultValue `false`
|
||||
* @since 1.4.0
|
||||
*/
|
||||
integersAsBigInt?: IntegersAsBigInt;
|
||||
/**
|
||||
* Whether to use the legacy {@link TomlDate}, instead of the new
|
||||
* {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal | Temporal API}.
|
||||
*
|
||||
* @defaultValue `true`
|
||||
* @since 1.9.0
|
||||
*/
|
||||
useLegacyDate?: boolean;
|
||||
/**
|
||||
* Behaviour of the library when encountering a potentially unsafe property (`__proto__`, `constructor`).
|
||||
*
|
||||
* @defaultValue `'keep'`
|
||||
* @since 1.9.0
|
||||
*/
|
||||
unsafeKeyBehaviour?: UnsafeKeyBehaviour;
|
||||
/**
|
||||
* Maximum permitted inline object/array depth.
|
||||
*
|
||||
* @defaultValue `1000`
|
||||
* @since 1.9.0
|
||||
*/
|
||||
maxDepth?: number;
|
||||
}
|
||||
export declare function parse(toml: string, options?: ParseOptions & {
|
||||
integersAsBigInt: Exclude<IntegersAsBigInt, undefined | false>;
|
||||
}): TomlTable;
|
||||
export declare function parse(toml: string, options?: ParseOptions): TomlTableWithoutBigInt;
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { parseKey } from './struct.js';
|
||||
import { extractValue } from './extract.js';
|
||||
import { skipVoid } from './util.js';
|
||||
import { TomlError } from './error.js';
|
||||
function peekTable(ctx, key, table, meta, type) {
|
||||
let t = table;
|
||||
let m = meta;
|
||||
let k;
|
||||
let hasOwn = false;
|
||||
let state;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
if (i) {
|
||||
t = hasOwn ? t[k] : (t[k] = Object.create(null));
|
||||
m = (state = m[k]).c;
|
||||
if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {
|
||||
return null;
|
||||
}
|
||||
if (state.t === 2 /* Type.ARRAY */) {
|
||||
let l = t.length - 1;
|
||||
t = t[l];
|
||||
m = m[l].c;
|
||||
}
|
||||
}
|
||||
k = key[i];
|
||||
if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {
|
||||
return null;
|
||||
}
|
||||
if (!hasOwn) {
|
||||
let unsafe = k === '__proto__';
|
||||
if (ctx.uk && (unsafe || k === 'constructor'))
|
||||
return false;
|
||||
if (unsafe) {
|
||||
Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
|
||||
Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
|
||||
}
|
||||
m[k] = {
|
||||
t: i < key.length - 1 && type === 2 /* Type.ARRAY */
|
||||
? 3 /* Type.ARRAY_DOTTED */ : type,
|
||||
d: false,
|
||||
i: 0,
|
||||
c: Object.create(null),
|
||||
};
|
||||
}
|
||||
}
|
||||
state = m[k];
|
||||
if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {
|
||||
// Bad key type!
|
||||
return null;
|
||||
}
|
||||
if (type === 2 /* Type.ARRAY */) {
|
||||
if (!state.d) {
|
||||
state.d = true;
|
||||
t[k] = [];
|
||||
}
|
||||
t[k].push(t = Object.create(null));
|
||||
state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: Object.create(null) });
|
||||
}
|
||||
if (state.d) {
|
||||
// Redefining a table!
|
||||
return null;
|
||||
}
|
||||
state.d = true;
|
||||
if (type === 1 /* Type.EXPLICIT */) {
|
||||
t = hasOwn ? t[k] : (t[k] = Object.create(null));
|
||||
}
|
||||
else if (type === 0 /* Type.DOTTED */ && hasOwn) {
|
||||
return null;
|
||||
}
|
||||
return [k, t, state.c];
|
||||
}
|
||||
function validateTablePeek(ctx, peek, ptr) {
|
||||
if (peek === null || ctx.uk === 2)
|
||||
TomlError.x(peek === null
|
||||
? 'trying to redefine an already defined table or value'
|
||||
: 'document contains an unsafe property', ctx, ptr);
|
||||
}
|
||||
export function parse(toml, options = {}) {
|
||||
let ctx = {
|
||||
s: toml,
|
||||
p: 0,
|
||||
d: options.maxDepth ?? 1000,
|
||||
bi: options.integersAsBigInt ?? false,
|
||||
ld: options.useLegacyDate ?? true,
|
||||
uk: options.unsafeKeyBehaviour === 'throw' ? 2 : options.unsafeKeyBehaviour === 'drop' ? 1 : 0,
|
||||
};
|
||||
let res = Object.create(null);
|
||||
let meta = Object.create(null);
|
||||
let tmp;
|
||||
let skipping = false;
|
||||
let tbl = res;
|
||||
let m = meta;
|
||||
// BOM is allowed, skip.
|
||||
// JS is UTF-16, so we have to check for the UTF-16 BOM instead of the UTF-8 BOM sequence!
|
||||
if (toml.charCodeAt(0) === 0xfeff)
|
||||
ctx.p++;
|
||||
skipVoid(ctx);
|
||||
while (ctx.p < toml.length) {
|
||||
if (toml.charCodeAt(ctx.p) === 0x5b /* [ */) {
|
||||
let isTableArray = toml.charCodeAt(++ctx.p) === 0x5b; /* [ */
|
||||
tmp = ctx.p += +isTableArray;
|
||||
skipping = false;
|
||||
let k = parseKey(ctx, 0x5d /* ] */);
|
||||
if (isTableArray) {
|
||||
if (toml.charCodeAt(ctx.p) !== 0x5d /* ] */) {
|
||||
TomlError.x('expected end of table array declaration', ctx);
|
||||
}
|
||||
ctx.p++;
|
||||
}
|
||||
let p = peekTable(ctx, k, res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);
|
||||
if (!p) {
|
||||
validateTablePeek(ctx, p, tmp);
|
||||
skipping = true;
|
||||
}
|
||||
else {
|
||||
m = p[2];
|
||||
tbl = p[1];
|
||||
}
|
||||
}
|
||||
else {
|
||||
tmp = ctx.p;
|
||||
let k = parseKey(ctx);
|
||||
let p = peekTable(ctx, k, tbl, m, 0 /* Type.DOTTED */);
|
||||
if (!p && !skipping)
|
||||
validateTablePeek(ctx, p, tmp);
|
||||
skipVoid(ctx, true, true);
|
||||
let v = extractValue(ctx, void 0);
|
||||
if (p && !skipping)
|
||||
p[1][p[0]] = v;
|
||||
}
|
||||
skipVoid(ctx, true);
|
||||
if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 0xa /* \n */ && (tmp !== 0xd /* \r */ || toml.charCodeAt(ctx.p + 1) !== 0xa /* \n */)) {
|
||||
TomlError.x('each key-value declaration must be followed by an end-of-line', ctx);
|
||||
}
|
||||
skipVoid(ctx);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { TomlError } from './error.js';
|
||||
/** @internal */
|
||||
export function parseString(ctx) {
|
||||
let startPtr = ctx.p;
|
||||
let c = ctx.s.charCodeAt(ctx.p++);
|
||||
let first = c;
|
||||
let isLiteral = c === 0x27; /* ' */
|
||||
let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
|
||||
if (isMultiline) {
|
||||
// Trim initial newline
|
||||
if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 0xa /* \n */)
|
||||
ctx.p++;
|
||||
else if (c === 0xd /* \r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \n */)
|
||||
ctx.p += 2;
|
||||
}
|
||||
// For the record: it is not worth it to use a fast-path for literal strings using `indexOf`.
|
||||
// Doing a char-by-char iteration ends up dispatching less instructions, for the same wall-clock runtime.
|
||||
let parsed = '';
|
||||
let sliceStart = ctx.p;
|
||||
// states:
|
||||
// 0 - decoding
|
||||
// 1 - decoding escape
|
||||
// 2 - whitespace escape (no newline encountered yet, must fail on non-whitespace)
|
||||
// 3 - whitespace escape (newline encountered, allowed to transition back to normal decode)
|
||||
let state = 0;
|
||||
for (; ctx.p < ctx.s.length; ctx.p++) {
|
||||
c = ctx.s.charCodeAt(ctx.p);
|
||||
// Deal with newlines first, since that simplifies control character checking and handling across all states
|
||||
if (isMultiline && (c === 0xa /* \n */ || (c === 0xd /* \r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \n */))) {
|
||||
state = state && 3;
|
||||
}
|
||||
// Control characters are banned in TOML, so we throw an error if we encounter them
|
||||
else if ((c < 0x20 && c !== 0x9 /* \t */) || c === 0x7f) {
|
||||
TomlError.x('control characters are not allowed in strings', ctx);
|
||||
}
|
||||
// The string might terminate while we're parsing through a newline escape.
|
||||
// It must have encountered a newline; otherwise, it'll simply fail in another branch.
|
||||
else if ((!state || state === 3) && c === first && (!isMultiline || (ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first))) {
|
||||
if (isMultiline) {
|
||||
// If the string ends with 4-5 quotes, then the first 1-2 are part of the string
|
||||
if (ctx.s.charCodeAt(ctx.p + 3) === first)
|
||||
ctx.p++;
|
||||
if (ctx.s.charCodeAt(ctx.p + 3) === first)
|
||||
ctx.p++;
|
||||
}
|
||||
// If we're in a newline escape still, then there's nothing to add.
|
||||
if (!state) {
|
||||
// Avoid a useless concat operation if the string can be used as-is.
|
||||
let s = ctx.s.slice(sliceStart, ctx.p);
|
||||
parsed = parsed ? parsed + s : s;
|
||||
}
|
||||
ctx.p += isMultiline ? 3 : 1;
|
||||
return parsed;
|
||||
}
|
||||
// Baseline state; keep moving forward unless an escape sequence starts
|
||||
else if (!state) {
|
||||
if (!isLiteral && c === 0x5c /* \ */) {
|
||||
parsed += ctx.s.slice(sliceStart, (sliceStart = ctx.p));
|
||||
state = 1;
|
||||
}
|
||||
}
|
||||
else if (state === 1) {
|
||||
if (c === 0x78 /* x */ || c === 0x75 /* u */ || c === 0x55 /* U */) { // Unicode escape
|
||||
let errPtr = ctx.p++ - 1;
|
||||
let value = 0;
|
||||
let len = c === 0x78 /* x */ ? 2 : c === 0x75 /* u */ ? 4 : 8;
|
||||
for (let j = 0; j < len; j++, ctx.p++) {
|
||||
let hex = ctx.s.charCodeAt(ctx.p);
|
||||
let digit =
|
||||
/* 0-9 */ hex >= 0x30 && hex <= 0x39 ? hex - 0x30 :
|
||||
/* A-F */ hex >= 0x41 && hex <= 0x46 ? hex - 0x41 + 10 :
|
||||
/* a-f */ hex >= 0x61 && hex <= 0x66 ? hex - 0x61 + 10 : -1;
|
||||
if (digit < 0)
|
||||
TomlError.x('invalid non-hex character in unicode escape', ctx);
|
||||
value = (value << 4) | digit;
|
||||
}
|
||||
// Because JS does bitwise on signed 32bit integers, all 0xfzzzzzzz values are actually seen as negative
|
||||
if (value < 0 || value > 0x10ffff || (value >= 0xd800 && value <= 0xdfff)) {
|
||||
TomlError.x('invalid unicode escape', ctx, errPtr);
|
||||
}
|
||||
parsed += String.fromCodePoint(value);
|
||||
sliceStart = ctx.p--;
|
||||
state = 0;
|
||||
}
|
||||
// Newline escape sequence. We only need to care about spaces and tabs; newlines are dealt with earlier
|
||||
else if (isMultiline && (c === 0x20 || c === 0x9 /* \t */)) {
|
||||
state = 2;
|
||||
}
|
||||
// Basic escape sequence
|
||||
else {
|
||||
if (c === 0x62 /* b */)
|
||||
parsed += '\b';
|
||||
else if (c === 0x74 /* t */)
|
||||
parsed += '\t';
|
||||
else if (c === 0x6e /* n */)
|
||||
parsed += '\n';
|
||||
else if (c === 0x66 /* f */)
|
||||
parsed += '\f';
|
||||
else if (c === 0x72 /* r */)
|
||||
parsed += '\r';
|
||||
else if (c === 0x65 /* e */)
|
||||
parsed += '\x1b';
|
||||
else if (c === 0x22 /* " */)
|
||||
parsed += '"';
|
||||
else if (c === 0x5c /* \ */)
|
||||
parsed += '\\';
|
||||
else
|
||||
TomlError.x('unrecognised escape sequence', ctx);
|
||||
sliceStart = ctx.p + 1;
|
||||
state = 0;
|
||||
}
|
||||
}
|
||||
// Newline escape continuation: keep moving forward until the first non-whitespace char
|
||||
else if (c !== 0x20 && c !== 0x9 /* \t */) {
|
||||
if (state === 2)
|
||||
TomlError.x('invalid escape: only line-ending whitespace may be escaped', ctx, sliceStart);
|
||||
// State cannot be zero, or we'd have branched earlier already.
|
||||
// If it's a backslash, immediately transition to the escape state so it can be processed.
|
||||
state = !isLiteral && c === 0x5c /* \ */ ? 1 : 0;
|
||||
sliceStart = ctx.p;
|
||||
}
|
||||
}
|
||||
TomlError.x('unfinished string', ctx, startPtr);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
export declare function stringify(obj: any, { maxDepth, numbersAsFloat, strictTemporal }?: {
|
||||
maxDepth?: number;
|
||||
numbersAsFloat?: boolean;
|
||||
strictTemporal?: boolean;
|
||||
}): string;
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
let BARE_KEY = /^[a-z0-9-_]+$/i;
|
||||
let HAS_WELLFORMED = !!(''.isWellFormed);
|
||||
function extendedTypeOf(obj) {
|
||||
let type = typeof obj;
|
||||
if (type === 'object') {
|
||||
if (Array.isArray(obj))
|
||||
return 'array';
|
||||
if (typeof obj.getUTCDate === 'function' && obj instanceof Date)
|
||||
return 'date';
|
||||
if (globalThis.Temporal) {
|
||||
if (obj.until) {
|
||||
if (obj instanceof Temporal.ZonedDateTime)
|
||||
return 'temporal/tz+uc';
|
||||
if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
|
||||
return 'temporal/uc';
|
||||
if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
|
||||
return 'temporal';
|
||||
if (obj instanceof Temporal.PlainYearMonth)
|
||||
return 'temporal/x';
|
||||
}
|
||||
else if ((obj.toPlainDate && obj instanceof Temporal.PlainMonthDay) ||
|
||||
(obj.negated && obj instanceof Temporal.Duration)) {
|
||||
return 'temporal/x';
|
||||
}
|
||||
}
|
||||
}
|
||||
return type;
|
||||
}
|
||||
function isArrayOfTables(obj) {
|
||||
for (let i = 0; i < obj.length; i++) {
|
||||
if (extendedTypeOf(obj[i]) !== 'object')
|
||||
return false;
|
||||
}
|
||||
return obj.length != 0;
|
||||
}
|
||||
function formatWellFormedStringUnchecked(s) {
|
||||
return JSON.stringify(s).replaceAll('\x7f', '\\u007f');
|
||||
}
|
||||
function formatString(s) {
|
||||
return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
|
||||
}
|
||||
function formatKey(s) {
|
||||
if (BARE_KEY.test(s))
|
||||
return s;
|
||||
if (HAS_WELLFORMED && !s.isWellFormed())
|
||||
throw new RangeError('key contains illegal lone surrogates');
|
||||
return formatWellFormedStringUnchecked(s);
|
||||
}
|
||||
function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) {
|
||||
throw new Error('Could not stringify the object: maximum object depth exceeded');
|
||||
}
|
||||
switch (type) {
|
||||
// @ts-expect-error -- intentional fallthrough case
|
||||
case 'number':
|
||||
if (isNaN(val))
|
||||
return 'nan';
|
||||
if (val === Infinity)
|
||||
return 'inf';
|
||||
if (val === -Infinity)
|
||||
return '-inf';
|
||||
if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
|
||||
return val.toFixed(1);
|
||||
case 'bigint':
|
||||
case 'boolean':
|
||||
case 'temporal':
|
||||
return val.toString();
|
||||
case 'string':
|
||||
return formatString(val);
|
||||
case 'date':
|
||||
if (isNaN(val.getTime()))
|
||||
throw new TypeError('cannot serialize invalid date');
|
||||
return val.toISOString();
|
||||
case 'object':
|
||||
return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
|
||||
case 'array':
|
||||
return stringifyArray(val, depth, numberAsFloat, strictTemporal);
|
||||
// @ts-expect-error -- intentional fallthrough case
|
||||
case 'temporal/tz+uc':
|
||||
if (strictTemporal) {
|
||||
let tz = val.timeZoneId;
|
||||
let tzc = tz.charCodeAt(0);
|
||||
if (
|
||||
// Classic offset
|
||||
tzc !== 0x2b /* + */ && tzc !== 0x2d /* - */ &&
|
||||
(
|
||||
// Fast pre-check pass; see below for the actually accepted values
|
||||
(tzc !== 0x55 /* U */ && tzc !== 0x47 /* G */ && tzc !== 0x5a /* Z */ && tzc !== 0x45 /* E */) ||
|
||||
(
|
||||
// UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
|
||||
tz !== 'UTC' && tz !== 'UCT' && tz !== 'Universal' && tz !== 'Zulu' &&
|
||||
// GMT is a TZ but it's for all intents and purposes equivalent to UTC. Safe to downgrade.
|
||||
!tz.startsWith('GMT') && tz !== 'Greenwich' &&
|
||||
// Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
|
||||
!tz.startsWith('Etc/')))) {
|
||||
throw new TypeError('Temporal objects with an IANA timezone are not allowed in Temporal strict mode');
|
||||
}
|
||||
}
|
||||
case 'temporal/uc':
|
||||
if (strictTemporal && val.calendarId !== 'iso8601')
|
||||
throw new TypeError('Temporal objects with a non-default calendar are not allowed in Temporal strict mode');
|
||||
return val.toString({
|
||||
calendarName: 'never',
|
||||
timeZoneName: 'never',
|
||||
});
|
||||
case 'temporal/x':
|
||||
throw new TypeError('Unsupported ' + val[Symbol.toStringTag]);
|
||||
}
|
||||
}
|
||||
function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
|
||||
let keys = Object.keys(obj);
|
||||
if (keys.length === 0)
|
||||
return '{}';
|
||||
let res = '{ ';
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let k = keys[i];
|
||||
if (i)
|
||||
res += ', ';
|
||||
res += formatKey(k) + ' = ' + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res + ' }';
|
||||
}
|
||||
function stringifyArray(array, depth, numberAsFloat, strictTemporal) {
|
||||
if (array.length === 0)
|
||||
return '[]';
|
||||
let res = '[ ';
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (i)
|
||||
res += ', ';
|
||||
if (array[i] === null || array[i] === void 0) {
|
||||
throw new TypeError('arrays cannot contain null or undefined values');
|
||||
}
|
||||
res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res + ' ]';
|
||||
}
|
||||
function stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) {
|
||||
throw new Error('Could not stringify the object: maximum object depth exceeded');
|
||||
}
|
||||
let res = '';
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
res += `${res && '\n'}[[${key}]]\n`;
|
||||
res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
|
||||
if (depth === 0) {
|
||||
throw new Error('Could not stringify the object: maximum object depth exceeded');
|
||||
}
|
||||
let preamble = '';
|
||||
let tables = '';
|
||||
let keys = Object.keys(obj);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let k = keys[i];
|
||||
if (obj[k] !== null && obj[k] !== void 0) {
|
||||
let type = extendedTypeOf(obj[k]);
|
||||
if (type === 'symbol' || type === 'function') {
|
||||
throw new TypeError(`cannot serialize values of type '${type}'`);
|
||||
}
|
||||
let key = formatKey(k);
|
||||
if (type === 'array' && isArrayOfTables(obj[k])) {
|
||||
tables += (tables && '\n') + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
else if (type === 'object') {
|
||||
let tblKey = prefix ? `${prefix}.${key}` : key;
|
||||
tables += (tables && '\n') + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
|
||||
}
|
||||
else {
|
||||
preamble += key;
|
||||
preamble += ' = ';
|
||||
preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
|
||||
preamble += '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tableKey && (preamble || !tables)) // Create table only if necessary
|
||||
preamble = preamble ? `[${tableKey}]\n${preamble}` : `[${tableKey}]`;
|
||||
return preamble && tables
|
||||
? `${preamble}\n${tables}`
|
||||
: preamble || tables;
|
||||
}
|
||||
export function stringify(obj, { maxDepth = 1000, numbersAsFloat = false, strictTemporal = false } = {}) {
|
||||
if (extendedTypeOf(obj) !== 'object') {
|
||||
throw new TypeError('stringify can only be called with an object');
|
||||
}
|
||||
let str = stringifyTable(0, obj, '', maxDepth, numbersAsFloat, strictTemporal);
|
||||
if (str[str.length - 1] !== '\n')
|
||||
return str + '\n';
|
||||
return str;
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { parseString } from './primitive.js';
|
||||
import { extractValue } from './extract.js';
|
||||
import { skipVoid } from './util.js';
|
||||
import { TomlError } from './error.js';
|
||||
/** @internal */
|
||||
export function parseKey(ctx, end = 0x3d /* = */) {
|
||||
// States:
|
||||
// 0: before first char
|
||||
// 1: parsing bare key
|
||||
// 2: after key component
|
||||
let startPtr;
|
||||
let state = 0;
|
||||
let parsed = [];
|
||||
let sliceStart;
|
||||
let c = ctx.s.charCodeAt(startPtr = ctx.p);
|
||||
do {
|
||||
// End of key
|
||||
if (c === end) {
|
||||
if (!state)
|
||||
TomlError.x('unexpected end of key', ctx);
|
||||
if (state === 1)
|
||||
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
return ctx.p++, parsed;
|
||||
}
|
||||
// Dotted key separator
|
||||
else if (c === 0x2e /* . */) {
|
||||
if (!state)
|
||||
TomlError.x('illegal empty bare key', ctx);
|
||||
if (state === 1)
|
||||
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
state = 0;
|
||||
}
|
||||
// Quoted key
|
||||
else if (!state && (c === 0x22 /* " */ || c === 0x27 /* ' */)) {
|
||||
if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
|
||||
TomlError.x('illegal quoted key: multiline strings are not allowed', ctx);
|
||||
parsed.push(parseString(ctx));
|
||||
state = 2;
|
||||
ctx.p--;
|
||||
}
|
||||
// Whitespace; no-op in state 0 and 2, end of bare key in state 1
|
||||
else if (c === 0x20 || c === 0x9 /* \t */) {
|
||||
if (state === 1) {
|
||||
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
||||
state = 2;
|
||||
}
|
||||
}
|
||||
// If state is post-key, no character is allowed; otherwise ensure it's a bare-key component
|
||||
else if (state === 2 || (c < 0x30 && c !== 0x2d /* - */) || (c > 0x39 && c < 0x41) || (c > 0x5a && c < 0x61 && c !== 0x5f /* _ */) || c > 0x7a) {
|
||||
TomlError.x('illegal character in key', ctx);
|
||||
}
|
||||
// Illegal character
|
||||
else if (!state) {
|
||||
state = 1;
|
||||
sliceStart = ctx.p;
|
||||
}
|
||||
} while (c = ctx.s.charCodeAt(++ctx.p));
|
||||
TomlError.x('incomplete key-value: cannot find end of key', ctx, startPtr);
|
||||
}
|
||||
/** @internal */
|
||||
export function parseInlineTable(ctx) {
|
||||
let startPtr = ctx.p++;
|
||||
let res = Object.create(null);
|
||||
let seen = new Set();
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p)) === 0x7d /* } */) {
|
||||
ctx.p++;
|
||||
return res;
|
||||
}
|
||||
let k;
|
||||
let t = res;
|
||||
let hasOwn = false;
|
||||
let errPtr = ctx.p;
|
||||
let key = parseKey(ctx);
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
if (i)
|
||||
t = hasOwn ? t[k] : (t[k] = Object.create(null));
|
||||
k = key[i];
|
||||
if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {
|
||||
TomlError.x('trying to redefine an already defined value', ctx, errPtr);
|
||||
}
|
||||
let unsafe = k === '__proto__';
|
||||
if (ctx.uk && (unsafe || k === 'constructor')) {
|
||||
t = ctx.uk !== 1 && TomlError.x('document contains an unsafe property', ctx, errPtr);
|
||||
break;
|
||||
}
|
||||
if (!hasOwn && unsafe) {
|
||||
Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
|
||||
}
|
||||
}
|
||||
if (hasOwn) {
|
||||
TomlError.x('trying to redefine an already defined value', ctx, errPtr);
|
||||
}
|
||||
skipVoid(ctx, true, true);
|
||||
let value = extractValue(ctx, 0x7d /* } */);
|
||||
if (t && typeof (t[k] = value) === 'object')
|
||||
seen.add(value);
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x7d /* } */) {
|
||||
return res;
|
||||
}
|
||||
if (c !== 0x2c /* , */)
|
||||
TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);
|
||||
}
|
||||
TomlError.x('unfinished table', ctx, startPtr);
|
||||
}
|
||||
/** @internal */
|
||||
export function parseArray(ctx) {
|
||||
let startPtr = ctx.p++;
|
||||
let res = [];
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p)) === 0x5d /* ] */) {
|
||||
ctx.p++;
|
||||
return res;
|
||||
}
|
||||
res.push(extractValue(ctx, 0x5d /* ] */));
|
||||
skipVoid(ctx);
|
||||
if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x5d /* ] */) {
|
||||
return res;
|
||||
}
|
||||
if (c !== 0x2c /* , */)
|
||||
TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);
|
||||
}
|
||||
TomlError.x('unfinished array', ctx, startPtr);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import type { TomlDate } from './date.js';
|
||||
type _Temporal = typeof globalThis extends {
|
||||
Temporal: infer T;
|
||||
} ? T : never;
|
||||
type AnyTemporalDateTime = InstanceType<_Temporal['Instant']> | InstanceType<_Temporal['PlainDate']> | InstanceType<_Temporal['PlainDateTime']> | InstanceType<_Temporal['PlainTime']> | InstanceType<_Temporal['ZonedDateTime']>;
|
||||
export type IntegersAsBigInt = undefined | boolean | 'asNeeded';
|
||||
export type TomlPrimitive = string | number | bigint | boolean | TomlDate | AnyTemporalDateTime;
|
||||
export type TomlTable = {
|
||||
[key: string]: TomlValue;
|
||||
};
|
||||
export type TomlValue = TomlPrimitive | TomlValue[] | TomlTable;
|
||||
export type TomlTableWithoutBigInt = {
|
||||
[key: string]: TomlValueWithoutBigInt;
|
||||
};
|
||||
export type TomlValueWithoutBigInt = Exclude<TomlPrimitive, bigint> | TomlValueWithoutBigInt[] | TomlTableWithoutBigInt;
|
||||
export {};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*!
|
||||
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
import { TomlError } from './error.js';
|
||||
/** @internal */
|
||||
export function skipComment(ctx) {
|
||||
for (; ctx.p < ctx.s.length; ctx.p++) {
|
||||
let c = ctx.s.charCodeAt(ctx.p);
|
||||
if (c === 0xa /* \n */)
|
||||
break;
|
||||
if (c === 0xd /* \r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \n */) {
|
||||
ctx.p++;
|
||||
break;
|
||||
}
|
||||
if ((c < 0x20 && c !== 0x9 /* \t */) || c === 0x7f) {
|
||||
TomlError.x('control characters are not allowed in comments', ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
export function skipVoid(ctx, banNewLines, banComments) {
|
||||
let c;
|
||||
while (ctx.p < ctx.s.length) {
|
||||
while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 0x20 ||
|
||||
c === 0x9 /* \t */ ||
|
||||
(!banNewLines &&
|
||||
(c === 0xa /* \n */ || (c === 0xd /* \r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \n */)))))
|
||||
ctx.p++;
|
||||
if (banComments || c !== 0x23 /* # */)
|
||||
break;
|
||||
skipComment(ctx);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "smol-toml",
|
||||
"version": "1.9.1",
|
||||
"description": "A small, fast, and correct TOML parser/serializer",
|
||||
"keywords": [
|
||||
"parser",
|
||||
"serializer",
|
||||
"toml"
|
||||
],
|
||||
"bugs": "https://github.com/squirrelchat/smol-toml/issues",
|
||||
"license": "BSD-3-Clause",
|
||||
"author": "Cynthia Rey <cynthia@cynthia.dev>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "github:squirrelchat/smol-toml"
|
||||
},
|
||||
"funding": "https://github.com/sponsors/cyyynthia",
|
||||
"files": [
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js",
|
||||
"require": "./dist/index.cjs"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"provenance": true
|
||||
},
|
||||
"devDependencies": {
|
||||
"@mitata/counters": "^0.0.8",
|
||||
"@tsconfig/node-lts": "^24.0.1",
|
||||
"@tsconfig/node-ts": "^23.6.4",
|
||||
"@tsconfig/strictest": "^2.0.8",
|
||||
"@types/node": "^26.6.4",
|
||||
"mitata": "^1.0.34",
|
||||
"pin-github-action": "^3.5.2",
|
||||
"rolldown": "^1.2.13",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.3.3",
|
||||
"vitest": "^5.0.3"
|
||||
},
|
||||
"devEngines": {
|
||||
"packageManager": {
|
||||
"name": "pnpm",
|
||||
"version": "12.10.1",
|
||||
"onFail": "error"
|
||||
},
|
||||
"runtime": {
|
||||
"name": "node",
|
||||
"version": "^26",
|
||||
"onFail": "warn"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest",
|
||||
"update-gha": "pin-github-action .github/workflows"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user