GithubHelp home page GithubHelp logo

inukshuk / edtf.js Goto Github PK

View Code? Open in Web Editor NEW
63.0 9.0 12.0 613 KB

Extended Date Time Format (ISO 8601-2 / EDTF) Parser for JavaScript

License: BSD 2-Clause "Simplified" License

JavaScript 93.69% Nearley 6.31%
edtf iso8601 date time javascript parser earley

edtf.js's People

Contributors

1ec5 avatar abbymullen avatar dependabot[bot] avatar earlyriser avatar fil avatar inukshuk avatar stevetweeddale avatar tarjelavik avatar workergnome avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

edtf.js's Issues

minimal node example not loading

I just tried the example code at the top with node.js, but getting this error.

import edtf, { Date, Interval } from 'edtf'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1176:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.15.0

If I add the import line to my typescript project, I get this:

npx tsc
src/reference.ts:3:38 - error TS7016: Could not find a declaration file for module 'edtf'. '/home/bruce/Code/csl-next.js/node_modules/edtf/dist/index.cjs' implicitly has an 'any' type.
  Try `npm i --save-dev @types/edtf` if it exists or add a new declaration (.d.ts) file containing `declare module 'edtf';`

3 import edtf, { Date, Interval } from 'edtf'

What am I doing wrong?

License acquisition

Greetings!

Thanks so much for your work on this. I would like to include your module in my production code at work to take EDTF values and get the min/max values for them to display approximate ages. As your code is APGL-3.0 licensed (and not MIT or Apache) I'm uncertain what the restrictions are. My goal is to include this in our bundle which gets minified and uglified. Do you have a process I can go through to acquire a license? Or recommendations on alternatives in the space that might solve the same problems?

Thanks,
Michael

-1XXX has incorrect min / max

var test = '-1XXX'
var d = edtf(test)

console.log(new Date(d.min))
// -001000-01-01T00:00:00.000Z  << expect -1999 ? 
console.log(new Date(d.max))
// -001000-12-31T23:59:59.999Z << correct ?

I think this is a bug.

Thanks for making this module, I'm using it to help create indigenous genealogy + history recording in New Zealand. Being able to record dates as humans have remembered them is a total gift ❤️

Invalid upper bound with dates before 1970-01-01

Hi!
I notice that if i try to add an interval with an unknown start it fails it the "end" is lower than 1970. Doing "../1960" works but has another meaning.

Looking at the code it seems like there is a missing check for this.lower being null?

edtf.js/src/interval.js

Lines 93 to 94 in 36f756f

if (this.lower !== Infinity && value <= this.lower)
throw new RangeError(`invalid upper bound: ${value}`)

Date.date

I'm trying to get the day-of-month value from a parsed date, but I'm getting some things I didn't expect:

edtf('2016-07-18T20:26:06+10:00').date = 19
edtf('-0876').date = 1

I sort of get the first, but I'd still prefer to have a way to get 18 out. The 2nd, I had expected undefined rather than 1.

AssertionError when calling edtf("{1978,1988}") in prod

it's ok when calling parse("{1978,1988}"), I get:

{
    "values": [
        {
            "type": "Date",
            "level": 0,
            "values": [
                1978
            ]
        },
        {
            "type": "Date",
            "level": 0,
            "values": [
                1988
            ]
        }
    ],
    "level": 2,
    "type": "List"
}

but next line, calling edtf("{1978,1988}"), I get this error:

{
    "name": "AssertionError",
    "actual": "n",
    "expected": "List",
    "operator": "==",
    "message": "'n' == 'List'",
    "generatedMessage": true,
    "stack": "AssertionError: 'n' == 'List'\n    at new n (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:630854)\n    at V (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:633514)\n    at https://editor.bdrc.io/static/js/main.f531b37e.chunk.js:1:13265\n    at set (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:79522)\n    at set (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:70876)\n    at ht (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:25475)\n    at At (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:26952)\n    at https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:27806\n    at Object.replaceState (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:43869)\n    at Nt (https://editor.bdrc.io/static/js/2.0f6ebddd.chunk.js:2:27703)"

}

this error only occurs after build, in a react app deployed in prod
not on a dev server running locally
which makes it hard to track in minified built code...

not sure how but this could be related to some trouble I had importing the edtf library
I ended up using this line to make it work:

import edtf, { parse } from "edtf/dist/../index.js" /

because I got this error:

Attempted import error: 'parse' is not exported from 'edtf'.

when using the regular one:

import edtf, { parse } from "edtf"

locale load can't be bundled anymore

This snippet

const load = (locale) =>
  JSON.parse(fs.readFileSync(new URL(`../locale-data/${locale}.json`, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)))));

can't be bundled. I can work around it by using a compile-time patch, but what is the benefit of loading this way over a require('../locale-data/en.json')?

JSON-schema validator

I'd like to prepare a PR for a JSON-schema validator, but it'd be convenient if the season-interval option could be a separate option to parse rather than the level 3 option before getting to it.

Year > 9999?

EDTF L1 (not the WD) accepts y170000002 as a valid date, how must I pass that to edtf.js? I've tried removing the leading y but that doesn't do it.

Inconsistent behavior for iterators on unspecified dates

Using EDTF.js v2.7.0, I am getting weird results with the next() iterator when applying it on unspecified years:

> edtf('201X').next().edtf // expecting "202X"... good
"202X"
> edtf('201X').prev().edtf // expecting "200X"... wrong
"201X"
> edtf('-22XX').next().edtf // expecting "-21XX"... wrong
"23XX"
> edtf('-22XX').prev().edtf // expecting "-23XX"... wrong
"22XX"

Not sure if unspecified years are supposed to be iterable, but the fact that the first test works makes me think they are.

Mismatches for XXXX-X2-<29+>

(Sorry for spamming issues, I swear I'm actually trying to work on fixes ':D)

Using v2.7.1

Since X2 sets the inner date to February by default, any value for days above 28 (29 on leap years) on an X2 month will get replaced by March 1rst or February 29th:

> edtf('2019-X2-31').edtf
"2019-X3-01"
> edtf('2020-X2-31').edtf
"2020-X2-29"

Then again, we can assume this is not a big deal since if you select X2-30 and above, you obviously meant to select December... The rest basically boils down to #20

Lists with continuations not parsing correctly

Description

According to the EDTF Specification, the string {..1984} should mean "The year 1984 and all earlier years" (See Example 9 under Set representation here.). Instead, it throws a parser error. Same with the trailing "on or after" .. indicator. Both work fine with square bracketed Set types.

Versions

edtf v3.0.1 on node v14.8.0

Expected Behavior

> edtf.parse('{..1984}')
{
  values: [ { type: 'Date', level: 0, values: [Array] } ],
  level: 2,
  type: 'List',
  earlier: true
}

Actual Behavior

> edtf.parse('{..1984}')
Uncaught Error: Syntax error at line 1 col 2:

1 {..1984}
   ^

Unexpected ".". Instead, I was expecting to see one of the following:
[... 2451 lines deleted ...]
for "{..1984}"
    at Parser.feed (/Users/mbk836/Workspace/meadow/priv/edtf/node_modules/nearley/lib/nearley.js:343:27)
    at Function.parse (/Users/mbk836/Workspace/meadow/priv/edtf/node_modules/edtf/src/parser.js:37:32) {
  offset: 1,
  token: { value: '.' }
}

February 29th on unspecified year

Using v2.7.1, here is another tricky corner case:

> edtf('21XX-02-29').edtf // expecting '21XX-02-29'
'21XX-03-01'

Since some unspecified year components can match leap years, the library should not move that date to March.

But then we should be careful! Because some other unspecified years such as "21X3" never match a leap year and should therefore behave accordingly.

But right now, the behavior is basically depending on whether the "chosen builtin date" is a leap year, which gives inconsistent results:

> edtf('24XX-02-29').edtf // expecting '24XX-02-29'... good
'24XX-02-29'
> edtf('21XX-02-29').edtf // expecting '21XX-02-29'... wrong
'21XX-03-01'

Would it be possible to check whether there is a matching leap year among the ones matching the year component, and set the Date element to the first occuring leap year?

Year zero not treated as a leap year

Using v2.7.1.

Creating another issue for this, since it happens regardless of the "unspecified" value (currently scratching my head over it by the way):

> edtf('0000-02-29').edtf // expecting '0000-02-29'... wrong
'0000-03-01'
> edtf('0000-02-28').next().edtf // expecting '0000-02-29'... wrong
'0000-03-01'
> edtf('0000-03-01').prev().edtf // expecting '0000-02-29'... wrong
'0000-02-28'

global is not defined

My apologies, but I cannot tell if this is a problem with the configuration of my React application or the packaging of edtf.js.

Using version 4.1.0 and 4.0.0, I get when running the application in a browser:

Uncaught ReferenceError: global is not defined
    js date.js:17

However, with 3.1.0 no error is received and edtf.js works as expected.

The webpack config is:

// Copyright 2019 Stanford University see LICENSE for license

/* eslint node/no-unpublished-require: ["off"] */
const path = require("path")
const webpack = require("webpack")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
  entry: "./src/index.js",
  module: {
    noParse: /bad_json/,
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve(__dirname, "./src"),
        exclude: /node_modules/,
        use: ["babel-loader"],
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(scss)$/,
        use: [
          {
            // inject CSS to page
            loader: "style-loader",
          },
          {
            // translates CSS into CommonJS modules
            loader: "css-loader",
          },
          {
            // Run postcss actions
            loader: "postcss-loader",
            options: {
              // `postcssOptions` is needed for postcss 8.x;
              // if you use postcss 7.x skip the key
              postcssOptions: {
                // postcss plugins, can be exported to postcss.config.js
                plugins() {
                  return [require("autoprefixer")]
                },
              },
            },
          },
          {
            // compiles Sass to CSS
            loader: "sass-loader",
          },
        ],
      },
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        // More information here https://webpack.js.org/guides/asset-modules/
        type: "asset",
      },
    ],
  },
  resolve: {
    extensions: ["*", ".js", ".jsx"],
    fallback: {
      fs: false,
      stream: require.resolve("stream-browserify"),
      crypto: require.resolve("crypto-browserify"),
    },
  },
  output: {
    path: path.join(__dirname, "/dist"),
    publicPath: "/dist/",
    filename: "bundle.js",
  },
  plugins: [
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
      process: "process/browser",
    }),
    new HtmlWebpackPlugin({
      template: "index.html",
      filename: "index.html",
      hash: true,
    }),
    new webpack.EnvironmentPlugin({
      USE_FIXTURES: null,
      SINOPIA_API_BASE_URL: null,
      SINOPIA_GROUP: null,
      SINOPIA_ENV: null,
      SINOPIA_URI: null,
      AWS_COGNITO_DOMAIN: null,
      COGNITO_CLIENT_ID: null,
      COGNITO_USER_POOL_ID: null,
      INDEX_URL: null,
      SEARCH_HOST: null,
      EXPORT_BUCKET_URL: null,
      HONEYBADGER_API_KEY: null,
      HONEYBADGER_REVISION: null,
    }),
  ],
  devtool: "source-map",
  devServer: {
    static: "./dist",
    historyApiFallback: true,
    hot: true,
    port: 8888,
    proxy: {
      "/api/search": "http://localhost:8000",
    },
  },
}

Thanks in advance for your assistance.

Add variants to .between() and .until()

[...edtf('2016-05').between('2016-07')]
#-> [2016-06]

[...edtf('2016-05').until('2016-07')]
#-> [2016-05, 2016-06, 2016-07]

.between() and .until() return a closed/exclusive and and open/inclusive interval, respectively. Maybe it would be useful to add two methods that return a half-open interval:

#-> [2016-05, 2016-06]

#-> [2016-06, 2016-07]

Obvious possible additions in English are .from(), .since(), .through(), .till(),.unto(), .to(), .by(), unless a name is already used or reserved. As a non-native speaker, I’ll refrain from suggesting exact semantics for these.

While .between() should work no matter the temporal order of EDTFs, .until() should arguably not.

[...edtf('2016-07').between('2016-06')]
#-> [2016-06]

[...edtf('2016-07').until('2016-05')]
#-> null

Provide transpiled version/variant for Node < 4.6

Hey,
this is not really a bug, but likely an issue that others may run into: The nodejs version that is shipping with the latest ubuntu (4.2.6) does not seem to include harmony flags to cover all the features you are using. So one really needs to transpile in order to use your package when using it on a standard server with one of the Ubuntu LTS releases. Or do you have any other information?

Usage in closed-source commercial product

We're developing an application that is only accessible to our customers. We are in need of a EDTF implementation in javascript, and found this repository which matches our needs exactly. We've also looked at edtfy but that misses some functioanlity we need.

Our code is closed-source, which due to the AGPL3 license of this repository means that we are unable to use it.

Would it be possible to discuss some specific alternate license that allows commercial use without having to open everything under AGPL3?

unknown/open

I'm getting errors parsing these dates:

  • */2006
  • 2004-06-01/*
  • 2004-01-01/

Max property of masked dates incorrect

As far as I understand it, the maximum possible extent of 20XX would be the last second of the year 2099. However it's parse as if it has year precision, so next() gives the year 2001, and .max gives you the year 2001 - 1 millisecond.

> new Date(edtf('20XX').max)
2000-12-31T23:59:59.999Z
> new Date(edtf('20XX').min)
2000-01-01T00:00:00.000Z

Looking at the code, I think this would need a bit of a refactor, with the introduction of a secondary notion of precision. Whereas currently it just knows "how many date parts we have provided" it would need to know which the most precise digit before any unknown ones is. So in this case, 20XX feels like it ought to be treated as a century instead of a year, whilst 201X would be a decade.

allowing uaSymbol on undefined dates

First, thanks for this very useful library!

Currently the code allows 18? to represent "19th century, uncertain", but not 18XX?, as exemplified in this sandbox. I can't really see 18XX? allowed or forbidden in part2 of the draft, but neither can I see 18? forbidden or allowed (even in the grammar at the end)... is there a reason one works and not the other?

Day not considered unspecified in month-precision Level 0 date

Hi, I’m unsure whether this is expected behaviour, but I noticed that constructing a month-precision date by omitting the day part yields a different result compared to a day-precision date when filling the day part with XX:

> const edtf = require('edtf')
> edtf.default('1963-12').unspecified.is('day')
0
> edtf.default('1963-12-XX').unspecified.is('day')
192

I would expect the method to tell me that the day is unspecified in the first case, too.
If this is working correctly, what is the intended way of determining that there is no day part?

import into ES6 project unclear

Hey,
this edtf module is somehow differently exported than all other packages on npmjs, and I don't quite get why. it says it's written in ES6, but from what I can tell, it's really using commonjs module imports. I expected to be able to do imports like this in ES6:

import {parse} from 'edtf'

That is working will all other packages, except this one. Is there some other ways to import it in ES6?

Parse error on trailing zeros

Hi there,

Thanks for this great library!
I was trying to parse 2020-05-18T22:39:24.422000Z, but it throws an error because it doesn't expect the trailing zeros. However, I think this should be valid? at least for new Date() it is.

Cheers,

Miel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.