@opentripplanner/core-utils 4.11.5 → 5.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/esm/deprecated-with-types.js +47 -0
  2. package/esm/deprecated-with-types.js.map +1 -0
  3. package/esm/deprecated.js +7 -0
  4. package/esm/deprecated.js.map +1 -1
  5. package/esm/index.js +0 -4
  6. package/esm/index.js.map +1 -1
  7. package/esm/itinerary.js +3 -9
  8. package/esm/itinerary.js.map +1 -1
  9. package/esm/map.js +9 -2
  10. package/esm/map.js.map +1 -1
  11. package/esm/route.js +5 -3
  12. package/esm/route.js.map +1 -1
  13. package/esm/storage.js +1 -0
  14. package/esm/storage.js.map +1 -1
  15. package/esm/time.js +6 -36
  16. package/esm/time.js.map +1 -1
  17. package/esm/ui.js +1 -1
  18. package/esm/ui.js.map +1 -1
  19. package/lib/deprecated-with-types.d.ts +23 -0
  20. package/lib/deprecated-with-types.d.ts.map +1 -0
  21. package/lib/deprecated-with-types.js +61 -0
  22. package/lib/deprecated-with-types.js.map +1 -0
  23. package/lib/deprecated.js +9 -0
  24. package/lib/deprecated.js.map +1 -1
  25. package/lib/index.d.ts +19 -0
  26. package/lib/index.d.ts.map +1 -0
  27. package/lib/index.js +0 -6
  28. package/lib/index.js.map +1 -1
  29. package/lib/itinerary.d.ts +113 -0
  30. package/lib/itinerary.d.ts.map +1 -0
  31. package/lib/itinerary.js +8 -9
  32. package/lib/itinerary.js.map +1 -1
  33. package/lib/map.d.ts +30 -0
  34. package/lib/map.d.ts.map +1 -0
  35. package/lib/map.js +8 -1
  36. package/lib/map.js.map +1 -1
  37. package/lib/route.d.ts +98 -0
  38. package/lib/route.d.ts.map +1 -0
  39. package/lib/route.js +5 -3
  40. package/lib/route.js.map +1 -1
  41. package/lib/storage.d.ts +19 -0
  42. package/lib/storage.d.ts.map +1 -0
  43. package/lib/storage.js +2 -0
  44. package/lib/storage.js.map +1 -1
  45. package/lib/time.d.ts +65 -0
  46. package/lib/time.d.ts.map +1 -0
  47. package/lib/time.js +22 -39
  48. package/lib/time.js.map +1 -1
  49. package/lib/ui.d.ts +13 -0
  50. package/lib/ui.d.ts.map +1 -0
  51. package/lib/ui.js +1 -1
  52. package/lib/ui.js.map +1 -1
  53. package/package.json +4 -1
  54. package/src/__tests__/__snapshots__/route.js.snap +30 -30
  55. package/src/deprecated-with-types.ts +62 -0
  56. package/src/deprecated.js +16 -0
  57. package/src/{index.js → index.ts} +0 -4
  58. package/src/{itinerary.js → itinerary.ts} +72 -50
  59. package/src/{map.js → map.ts} +48 -21
  60. package/src/{route.js → route.ts} +52 -28
  61. package/src/{storage.js → storage.ts} +6 -5
  62. package/src/{time.js → time.ts} +28 -46
  63. package/src/{ui.js → ui.ts} +8 -8
  64. package/tsconfig.json +15 -0
  65. package/tsconfig.tsbuildinfo +4921 -0
  66. package/esm/messages.js +0 -25
  67. package/esm/messages.js.map +0 -1
  68. package/esm/types.js +0 -560
  69. package/esm/types.js.map +0 -1
  70. package/lib/messages.js +0 -29
  71. package/lib/messages.js.map +0 -1
  72. package/lib/types.js +0 -661
  73. package/lib/types.js.map +0 -1
  74. package/src/messages.js +0 -20
  75. package/src/types.js +0 -605
package/esm/route.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/route.js"],"names":["getTransitOperatorFromFeedIdAndAgencyId","feedId","agencyId","transitOperators","find","transitOperator","getTransitOperatorFromLeg","leg","routeId","split","getTransitOperatorFromOtpRoute","route","id","agency","END_OF_LIST_COMPARATOR_VALUE","getTransitOperatorComparatorValue","length","name","agencyName","order","makeTransitOperatorComparator","a","b","aVal","bVal","getSortValues","getterFn","modeComparatorValue","SUBWAY","TRAM","RAIL","GONDOLA","FERRY","CABLE_CAR","FUNICULAR","BUS","routeTypeComparatorValue","getRouteTypeComparatorValue","Error","mode","type","console","warn","routeTypeComparator","startsWithAlphabeticCharacter","val","firstCharCode","charCodeAt","alphabeticShortNameComparator","aStartsWithAlphabeticCharacter","shortName","bStartsWithAlphabeticCharacter","makeNumericValueComparator","objGetterFn","isNaN","makeStringValueComparator","getRouteSortOrderValue","undefined","makeMultiCriteriaSort","criteria","i","curCriteriaComparatorValue","makeRouteComparator","obj","sortOrder","parseInt","longName"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,uCAAT,CACLC,MADK,EAELC,QAFK,EAGLC,gBAHK,EAIL;AACA,SACEA,gBAAgB,CAACC,IAAjB,CACE,UAAAC,eAAe;AAAA,WACbA,eAAe,CAACJ,MAAhB,KAA2BA,MAA3B,IACAI,eAAe,CAACH,QAAhB,KAA6BA,QAFhB;AAAA,GADjB,KAIK,IALP;AAOD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASI,yBAAT,CAAmCC,GAAnC,EAAwCJ,gBAAxC,EAA0D;AAC/D,MAAI,CAACI,GAAG,CAACC,OAAL,IAAgB,CAACD,GAAG,CAACL,QAAzB,EAAmC,OAAO,IAAP;AACnC,MAAMD,MAAM,GAAGM,GAAG,CAACC,OAAJ,CAAYC,KAAZ,CAAkB,GAAlB,EAAuB,CAAvB,CAAf;AACA,SAAOT,uCAAuC,CAC5CC,MAD4C,EAE5CM,GAAG,CAACL,QAFwC,EAG5CC,gBAH4C,CAA9C;AAKD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASO,8BAAT,CAAwCC,KAAxC,EAA+CR,gBAA/C,EAAiE;AACtE,MAAI,CAACQ,KAAK,CAACC,EAAX,EAAe,OAAO,IAAP;AACf,MAAMX,MAAM,GAAGU,KAAK,CAACC,EAAN,CAASH,KAAT,CAAe,GAAf,EAAoB,CAApB,CAAf;AACA,MAAIP,QAAJ;;AACA,MAAIS,KAAK,CAACE,MAAV,EAAkB;AAChB;AACAX,IAAAA,QAAQ,GAAGS,KAAK,CAACE,MAAN,CAAaD,E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;AACpC,eAAOA,0BAAP;AACD;AACF;;AACD,WAAO,CAAP;AACD,GAVD;AAWD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,OAAO,SAASC,mBAAT,CAA6B3D,gBAA7B,EAA+C;AACpD,SAAOuD,qBAAqB,CAC1BtC,6BAA6B,CAACjB,gBAAD,CADH,EAE1BiD,0BAA0B,CAAC,UAAAW,GAAG;AAAA,WAAIP,sBAAsB,CAACO,GAAG,CAACC,SAAL,CAA1B;AAAA,GAAJ,CAFA,EAG1BrB,mBAH0B,EAI1BK,6BAJ0B,EAK1BI,0BAA0B,CAAC,UAAAW,GAAG;AAAA,WAAIE,QAAQ,CAACF,GAAG,CAACb,SAAL,EAAgB,EAAhB,CAAZ;AAAA,GAAJ,CALA,EAM1BK,yBAAyB,CAAC,UAAAQ,GAAG;AAAA,WAAIA,GAAG,CAACb,SAAR;AAAA,GAAJ,CANC,EAO1BK,yBAAyB,CAAC,UAAAQ,GAAG;AAAA,WAAIA,GAAG,CAACG,QAAR;AAAA,GAAJ,CAPC,CAA5B;AASD","sourcesContent":["/**\n * Returns the transit operator (if an exact match is found) from the transit\n * operators config value. It is critical to use both the feedId and agencyId in\n * this method because it is possible in OTP for there to be a duplicate\n * agencyId in separate feeds.\n *\n * @param {string} feedId The feedId that this transit agency belongs to\n * @param {string} agencyId The agencyId of the transit agency\n * @param {array} transitOperators The transitOperators list from the config\n * @return {object} The transitOperator if a match was found or null if no match\n * was found\n */\nexport function getTransitOperatorFromFeedIdAndAgencyId(\n feedId,\n agencyId,\n transitOperators\n) {\n return (\n transitOperators.find(\n transitOperator =>\n transitOperator.feedId === feedId &&\n transitOperator.agencyId === agencyId\n ) || null\n );\n}\n\n/**\n * Looks up an operator from the provided leg.\n *\n * @param {object} leg The Itinerary Leg from which to find the transit\n * operator\n * @param {object} transitOperators transitOperators from config.\n * @return {object} the operator if one was found or null if no match was found\n */\nexport function getTransitOperatorFromLeg(leg, transitOperators) {\n if (!leg.routeId || !leg.agencyId) return null;\n const feedId = leg.routeId.split(\":\")[0];\n return getTransitOperatorFromFeedIdAndAgencyId(\n feedId,\n leg.agencyId,\n transitOperators\n );\n}\n\n/**\n * Looks up an operator from the provided configuration given an OTP route.\n * NOTE: this assumes the use of the OTP Route model or a modified OTP\n * RouteShort model (such as the one found in the IBI fork of OTP) that also\n * returns the agencyId.\n *\n * @param {object} route Either an OTP Route or RouteShort model\n * @param {array} transitOperators transitOperators from config\n * @return {object} the operator if one was found or null if no match was found\n */\nexport function getTransitOperatorFromOtpRoute(route, transitOperators) {\n if (!route.id) return null;\n const feedId = route.id.split(\":\")[0];\n let agencyId;\n if (route.agency) {\n // This is returned in the OTP Route model\n agencyId = route.agency.id;\n } else if (route.agencyId) {\n // This is returned in the OTP RouteShort model (such as in the IBI fork)\n agencyId = route.agencyId;\n } else {\n return null;\n }\n return getTransitOperatorFromFeedIdAndAgencyId(\n feedId,\n agencyId,\n transitOperators\n );\n}\n\n// The functions below are for enhanced route sorting functions for the route\n// viewer on OTP-react-redux.\n// They address route ordering issues discussed in\n// https://github.com/opentripplanner/otp-react-redux/pull/123 and\n// https://github.com/opentripplanner/otp-react-redux/pull/124.\n\n/**\n * A large comparator value that can safely be used in mathematical sort\n * comparisons to place things at the end of lists\n */\nconst END_OF_LIST_COMPARATOR_VALUE = 999999999999;\n\n/**\n * Returns a transit operator comparator value given a route and an optional\n * transitOperators config value. This function will do its best to handle all\n * kinds of input data as certain deployments of an implementing webapp may have\n * incomplete data and certain versions of OTP might not have a modified\n * implementation of the RouteShort model.\n *\n * @param {object} route Either an OTP Route or RouteShort model\n * @param {array} transitOperators transitOperators from config\n * @return {mixed} this could return a string value (the route's agency name) if\n * the transitOperators value is not defined. Otherwise an integer will be\n * returned.\n */\nfunction getTransitOperatorComparatorValue(route, transitOperators) {\n // if the transitOperators is undefined or has zero length, use the route's\n // agency name as the comparator value\n if (!transitOperators || transitOperators.length === 0) {\n // OTP Route\n if (route.agency) return route.agency.name;\n // OTP RouteShort (base OTP repo or IBI fork)\n if (route.agencyName) return route.agencyName;\n // shouldn't happen as agency names will be defined\n return \"zzz\";\n }\n\n // find operator associated with route\n const transitOperator = getTransitOperatorFromOtpRoute(\n route,\n transitOperators\n );\n\n // if transit operator not found, return infinity\n if (!transitOperator) return END_OF_LIST_COMPARATOR_VALUE;\n\n // return the transit operator's sort value or END_OF_LIST_COMPARATOR_VALUE if\n // the sort value is not a number\n return typeof transitOperator.order === \"number\"\n ? transitOperator.order\n : END_OF_LIST_COMPARATOR_VALUE;\n}\n\n/**\n * Calculates the sort comparator value given two routes based off of the\n * route's agency and provided transitOperators config data.\n */\nfunction makeTransitOperatorComparator(transitOperators) {\n return (a, b) => {\n const aVal = getTransitOperatorComparatorValue(a, transitOperators);\n const bVal = getTransitOperatorComparatorValue(b, transitOperators);\n if (typeof aVal === \"string\") {\n // happens when transitOperators is undefined. Both aVal are guaranteed to\n // be strings. Make a string comparison.\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n }\n\n // transitOperators are defined and therefore a numeric value is guaranteed\n // to be returned\n return aVal - bVal;\n };\n}\n\n/**\n * Gets the desired sort values according to an optional getter function. If the\n * getter function is not defined, the original sort values are returned.\n */\nfunction getSortValues(getterFn, a, b) {\n let aVal;\n let bVal;\n if (typeof getterFn === \"function\") {\n aVal = getterFn(a);\n bVal = getterFn(b);\n } else {\n aVal = a;\n bVal = b;\n }\n return { aVal, bVal };\n}\n\n// Lookup for the sort values associated with various OTP modes.\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// https://github.com/documentationjs/documentation/issues/372\nconst modeComparatorValue = {\n SUBWAY: 1,\n TRAM: 2,\n RAIL: 3,\n GONDOLA: 4,\n FERRY: 5,\n CABLE_CAR: 6,\n FUNICULAR: 7,\n BUS: 8\n};\n\n// Lookup that maps route types to the OTP mode sort values.\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// https://github.com/documentationjs/documentation/issues/372\nconst routeTypeComparatorValue = {\n 0: modeComparatorValue.TRAM, // - Tram, Streetcar, Light rail.\n 1: modeComparatorValue.SUBWAY, // - Subway, Metro.\n 2: modeComparatorValue.RAIL, // - Rail. Used for intercity or long-distance travel.\n 3: modeComparatorValue.BUS, // - Bus.\n 4: modeComparatorValue.FERRY, // - Ferry.\n 5: modeComparatorValue.CABLE_CAR, // - Cable tram.\n 6: modeComparatorValue.GONDOLA, // - Gondola, etc.\n 7: modeComparatorValue.FUNICULAR, // - Funicular.\n // TODO: 11 and 12 are not a part of OTP as of 2019-02-14, but for now just\n // associate them with bus/rail.\n 11: modeComparatorValue.BUS, // - Trolleybus.\n 12: modeComparatorValue.RAIL // - Monorail.\n};\n\n// Gets a comparator value for a given route's type (OTP mode).\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// ttps://github.com/documentationjs/documentation/issues/372\nfunction getRouteTypeComparatorValue(route) {\n // For some strange reason, the short route response in OTP returns the\n // string-based modes, but the long route response returns the\n // integer route type. This attempts to account for both of those cases.\n if (!route) throw new Error(\"Route is undefined.\", route);\n if (typeof modeComparatorValue[route.mode] !== \"undefined\") {\n return modeComparatorValue[route.mode];\n }\n if (typeof routeTypeComparatorValue[route.type] !== \"undefined\") {\n return routeTypeComparatorValue[route.type];\n }\n // Default the comparator value to a large number (placing the route at the\n // end of the list).\n console.warn(\"no mode/route type found for route\", route);\n return END_OF_LIST_COMPARATOR_VALUE;\n}\n\n/**\n * Calculates the sort comparator value given two routes based off of route type\n * (OTP mode).\n */\nfunction routeTypeComparator(a, b) {\n return getRouteTypeComparatorValue(a) - getRouteTypeComparatorValue(b);\n}\n\n/**\n * Determines whether a value is a string that starts with an alphabetic\n * ascii character.\n */\nfunction startsWithAlphabeticCharacter(val) {\n if (typeof val === \"string\" && val.length > 0) {\n const firstCharCode = val.charCodeAt(0);\n return (\n (firstCharCode >= 65 && firstCharCode <= 90) ||\n (firstCharCode >= 97 && firstCharCode <= 122)\n );\n }\n return false;\n}\n\n/**\n * Sorts routes based off of whether the shortName begins with an alphabetic\n * character. Routes with shortn that do start with an alphabetic character will\n * be prioritized over those that don't.\n */\nfunction alphabeticShortNameComparator(a, b) {\n const aStartsWithAlphabeticCharacter = startsWithAlphabeticCharacter(\n a.shortName\n );\n const bStartsWithAlphabeticCharacter = startsWithAlphabeticCharacter(\n b.shortName\n );\n\n if (aStartsWithAlphabeticCharacter && bStartsWithAlphabeticCharacter) {\n // both start with an alphabetic character, return equivalence\n return 0;\n }\n // a does start with an alphabetic character, but b does not. Prioritize a\n if (aStartsWithAlphabeticCharacter) return -1;\n // b does start with an alphabetic character, but a does not. Prioritize b\n if (bStartsWithAlphabeticCharacter) return 1;\n // neither route has a shortName that starts with an alphabetic character.\n // Return equivalence\n return 0;\n}\n\n/**\n * Checks whether an appropriate comparison of numeric values can be made for\n * sorting purposes. If both values are not valid numbers according to the\n * isNaN check, then this function returns undefined which indicates that a\n * secondary sorting criteria should be used instead. If one value is valid and\n * the other is not, then the valid value will be given sorting priority. If\n * both values are valid numbers, the difference is obtained as the sort value.\n *\n * An optional argument can be provided which will be used to obtain the\n * comparison value from the comparison function arguments.\n *\n * IMPORTANT: the comparison values must be numeric values or at least be\n * attempted to be converted to numeric values! If one of the arguments is\n * something crazy like an empty string, unexpected behavior will occur because\n * JavaScript.\n *\n * @param {function} [objGetterFn] An optional function to obtain the\n * comparison value from the comparator function arguments\n */\nexport function makeNumericValueComparator(objGetterFn) {\n /* Note: Using the global version of isNaN (the Number version behaves differently. */\n /* eslint-disable no-restricted-globals */\n return (a, b) => {\n const { aVal, bVal } = getSortValues(objGetterFn, a, b);\n // if both values aren't valid numbers, use the next sort criteria\n if (isNaN(aVal) && isNaN(bVal)) return 0;\n // b is a valid number, b gets priority\n if (isNaN(aVal)) return 1;\n // a is a valid number, a gets priority\n if (isNaN(bVal)) return -1;\n // a and b are valid numbers, return the sort value\n return aVal - bVal;\n };\n}\n\n/**\n * Create a comparator function that compares string values. The comparison\n * values feed to the sort comparator function are assumed to be objects that\n * will have either undefined, null or string values at the given key. If one\n * object has undefined, null or an empty string, but the other does have a\n * string with length > 0, then that string will get priority.\n *\n * @param {function} [objGetterFn] An optional function to obtain the\n * comparison value from the comparator function arguments\n */\nexport function makeStringValueComparator(objGetterFn) {\n return (a, b) => {\n const { aVal, bVal } = getSortValues(objGetterFn, a, b);\n // both a and b are uncomparable strings, return equivalent value\n if (!aVal && !bVal) return 0;\n // a is not a comparable string, b gets priority\n if (!aVal) return 1;\n // b is not a comparable string, a gets priority\n if (!bVal) return -1;\n // a and b are comparable strings, return the sort value\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n };\n}\n\n/**\n * OpenTripPlanner sets the routeSortOrder to -999 by default. So, if that value\n * is encountered, assume that it actually means that the routeSortOrder is not\n * set in the GTFS.\n *\n * See https://github.com/opentripplanner/OpenTripPlanner/issues/2938\n * Also see https://github.com/opentripplanner/otp-react-redux/issues/122\n */\nfunction getRouteSortOrderValue(val) {\n return val === -999 ? undefined : val;\n}\n\n/**\n * Create a multi-criteria sort comparator function composed of other sort\n * comparator functions. Each comparator function will be ran in the order given\n * until a non-zero comparison value is obtained which is then immediately\n * returned. If all comparison functions return equivalence, then the values\n * are assumed to be equivalent.\n */\nfunction makeMultiCriteriaSort(...criteria) {\n return (a, b) => {\n for (let i = 0; i < criteria.length; i++) {\n const curCriteriaComparatorValue = criteria[i](a, b);\n // if the comparison objects are not equivalent, return the value obtained\n // in this current criteria comparison\n if (curCriteriaComparatorValue !== 0) {\n return curCriteriaComparatorValue;\n }\n }\n return 0;\n };\n}\n\n/**\n * Creates a sort comparator function to compares routes for the purposes of\n * sorting and displaying in a user interface. This takes in a single optional\n * argument which should be a list of transitOperators as defined in the config\n * file. Due to GTFS feeds having varying levels of data quality, a multi-\n * criteria sort is needed to account for various differences. The criteria\n * included here are each applied to the routes in the order listed. If a given\n * sort criterion yields equivalence (e.g., two routes have the short name\n * \"20\"), the comparator falls back onto the next sort criterion (e.g., long\n * name). The sort operates on the following values (in order):\n *\n * 1. Transit Operator. The transit operator will be attempted to be obtained\n * for each route. If no argument is provided when creating this comparator\n * function, then routes will be sorted by their agency's name. If an\n * argument is provided and a match is found based off of the route's feed_id\n * and agency_id and a transitOperator's feed_id and agency_id, then the\n * field transitOperator.order will be used as the comparator value as long\n * as it is numeric. If it is not numeric, a value is returned indicating\n * that this transit operator should be placed at the end of the list.\n * 2. sortOrder. Routes that do not have a valid sortOrder will be placed\n * beneath those that do.\n * 3. route type (OTP mode). See routeTypeComparator code for prioritization of\n * route types.\n * 4. shortNames that begin with alphabetic characters. shortNames that do not\n * start with alphabetic characters will be place beneath those that do.\n * 5. shortName as integer. shortNames that cannot be parsed as integers will\n * be placed beneath those that are valid.\n * 6. shortName as string. Routes without shortNames will be placed beneath\n * those with shortNames.\n * 7. longName as string.\n */\nexport function makeRouteComparator(transitOperators) {\n return makeMultiCriteriaSort(\n makeTransitOperatorComparator(transitOperators),\n makeNumericValueComparator(obj => getRouteSortOrderValue(obj.sortOrder)),\n routeTypeComparator,\n alphabeticShortNameComparator,\n makeNumericValueComparator(obj => parseInt(obj.shortName, 10)),\n makeStringValueComparator(obj => obj.shortName),\n makeStringValueComparator(obj => obj.longName)\n );\n}\n"],"file":"route.js"}
1
+ {"version":3,"sources":["../src/route.ts"],"names":["getTransitOperatorFromFeedIdAndAgencyId","feedId","agencyId","transitOperators","find","transitOperator","getTransitOperatorFromLeg","leg","routeId","split","getTransitOperatorFromOtpRoute","route","id","agency","END_OF_LIST_COMPARATOR_VALUE","getTransitOperatorComparatorValue","length","name","agencyName","order","makeTransitOperatorComparator","a","b","aVal","bVal","getSortValues","getterFn","modeComparatorValue","SUBWAY","TRAM","RAIL","GONDOLA","FERRY","CABLE_CAR","FUNICULAR","BUS","routeTypeComparatorValue","getRouteTypeComparatorValue","Error","mode","type","console","warn","routeTypeComparator","startsWithAlphabeticCharacter","val","firstCharCode","charCodeAt","alphabeticShortNameComparator","aStartsWithAlphabeticCharacter","shortName","bStartsWithAlphabeticCharacter","makeNumericValueComparator","objGetterFn","isNaN","makeStringValueComparator","getRouteSortOrderValue","undefined","makeMultiCriteriaSort","criteria","i","curCriteriaComparatorValue","makeRouteComparator","obj","sortOrder","parseInt","longName"],"mappings":"AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,uCAAT,CACLC,MADK,EAELC,QAFK,EAGLC,gBAHK,EAIY;AACjB,SACEA,gBAAgB,CAACC,IAAjB,CACE,UAAAC,eAAe;AAAA,WACbA,eAAe,CAACJ,MAAhB,KAA2BA,MAA3B,IACAI,eAAe,CAACH,QAAhB,KAA6BA,QAFhB;AAAA,GADjB,KAIK,IALP;AAOD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASI,yBAAT,CACLC,GADK,EAELJ,gBAFK,EAGY;AACjB,MAAI,CAACI,GAAG,CAACC,OAAL,IAAgB,CAACD,GAAG,CAACL,QAAzB,EAAmC,OAAO,IAAP;AACnC,MAAMD,MAAM,GAAGM,GAAG,CAACC,OAAJ,CAAYC,KAAZ,CAAkB,GAAlB,EAAuB,CAAvB,CAAf;AACA,SAAOT,uCAAuC,CAC5CC,MAD4C,EAE5CM,GAAG,CAACL,QAFwC,EAG5CC,gBAH4C,CAA9C;AAKD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASO,8BAAT,CACLC,KADK,EAELR,gBAFK,EAGY;AACjB,MAAI,CAACQ,KAAK,CAACC,EAAX,EAAe,OAAO,IAAP;AACf,MAAMX,MAAM,GAAGU,KAAK,CAACC,EAAN,CAASH,KAAT,CAAe,GAAf,EAAoB,CAApB,CAAf;AACA,MAAIP,QAAJ;;AACA,MAAIS,KAAK,CAACE,MAAV,EAAkB;AAChB;AACAX,IAAAA,QAAQ,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ACC,CAAD,CAAR,CAAYvC,CAAZ,EAAeC,CAAf,CAAnC,CADwC,CAExC;AACA;;AACA,UAAIuC,0BAA0B,KAAK,CAAnC,EAAsC;AACpC,eAAOA,0BAAP;AACD;AACF;;AACD,WAAO,CAAP;AACD,GAVD;AAWD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,OAAO,SAASC,mBAAT,CACL3D,gBADK,EAE6B;AAClC,SAAOuD,qBAAqB,CAC1BtC,6BAA6B,CAACjB,gBAAD,CADH,EAE1BiD,0BAA0B,CAAC,UAAAW,GAAG;AAAA,WAAIP,sBAAsB,CAACO,GAAG,CAACC,SAAL,CAA1B;AAAA,GAAJ,CAFA,EAG1BrB,mBAH0B,EAI1BK,6BAJ0B,EAK1BI,0BAA0B,CAAC,UAAAW,GAAG;AAAA,WAAIE,QAAQ,CAACF,GAAG,CAACb,SAAL,EAAgB,EAAhB,CAAZ;AAAA,GAAJ,CALA,EAM1BK,yBAAyB,CAAC,UAAAQ,GAAG;AAAA,WAAIA,GAAG,CAACb,SAAR;AAAA,GAAJ,CANC,EAO1BK,yBAAyB,CAAC,UAAAQ,GAAG;AAAA,WAAIA,GAAG,CAACG,QAAR;AAAA,GAAJ,CAPC,CAA5B;AASD","sourcesContent":["import { Leg, Route, TransitOperator } from \"@opentripplanner/types\";\n/**\n * Returns the transit operator (if an exact match is found) from the transit\n * operators config value. It is critical to use both the feedId and agencyId in\n * this method because it is possible in OTP for there to be a duplicate\n * agencyId in separate feeds.\n *\n * @param {string} feedId The feedId that this transit agency belongs to\n * @param {string} agencyId The agencyId of the transit agency\n * @param {array} transitOperators The transitOperators list from the config\n * @return {object} The transitOperator if a match was found or null if no match\n * was found\n */\nexport function getTransitOperatorFromFeedIdAndAgencyId(\n feedId: string,\n agencyId: string | number,\n transitOperators: TransitOperator[]\n): TransitOperator {\n return (\n transitOperators.find(\n transitOperator =>\n transitOperator.feedId === feedId &&\n transitOperator.agencyId === agencyId\n ) || null\n );\n}\n\n/**\n * Looks up an operator from the provided leg.\n *\n * @param {object} leg The Itinerary Leg from which to find the transit\n * operator\n * @param {object} transitOperators transitOperators from config.\n * @return {object} the operator if one was found or null if no match was found\n */\nexport function getTransitOperatorFromLeg(\n leg: Leg,\n transitOperators: TransitOperator[]\n): TransitOperator {\n if (!leg.routeId || !leg.agencyId) return null;\n const feedId = leg.routeId.split(\":\")[0];\n return getTransitOperatorFromFeedIdAndAgencyId(\n feedId,\n leg.agencyId,\n transitOperators\n );\n}\n\n/**\n * Looks up an operator from the provided configuration given an OTP route.\n * NOTE: this assumes the use of the OTP Route model or a modified OTP\n * RouteShort model (such as the one found in the IBI fork of OTP) that also\n * returns the agencyId.\n *\n * @param {object} route Either an OTP Route or RouteShort model\n * @param {array} transitOperators transitOperators from config\n * @return {object} the operator if one was found or null if no match was found\n */\nexport function getTransitOperatorFromOtpRoute(\n route: Route,\n transitOperators: TransitOperator[]\n): TransitOperator {\n if (!route.id) return null;\n const feedId = route.id.split(\":\")[0];\n let agencyId: string | number;\n if (route.agency) {\n // This is returned in the OTP Route model\n agencyId = route.agency.id;\n } else if (route.agencyId) {\n // This is returned in the OTP RouteShort model (such as in the IBI fork)\n agencyId = route.agencyId;\n } else {\n return null;\n }\n return getTransitOperatorFromFeedIdAndAgencyId(\n feedId,\n agencyId,\n transitOperators\n );\n}\n\n// The functions below are for enhanced route sorting functions for the route\n// viewer on OTP-react-redux.\n// They address route ordering issues discussed in\n// https://github.com/opentripplanner/otp-react-redux/pull/123 and\n// https://github.com/opentripplanner/otp-react-redux/pull/124.\n\n/**\n * A large comparator value that can safely be used in mathematical sort\n * comparisons to place things at the end of lists\n */\nconst END_OF_LIST_COMPARATOR_VALUE = 999999999999;\n\n/**\n * Returns a transit operator comparator value given a route and an optional\n * transitOperators config value. This function will do its best to handle all\n * kinds of input data as certain deployments of an implementing webapp may have\n * incomplete data and certain versions of OTP might not have a modified\n * implementation of the RouteShort model.\n *\n * @param {object} route Either an OTP Route or RouteShort model\n * @param {array} transitOperators transitOperators from config\n * @return {mixed} this could return a string value (the route's agency name) if\n * the transitOperators value is not defined. Otherwise an integer will be\n * returned.\n */\nfunction getTransitOperatorComparatorValue(\n route: Route,\n transitOperators: TransitOperator[]\n): number | string {\n // if the transitOperators is undefined or has zero length, use the route's\n // agency name as the comparator value\n if (!transitOperators || transitOperators.length === 0) {\n // OTP Route\n if (route.agency) return route.agency.name;\n // OTP RouteShort (base OTP repo or IBI fork)\n if (route.agencyName) return route.agencyName;\n // shouldn't happen as agency names will be defined\n return \"zzz\";\n }\n\n // find operator associated with route\n const transitOperator = getTransitOperatorFromOtpRoute(\n route,\n transitOperators\n );\n\n // if transit operator not found, return infinity\n if (!transitOperator) return END_OF_LIST_COMPARATOR_VALUE;\n\n // return the transit operator's sort value or END_OF_LIST_COMPARATOR_VALUE if\n // the sort value is not a number\n return typeof transitOperator.order === \"number\"\n ? transitOperator.order\n : END_OF_LIST_COMPARATOR_VALUE;\n}\n\n/**\n * Calculates the sort comparator value given two routes based off of the\n * route's agency and provided transitOperators config data.\n */\nfunction makeTransitOperatorComparator(transitOperators: TransitOperator[]) {\n return (a: Route, b: Route) => {\n const aVal = getTransitOperatorComparatorValue(a, transitOperators);\n const bVal = getTransitOperatorComparatorValue(b, transitOperators);\n if (typeof aVal === \"string\") {\n // happens when transitOperators is undefined. Both aVal are guaranteed to\n // be strings. Make a string comparison.\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n }\n // @ts-expect-error transitOperators are defined and therefore a numeric value is guaranteed\n // to be returned\n return aVal - bVal;\n };\n}\n\n/**\n * Gets the desired sort values according to an optional getter function. If the\n * getter function is not defined, the original sort values are returned.\n */\nfunction getSortValues(\n getterFn: (item: unknown) => unknown,\n a: unknown,\n b: unknown\n) {\n let aVal: unknown;\n let bVal: unknown;\n if (typeof getterFn === \"function\") {\n aVal = getterFn(a);\n bVal = getterFn(b);\n } else {\n aVal = a;\n bVal = b;\n }\n return { aVal, bVal };\n}\n\n// Lookup for the sort values associated with various OTP modes.\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// https://github.com/documentationjs/documentation/issues/372\nconst modeComparatorValue = {\n SUBWAY: 1,\n TRAM: 2,\n RAIL: 3,\n GONDOLA: 4,\n FERRY: 5,\n CABLE_CAR: 6,\n FUNICULAR: 7,\n BUS: 8\n};\n\n// Lookup that maps route types to the OTP mode sort values.\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// https://github.com/documentationjs/documentation/issues/372\nconst routeTypeComparatorValue = {\n 0: modeComparatorValue.TRAM, // - Tram, Streetcar, Light rail.\n 1: modeComparatorValue.SUBWAY, // - Subway, Metro.\n 2: modeComparatorValue.RAIL, // - Rail. Used for intercity or long-distance travel.\n 3: modeComparatorValue.BUS, // - Bus.\n 4: modeComparatorValue.FERRY, // - Ferry.\n 5: modeComparatorValue.CABLE_CAR, // - Cable tram.\n 6: modeComparatorValue.GONDOLA, // - Gondola, etc.\n 7: modeComparatorValue.FUNICULAR, // - Funicular.\n // TODO: 11 and 12 are not a part of OTP as of 2019-02-14, but for now just\n // associate them with bus/rail.\n 11: modeComparatorValue.BUS, // - Trolleybus.\n 12: modeComparatorValue.RAIL // - Monorail.\n};\n\n// Gets a comparator value for a given route's type (OTP mode).\n// Note: JSDoc format not used to avoid bug in documentationjs.\n// ttps://github.com/documentationjs/documentation/issues/372\nfunction getRouteTypeComparatorValue(route: Route): number {\n // For some strange reason, the short route response in OTP returns the\n // string-based modes, but the long route response returns the\n // integer route type. This attempts to account for both of those cases.\n if (!route) throw new Error(`Route is undefined. ${route}`);\n if (typeof modeComparatorValue[route.mode] !== \"undefined\") {\n return modeComparatorValue[route.mode];\n }\n if (typeof routeTypeComparatorValue[route.type] !== \"undefined\") {\n return routeTypeComparatorValue[route.type];\n }\n // Default the comparator value to a large number (placing the route at the\n // end of the list).\n // eslint-disable-next-line no-console\n console.warn(\"no mode/route type found for route\", route);\n return END_OF_LIST_COMPARATOR_VALUE;\n}\n\n/**\n * Calculates the sort comparator value given two routes based off of route type\n * (OTP mode).\n */\nfunction routeTypeComparator(a: Route, b: Route): number {\n return getRouteTypeComparatorValue(a) - getRouteTypeComparatorValue(b);\n}\n\n/**\n * Determines whether a value is a string that starts with an alphabetic\n * ascii character.\n */\nfunction startsWithAlphabeticCharacter(val: unknown): boolean {\n if (typeof val === \"string\" && val.length > 0) {\n const firstCharCode = val.charCodeAt(0);\n return (\n (firstCharCode >= 65 && firstCharCode <= 90) ||\n (firstCharCode >= 97 && firstCharCode <= 122)\n );\n }\n return false;\n}\n\n/**\n * Sorts routes based off of whether the shortName begins with an alphabetic\n * character. Routes with shortn that do start with an alphabetic character will\n * be prioritized over those that don't.\n */\nfunction alphabeticShortNameComparator(a: Route, b: Route): number {\n const aStartsWithAlphabeticCharacter = startsWithAlphabeticCharacter(\n a.shortName\n );\n const bStartsWithAlphabeticCharacter = startsWithAlphabeticCharacter(\n b.shortName\n );\n\n if (aStartsWithAlphabeticCharacter && bStartsWithAlphabeticCharacter) {\n // both start with an alphabetic character, return equivalence\n return 0;\n }\n // a does start with an alphabetic character, but b does not. Prioritize a\n if (aStartsWithAlphabeticCharacter) return -1;\n // b does start with an alphabetic character, but a does not. Prioritize b\n if (bStartsWithAlphabeticCharacter) return 1;\n // neither route has a shortName that starts with an alphabetic character.\n // Return equivalence\n return 0;\n}\n\n/**\n * Checks whether an appropriate comparison of numeric values can be made for\n * sorting purposes. If both values are not valid numbers according to the\n * isNaN check, then this function returns undefined which indicates that a\n * secondary sorting criteria should be used instead. If one value is valid and\n * the other is not, then the valid value will be given sorting priority. If\n * both values are valid numbers, the difference is obtained as the sort value.\n *\n * An optional argument can be provided which will be used to obtain the\n * comparison value from the comparison function arguments.\n *\n * IMPORTANT: the comparison values must be numeric values or at least be\n * attempted to be converted to numeric values! If one of the arguments is\n * something crazy like an empty string, unexpected behavior will occur because\n * JavaScript.\n *\n * @param {function} [objGetterFn] An optional function to obtain the\n * comparison value from the comparator function arguments\n */\nexport function makeNumericValueComparator(\n objGetterFn?: (item: Route) => number\n) {\n /* Note: Using the global version of isNaN (the Number version behaves differently. */\n /* eslint-disable no-restricted-globals */\n return (a: number, b: number): number => {\n const { aVal, bVal } = getSortValues(objGetterFn, a, b);\n if (typeof aVal !== \"number\" || typeof bVal !== \"number\") return 0;\n\n // if both values aren't valid numbers, use the next sort criteria\n if (isNaN(aVal) && isNaN(bVal)) return 0;\n // b is a valid number, b gets priority\n if (isNaN(aVal)) return 1;\n // a is a valid number, a gets priority\n if (isNaN(bVal)) return -1;\n // a and b are valid numbers, return the sort value\n return aVal - bVal;\n };\n}\n\n/**\n * Create a comparator function that compares string values. The comparison\n * values feed to the sort comparator function are assumed to be objects that\n * will have either undefined, null or string values at the given key. If one\n * object has undefined, null or an empty string, but the other does have a\n * string with length > 0, then that string will get priority.\n *\n * @param {function} [objGetterFn] An optional function to obtain the\n * comparison value from the comparator function arguments\n */\nexport function makeStringValueComparator(\n objGetterFn?: (item: Route) => string\n) {\n return (a: string, b: string): number => {\n const { aVal, bVal } = getSortValues(objGetterFn, a, b);\n // both a and b are uncomparable strings, return equivalent value\n if (!aVal && !bVal) return 0;\n // a is not a comparable string, b gets priority\n if (!aVal) return 1;\n // b is not a comparable string, a gets priority\n if (!bVal) return -1;\n // a and b are comparable strings, return the sort value\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n };\n}\n\n/**\n * OpenTripPlanner sets the routeSortOrder to -999 by default. So, if that value\n * is encountered, assume that it actually means that the routeSortOrder is not\n * set in the GTFS.\n *\n * See https://github.com/opentripplanner/OpenTripPlanner/issues/2938\n * Also see https://github.com/opentripplanner/otp-react-redux/issues/122\n */\nfunction getRouteSortOrderValue(val: number): number {\n return val === -999 ? undefined : val;\n}\n\n/**\n * Create a multi-criteria sort comparator function composed of other sort\n * comparator functions. Each comparator function will be ran in the order given\n * until a non-zero comparison value is obtained which is then immediately\n * returned. If all comparison functions return equivalence, then the values\n * are assumed to be equivalent.\n */\nfunction makeMultiCriteriaSort(\n ...criteria: ((a: unknown, b: unknown) => number)[]\n) {\n return (a: number, b: number): number => {\n for (let i = 0; i < criteria.length; i++) {\n const curCriteriaComparatorValue = criteria[i](a, b);\n // if the comparison objects are not equivalent, return the value obtained\n // in this current criteria comparison\n if (curCriteriaComparatorValue !== 0) {\n return curCriteriaComparatorValue;\n }\n }\n return 0;\n };\n}\n\n/**\n * Creates a sort comparator function to compares routes for the purposes of\n * sorting and displaying in a user interface. This takes in a single optional\n * argument which should be a list of transitOperators as defined in the config\n * file. Due to GTFS feeds having varying levels of data quality, a multi-\n * criteria sort is needed to account for various differences. The criteria\n * included here are each applied to the routes in the order listed. If a given\n * sort criterion yields equivalence (e.g., two routes have the short name\n * \"20\"), the comparator falls back onto the next sort criterion (e.g., long\n * name). The sort operates on the following values (in order):\n *\n * 1. Transit Operator. The transit operator will be attempted to be obtained\n * for each route. If no argument is provided when creating this comparator\n * function, then routes will be sorted by their agency's name. If an\n * argument is provided and a match is found based off of the route's feed_id\n * and agency_id and a transitOperator's feed_id and agency_id, then the\n * field transitOperator.order will be used as the comparator value as long\n * as it is numeric. If it is not numeric, a value is returned indicating\n * that this transit operator should be placed at the end of the list.\n * 2. sortOrder. Routes that do not have a valid sortOrder will be placed\n * beneath those that do.\n * 3. route type (OTP mode). See routeTypeComparator code for prioritization of\n * route types.\n * 4. shortNames that begin with alphabetic characters. shortNames that do not\n * start with alphabetic characters will be place beneath those that do.\n * 5. shortName as integer. shortNames that cannot be parsed as integers will\n * be placed beneath those that are valid.\n * 6. shortName as string. Routes without shortNames will be placed beneath\n * those with shortNames.\n * 7. longName as string.\n */\nexport function makeRouteComparator(\n transitOperators: TransitOperator[]\n): (a: number, b: number) => number {\n return makeMultiCriteriaSort(\n makeTransitOperatorComparator(transitOperators),\n makeNumericValueComparator(obj => getRouteSortOrderValue(obj.sortOrder)),\n routeTypeComparator,\n alphabeticShortNameComparator,\n makeNumericValueComparator(obj => parseInt(obj.shortName, 10)),\n makeStringValueComparator(obj => obj.shortName),\n makeStringValueComparator(obj => obj.longName)\n );\n}\n"],"file":"route.js"}
package/esm/storage.js CHANGED
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-console */
1
2
  // Prefix to use with local storage keys.
2
3
  var STORAGE_PREFIX = "otp";
3
4
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.js"],"names":["STORAGE_PREFIX","storeItem","key","object","window","localStorage","setItem","JSON","stringify","getItem","notFoundValue","itemAsString","json","parse","e","console","warn","removeItem","randId","Math","random","toString","substr"],"mappings":"AAAA;AACA,IAAMA,cAAc,GAAG,KAAvB;AAEA;AACA;AACA;;AACA,OAAO,SAASC,SAAT,CAAmBC,GAAnB,EAAwBC,MAAxB,EAAgC;AACrCC,EAAAA,MAAM,CAACC,YAAP,CAAoBC,OAApB,WACKN,cADL,cACuBE,GADvB,GAEEK,IAAI,CAACC,SAAL,CAAeL,MAAf,CAFF;AAID;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASM,OAAT,CAAiBP,GAAjB,EAA4C;AAAA,MAAtBQ,aAAsB,uEAAN,IAAM;AACjD,MAAIC,YAAJ;;AACA,MAAI;AACFA,IAAAA,YAAY,GAAGP,MAAM,CAACC,YAAP,CAAoBI,OAApB,WAA+BT,cAA/B,cAAiDE,GAAjD,EAAf;AACA,QAAMU,IAAI,GAAGL,IAAI,CAACM,KAAL,CAAWF,YAAX,CAAb;AACA,QAAIC,IAAJ,EAAU,OAAOA,IAAP;AACV,WAAOF,aAAP;AACD,GALD,CAKE,OAAOI,CAAP,EAAU;AACV;AACAC,IAAAA,OAAO,CAACC,IAAR,CAAaF,CAAb,EAAgBH,YAAhB;AACA,WAAOD,aAAP;AACD;AACF;AAED;AACA;AACA;;AACA,OAAO,SAASO,UAAT,CAAoBf,GAApB,EAAyB;AAC9BE,EAAAA,MAAM,CAACC,YAAP,CAAoBY,UAApB,WAAkCjB,cAAlC,cAAoDE,GAApD;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASgB,MAAT,GAAkB;AACvB,SAAOC,IAAI,CAACC,MAAL,GACJC,QADI,CACK,EADL,EAEJC,MAFI,CAEG,CAFH,EAEM,CAFN,CAAP;AAGD","sourcesContent":["// Prefix to use with local storage keys.\nconst STORAGE_PREFIX = \"otp\";\n\n/**\n * Store a javascript object at the specified key.\n */\nexport function storeItem(key, object) {\n window.localStorage.setItem(\n `${STORAGE_PREFIX}.${key}`,\n JSON.stringify(object)\n );\n}\n\n/**\n * Retrieve a javascript object at the specified key. If not found, defaults to\n * null or, the optionally provided notFoundValue.\n */\nexport function getItem(key, notFoundValue = null) {\n let itemAsString;\n try {\n itemAsString = window.localStorage.getItem(`${STORAGE_PREFIX}.${key}`);\n const json = JSON.parse(itemAsString);\n if (json) return json;\n return notFoundValue;\n } catch (e) {\n // Catch any errors associated with parsing bad JSON.\n console.warn(e, itemAsString);\n return notFoundValue;\n }\n}\n\n/**\n * Remove item at specified key.\n */\nexport function removeItem(key) {\n window.localStorage.removeItem(`${STORAGE_PREFIX}.${key}`);\n}\n\n/**\n * Generate a random ID. This might not quite be a UUID, but it serves our\n * purposes for now.\n */\nexport function randId() {\n return Math.random()\n .toString(36)\n .substr(2, 9);\n}\n"],"file":"storage.js"}
1
+ {"version":3,"sources":["../src/storage.ts"],"names":["STORAGE_PREFIX","storeItem","key","object","window","localStorage","setItem","JSON","stringify","getItem","notFoundValue","itemAsString","json","parse","e","console","warn","removeItem","randId","Math","random","toString","substr"],"mappings":"AAAA;AACA;AACA,IAAMA,cAAc,GAAG,KAAvB;AAEA;AACA;AACA;;AACA,OAAO,SAASC,SAAT,CAAmBC,GAAnB,EAAgCC,MAAhC,EAAuD;AAC5DC,EAAAA,MAAM,CAACC,YAAP,CAAoBC,OAApB,WACKN,cADL,cACuBE,GADvB,GAEEK,IAAI,CAACC,SAAL,CAAeL,MAAf,CAFF;AAID;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASM,OAAT,CAAiBP,GAAjB,EAAsE;AAAA,MAAxCQ,aAAwC,uEAAf,IAAe;AAC3E,MAAIC,YAAJ;;AACA,MAAI;AACFA,IAAAA,YAAY,GAAGP,MAAM,CAACC,YAAP,CAAoBI,OAApB,WAA+BT,cAA/B,cAAiDE,GAAjD,EAAf;AACA,QAAMU,IAAI,GAAGL,IAAI,CAACM,KAAL,CAAWF,YAAX,CAAb;AACA,QAAIC,IAAJ,EAAU,OAAOA,IAAP;AACV,WAAOF,aAAP;AACD,GALD,CAKE,OAAOI,CAAP,EAAU;AACV;AACAC,IAAAA,OAAO,CAACC,IAAR,CAAaF,CAAb,EAAgBH,YAAhB;AACA,WAAOD,aAAP;AACD;AACF;AAED;AACA;AACA;;AACA,OAAO,SAASO,UAAT,CAAoBf,GAApB,EAAuC;AAC5CE,EAAAA,MAAM,CAACC,YAAP,CAAoBY,UAApB,WAAkCjB,cAAlC,cAAoDE,GAApD;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASgB,MAAT,GAA0B;AAC/B,SAAOC,IAAI,CAACC,MAAL,GACJC,QADI,CACK,EADL,EAEJC,MAFI,CAEG,CAFH,EAEM,CAFN,CAAP;AAGD","sourcesContent":["/* eslint-disable no-console */\n// Prefix to use with local storage keys.\nconst STORAGE_PREFIX = \"otp\";\n\n/**\n * Store a javascript object at the specified key.\n */\nexport function storeItem(key: string, object: unknown): void {\n window.localStorage.setItem(\n `${STORAGE_PREFIX}.${key}`,\n JSON.stringify(object)\n );\n}\n\n/**\n * Retrieve a javascript object at the specified key. If not found, defaults to\n * null or, the optionally provided notFoundValue.\n */\nexport function getItem(key: string, notFoundValue: unknown = null): unknown {\n let itemAsString: string;\n try {\n itemAsString = window.localStorage.getItem(`${STORAGE_PREFIX}.${key}`);\n const json = JSON.parse(itemAsString);\n if (json) return json;\n return notFoundValue;\n } catch (e) {\n // Catch any errors associated with parsing bad JSON.\n console.warn(e, itemAsString);\n return notFoundValue;\n }\n}\n\n/**\n * Remove item at specified key.\n */\nexport function removeItem(key: string): void {\n window.localStorage.removeItem(`${STORAGE_PREFIX}.${key}`);\n}\n\n/**\n * Generate a random ID. This might not quite be a UUID, but it serves our\n * purposes for now.\n */\nexport function randId(): string {\n return Math.random()\n .toString(36)\n .substr(2, 9);\n}\n"],"file":"storage.js"}
package/esm/time.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { startOfDay, add, format, formatDuration as dateFnsFormatDuration } from "date-fns";
2
- import { utcToZonedTime } from "date-fns-tz"; // special constants for making sure the following date format is always sent to
2
+ import { utcToZonedTime } from "date-fns-tz";
3
+ /* eslint-disable import/no-cycle */
4
+
5
+ import { formatTime, formatDurationWithSeconds, formatDuration } from "./deprecated-with-types";
6
+ export { formatTime, formatDuration, formatDurationWithSeconds }; // special constants for making sure the following date format is always sent to
3
7
  // OTP regardless of whatever the user has configured as the display format
4
8
 
5
9
  export var OTP_API_DATE_FORMAT = "YYYY-MM-DD"; // Date-Fns uses a different string format than moment.js
@@ -17,7 +21,7 @@ export var OTP_API_TIME_FORMAT = "HH:mm";
17
21
  * @returns Formatted duration
18
22
  */
19
23
 
20
- function formatDurationLikeMoment(seconds, showSeconds) {
24
+ export function formatDurationLikeMoment(seconds, showSeconds) {
21
25
  var localize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
22
26
  enabled: true,
23
27
  code: "en-US"
@@ -58,7 +62,6 @@ function formatDurationLikeMoment(seconds, showSeconds) {
58
62
  * @returns an object with fields with the corresponding, hours, minutes, seconds.
59
63
  */
60
64
 
61
-
62
65
  export function toHoursMinutesSeconds(seconds) {
63
66
  var hours = Math.floor(seconds / 3600);
64
67
  var minutes = Math.floor((seconds - hours * 3600) / 60);
@@ -88,29 +91,6 @@ export function getLongDateFormat(config) {
88
91
 
89
92
  return (config === null || config === void 0 ? void 0 : (_config$dateTime3 = config.dateTime) === null || _config$dateTime3 === void 0 ? void 0 : _config$dateTime3.longDateFormat) || "D MMMM YYYY";
90
93
  }
91
- /**
92
- * Formats an elapsed time duration for display in narrative.
93
- * TODO: internationalization
94
- * @param {number} seconds duration in seconds
95
- * @returns {string} formatted text representation
96
- */
97
-
98
- export function formatDuration(seconds) {
99
- return formatDurationLikeMoment(seconds, false);
100
- }
101
- /**
102
- * Formats an elapsed time in seconds, minutes, hours duration for display in narrative
103
- * @param {number} seconds duration in seconds
104
- * @param {object} region an object that allows internationalization of the time
105
- * @returns {string} formatted text representation
106
- */
107
-
108
- export function formatDurationWithSeconds(seconds, region) {
109
- return formatDurationLikeMoment(seconds, {
110
- enabled: true,
111
- code: region
112
- });
113
- }
114
94
  /**
115
95
  * Offsets a time according to the provided time options
116
96
  * and returns the result.
@@ -119,16 +99,6 @@ export function formatDurationWithSeconds(seconds, region) {
119
99
  export function offsetTime(ms, options) {
120
100
  return ms + ((options === null || options === void 0 ? void 0 : options.offset) || 0);
121
101
  }
122
- /**
123
- * Formats a time value for display in narrative
124
- * TODO: internationalization/timezone
125
- * @param {number} ms epoch time value in milliseconds
126
- * @returns {string} formatted text representation
127
- */
128
-
129
- export function formatTime(ms, options) {
130
- return format(offsetTime(ms, options), (options === null || options === void 0 ? void 0 : options.format) || OTP_API_TIME_FORMAT);
131
- }
132
102
  /**
133
103
  * Formats a seconds after midnight value for display in narrative
134
104
  * @param {number} seconds time since midnight in seconds
package/esm/time.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/time.js"],"names":["startOfDay","add","format","formatDuration","dateFnsFormatDuration","utcToZonedTime","OTP_API_DATE_FORMAT","OTP_API_DATE_FORMAT_DATE_FNS","OTP_API_TIME_FORMAT","formatDurationLikeMoment","seconds","showSeconds","localize","enabled","code","hours","Math","floor","minutes","secondsLeftOver","specLookup","xHours","xMinutes","xSeconds","locale","formatDistance","spec","val","undefined","toHoursMinutesSeconds","getTimeFormat","config","dateTime","timeFormat","getDateFormat","dateFormat","getLongDateFormat","longDateFormat","formatDurationWithSeconds","region","offsetTime","ms","options","offset","formatTime","formatSecondsAfterMidnight","time","Date","getUserTimezone","fallbackTimezone","process","env","NODE_ENV","TZ","Intl","DateTimeFormat","resolvedOptions","timeZone","getCurrentTime","timezone","now","getCurrentDate"],"mappings":"AAAA,SACEA,UADF,EAEEC,GAFF,EAGEC,MAHF,EAIEC,cAAc,IAAIC,qBAJpB,QAKO,UALP;AAMA,SAASC,cAAT,QAA+B,aAA/B,C,CAEA;AACA;;AACA,OAAO,IAAMC,mBAAmB,GAAG,YAA5B,C,CACP;AACA;;AACA,OAAO,IAAMC,4BAA4B,GAAG,YAArC;AACP,OAAO,IAAMC,mBAAmB,GAAG,OAA5B;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,SAASC,wBAAT,CACEC,OADF,EAEEC,WAFF,EAIE;AAAA,MADAC,QACA,uEADW;AAAEC,IAAAA,OAAO,EAAE,IAAX;AAAiBC,IAAAA,IAAI,EAAE;AAAvB,GACX;;AACA;AACA,MAAK,CAACH,WAAD,IAAgBD,OAAO,GAAG,EAA3B,IAAkCA,OAAO,KAAK,CAAlD,EAAqD;AACnD,WAAO,OAAP;AACD;;AAED,MAAMK,KAAK,GAAGC,IAAI,CAACC,KAAL,CAAWP,OAAO,GAAG,IAArB,CAAd;AACA,MAAMQ,OAAO,GAAGF,IAAI,CAACC,KAAL,CAAW,CAACP,OAAO,GAAGK,KAAK,GAAG,IAAnB,IAA2B,EAAtC,CAAhB;AACA,MAAMI,eAAe,GAAGR,WAAW,GAC/BD,OAAO,GAAGK,KAAK,GAAG,IAAlB,GAAyBG,OAAO,GAAG,EADJ,GAE/B,CAFJ;AAGA,MAAME,UAAU,GAAG;AACjBC,IAAAA,MAAM,EAAE,IADS;AAEjBC,IAAAA,QAAQ,EAAE,KAFO;AAGjBC,IAAAA,QAAQ,EAAE;AAHO,GAAnB;AAKA,MAAMC,MAAM,GAAGZ,QAAQ,GACnB;AACE;AACAE,IAAAA,IAAI,EAAE,C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,OAAO,EAAPA;AAAF,GAAzB,CAAhB;AACA,SAAOR,MAAM,CAAC4C,IAAD,EAAOb,UAAP,CAAb;AACD;AAED;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASe,eAAT,GAA6D;AAAA;;AAAA,MAApCC,gBAAoC,uEAAjB,eAAiB;AAClE,MAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,MAA7B,EAAqC,OAAOF,OAAO,CAACC,GAAR,CAAYE,EAAnB;AACrC,SAAO,UAAAC,IAAI,UAAJ,sCAAMC,cAAN,GAAuBC,eAAvB,GAAyCC,QAAzC,KAAqDR,gBAA5D;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASS,cAAT,GAAsD;AAAA,MAA9BC,QAA8B,uEAAnBX,eAAe,EAAI;AAC3D,SAAO9C,MAAM,CAACG,cAAc,CAAC0C,IAAI,CAACa,GAAL,EAAD,EAAaD,QAAb,CAAf,EAAuCnD,mBAAvC,CAAb;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASqD,cAAT,GAAsD;AAAA,MAA9BF,QAA8B,uEAAnBX,eAAe,EAAI;AAC3D,SAAO9C,MAAM,CACXG,cAAc,CAAC0C,IAAI,CAACa,GAAL,EAAD,EAAaD,QAAb,CADH,EAEXpD,4BAFW,CAAb;AAID","sourcesContent":["import {\n startOfDay,\n add,\n format,\n formatDuration as dateFnsFormatDuration\n} from \"date-fns\";\nimport { utcToZonedTime } from \"date-fns-tz\";\n\n// special constants for making sure the following date format is always sent to\n// OTP regardless of whatever the user has configured as the display format\nexport const OTP_API_DATE_FORMAT = \"YYYY-MM-DD\";\n// Date-Fns uses a different string format than moment.js\n// see https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\nexport const OTP_API_DATE_FORMAT_DATE_FNS = \"yyyy-MM-dd\";\nexport const OTP_API_TIME_FORMAT = \"HH:mm\";\n\n/**\n * To ease the transition away from moment.js, this method uses date-fns to format durations\n * the way moment.js did.\n * @param {number} seconds The number of seconds to format\n * @param {boolean} showSeconds Whether to render seconds or not\n * @param {boolean} localize If true, will create output like moment.js using date-fns locale.\n * Otherwise, uses date-fns default\n * @returns Formatted duration\n */\nfunction formatDurationLikeMoment(\n seconds,\n showSeconds,\n localize = { enabled: true, code: \"en-US\" }\n) {\n // date-fns doesn't do this automatically\n if ((!showSeconds && seconds < 60) || seconds === 0) {\n return \"0 min\";\n }\n\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds - hours * 3600) / 60);\n const secondsLeftOver = showSeconds\n ? seconds - hours * 3600 - minutes * 60\n : 0;\n const specLookup = {\n xHours: \"hr\",\n xMinutes: \"min\",\n xSeconds: \"sec\"\n };\n const locale = localize\n ? {\n // Maintain backwards compatibility when called with localize=true\n code: localize?.code || \"en-US\",\n formatDistance: (spec, val) => {\n return `${val} ${specLookup[spec]}`;\n }\n }\n : undefined;\n\n return dateFnsFormatDuration(\n {\n hours,\n minutes,\n seconds: secondsLeftOver\n },\n {\n format: [\"hours\", \"minutes\", \"seconds\"],\n locale\n }\n );\n}\n\n/**\n * Breaks up a duration in seconds into hours, minutes, and seconds.\n * @param {number} seconds The number of seconds to break up\n * @returns an object with fields with the corresponding, hours, minutes, seconds.\n */\nexport function toHoursMinutesSeconds(seconds) {\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds - hours * 3600) / 60);\n return {\n hours,\n minutes,\n seconds: seconds - hours * 3600 - minutes * 60\n };\n}\n\n/**\n * @param {[type]} config the OTP config object found in store\n * @return {string} the config-defined time formatter or HH:mm (24-hr time)\n */\nexport function getTimeFormat(config) {\n return config?.dateTime?.timeFormat || OTP_API_TIME_FORMAT;\n}\n\nexport function getDateFormat(config) {\n return config?.dateTime?.dateFormat || OTP_API_DATE_FORMAT;\n}\n\nexport function getLongDateFormat(config) {\n return config?.dateTime?.longDateFormat || \"D MMMM YYYY\";\n}\n\n/**\n * Formats an elapsed time duration for display in narrative.\n * TODO: internationalization\n * @param {number} seconds duration in seconds\n * @returns {string} formatted text representation\n */\nexport function formatDuration(seconds) {\n return formatDurationLikeMoment(seconds, false);\n}\n\n/**\n * Formats an elapsed time in seconds, minutes, hours duration for display in narrative\n * @param {number} seconds duration in seconds\n * @param {object} region an object that allows internationalization of the time\n * @returns {string} formatted text representation\n */\nexport function formatDurationWithSeconds(seconds, region) {\n return formatDurationLikeMoment(seconds, { enabled: true, code: region });\n}\n\n/**\n * Offsets a time according to the provided time options\n * and returns the result.\n */\nexport function offsetTime(ms, options) {\n return ms + (options?.offset || 0);\n}\n\n/**\n * Formats a time value for display in narrative\n * TODO: internationalization/timezone\n * @param {number} ms epoch time value in milliseconds\n * @returns {string} formatted text representation\n */\nexport function formatTime(ms, options) {\n return format(\n offsetTime(ms, options),\n options?.format || OTP_API_TIME_FORMAT\n );\n}\n\n/**\n * Formats a seconds after midnight value for display in narrative\n * @param {number} seconds time since midnight in seconds\n * @param {string} timeFormat A valid date-fns time format\n * @return {string} formatted text representation\n */\nexport function formatSecondsAfterMidnight(seconds, timeFormat) {\n const time = add(startOfDay(new Date()), { seconds });\n return format(time, timeFormat);\n}\n\n/**\n * Uses Intl.DateTimeFormat() api to get the user's time zone. In a test\n * environment, pulls timezone information from an env variable. Default to\n * GMT+0 if the Intl API is unavailable.\n */\nexport function getUserTimezone(fallbackTimezone = \"Etc/Greenwich\") {\n if (process.env.NODE_ENV === \"test\") return process.env.TZ;\n return Intl?.DateTimeFormat().resolvedOptions().timeZone || fallbackTimezone;\n}\n\n/**\n * Formats current time for use in OTP query\n * The conversion to the user's timezone is needed for testing purposes.\n */\nexport function getCurrentTime(timezone = getUserTimezone()) {\n return format(utcToZonedTime(Date.now(), timezone), OTP_API_TIME_FORMAT);\n}\n\n/**\n * Formats current date for use in OTP query\n * The conversion to the user's timezone is needed for testing purposes.\n */\nexport function getCurrentDate(timezone = getUserTimezone()) {\n return format(\n utcToZonedTime(Date.now(), timezone),\n OTP_API_DATE_FORMAT_DATE_FNS\n );\n}\n"],"file":"time.js"}
1
+ {"version":3,"sources":["../src/time.ts"],"names":["startOfDay","add","format","formatDuration","dateFnsFormatDuration","utcToZonedTime","formatTime","formatDurationWithSeconds","OTP_API_DATE_FORMAT","OTP_API_DATE_FORMAT_DATE_FNS","OTP_API_TIME_FORMAT","formatDurationLikeMoment","seconds","showSeconds","localize","enabled","code","hours","Math","floor","minutes","secondsLeftOver","specLookup","xHours","xMinutes","xSeconds","locale","formatDistance","spec","val","undefined","toHoursMinutesSeconds","getTimeFormat","config","dateTime","timeFormat","getDateFormat","dateFormat","getLongDateFormat","longDateFormat","offsetTime","ms","options","offset","formatSecondsAfterMidnight","time","Date","getUserTimezone","fallbackTimezone","process","env","NODE_ENV","TZ","Intl","DateTimeFormat","resolvedOptions","timeZone","getCurrentTime","timezone","now","getCurrentDate"],"mappings":"AACA,SACEA,UADF,EAEEC,GAFF,EAGEC,MAHF,EAIEC,cAAc,IAAIC,qBAJpB,QAKO,UALP;AAMA,SAASC,cAAT,QAA+B,aAA/B;AAEA;;AACA,SACEC,UADF,EAEEC,yBAFF,EAGEJ,cAHF,QAIO,yBAJP;AAMA,SAASG,UAAT,EAAqBH,cAArB,EAAqCI,yBAArC,G,CAEA;AACA;;AACA,OAAO,IAAMC,mBAAmB,GAAG,YAA5B,C,CACP;AACA;;AACA,OAAO,IAAMC,4BAA4B,GAAG,YAArC;AACP,OAAO,IAAMC,mBAAmB,GAAG,OAA5B;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASC,wBAAT,CACLC,OADK,EAELC,WAFK,EAOG;AAAA,MAJRC,QAIQ,uEAJuC;AAC7CC,IAAAA,OAAO,EAAE,IADoC;AAE7CC,IAAAA,IAAI,EAAE;AAFuC,GAIvC;;AACR;AACA,MAAK,CAACH,WAAD,IAAgBD,OAAO,GAAG,EAA3B,IAAkCA,OAAO,KAAK,CAAlD,EAAqD;AACnD,WAAO,OAAP;AACD;;AAED,MAAMK,KAAK,GAAGC,IAAI,CAACC,KAAL,C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,gBAA4C,uEAAzB,eAAyB;AAC1E,MAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,MAA7B,EAAqC,OAAOF,OAAO,CAACC,GAAR,CAAYE,EAAnB;AACrC,SAAO,UAAAC,IAAI,UAAJ,sCAAMC,cAAN,GAAuBC,eAAvB,GAAyCC,QAAzC,KAAqDR,gBAA5D;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASS,cAAT,GAA8D;AAAA,MAAtCC,QAAsC,uEAA3BX,eAAe,EAAY;AACnE,SAAO7C,MAAM,CAACG,cAAc,CAACyC,IAAI,CAACa,GAAL,EAAD,EAAaD,QAAb,CAAf,EAAuChD,mBAAvC,CAAb;AACD;AAED;AACA;AACA;AACA;;AACA,OAAO,SAASkD,cAAT,GAA8D;AAAA,MAAtCF,QAAsC,uEAA3BX,eAAe,EAAY;AACnE,SAAO7C,MAAM,CACXG,cAAc,CAACyC,IAAI,CAACa,GAAL,EAAD,EAAaD,QAAb,CADH,EAEXjD,4BAFW,CAAb;AAID","sourcesContent":["import { Config } from \"@opentripplanner/types\";\nimport {\n startOfDay,\n add,\n format,\n formatDuration as dateFnsFormatDuration\n} from \"date-fns\";\nimport { utcToZonedTime } from \"date-fns-tz\";\n\n/* eslint-disable import/no-cycle */\nimport {\n formatTime,\n formatDurationWithSeconds,\n formatDuration\n} from \"./deprecated-with-types\";\n\nexport { formatTime, formatDuration, formatDurationWithSeconds };\n\n// special constants for making sure the following date format is always sent to\n// OTP regardless of whatever the user has configured as the display format\nexport const OTP_API_DATE_FORMAT = \"YYYY-MM-DD\";\n// Date-Fns uses a different string format than moment.js\n// see https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\nexport const OTP_API_DATE_FORMAT_DATE_FNS = \"yyyy-MM-dd\";\nexport const OTP_API_TIME_FORMAT = \"HH:mm\";\n\n/**\n * To ease the transition away from moment.js, this method uses date-fns to format durations\n * the way moment.js did.\n * @param {number} seconds The number of seconds to format\n * @param {boolean} showSeconds Whether to render seconds or not\n * @param {boolean} localize If true, will create output like moment.js using date-fns locale.\n * Otherwise, uses date-fns default\n * @returns Formatted duration\n */\nexport function formatDurationLikeMoment(\n seconds: number,\n showSeconds: boolean,\n localize: { enabled: boolean; code: string } = {\n enabled: true,\n code: \"en-US\"\n }\n): string {\n // date-fns doesn't do this automatically\n if ((!showSeconds && seconds < 60) || seconds === 0) {\n return \"0 min\";\n }\n\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds - hours * 3600) / 60);\n const secondsLeftOver = showSeconds\n ? seconds - hours * 3600 - minutes * 60\n : 0;\n const specLookup = {\n xHours: \"hr\",\n xMinutes: \"min\",\n xSeconds: \"sec\"\n };\n const locale = localize\n ? {\n // Maintain backwards compatibility when called with localize=true\n code: localize?.code || \"en-US\",\n formatDistance: (spec, val) => {\n return `${val} ${specLookup[spec]}`;\n }\n }\n : undefined;\n\n return dateFnsFormatDuration(\n {\n hours,\n minutes,\n seconds: secondsLeftOver\n },\n {\n format: [\"hours\", \"minutes\", \"seconds\"],\n locale\n }\n );\n}\n\n/**\n * Breaks up a duration in seconds into hours, minutes, and seconds.\n * @param {number} seconds The number of seconds to break up\n * @returns an object with fields with the corresponding, hours, minutes, seconds.\n */\nexport function toHoursMinutesSeconds(seconds) {\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds - hours * 3600) / 60);\n return {\n hours,\n minutes,\n seconds: seconds - hours * 3600 - minutes * 60\n };\n}\n\n/**\n * @param {[type]} config the OTP config object found in store\n * @return {string} the config-defined time formatter or HH:mm (24-hr time)\n */\nexport function getTimeFormat(config: Config): string {\n return config?.dateTime?.timeFormat || OTP_API_TIME_FORMAT;\n}\n\nexport function getDateFormat(config: Config): string {\n return config?.dateTime?.dateFormat || OTP_API_DATE_FORMAT;\n}\n\nexport function getLongDateFormat(config: Config): string {\n return config?.dateTime?.longDateFormat || \"D MMMM YYYY\";\n}\n/**\n * Offsets a time according to the provided time options\n * and returns the result.\n */\nexport function offsetTime(ms, options) {\n return ms + (options?.offset || 0);\n}\n\n/**\n * Formats a seconds after midnight value for display in narrative\n * @param {number} seconds time since midnight in seconds\n * @param {string} timeFormat A valid date-fns time format\n * @return {string} formatted text representation\n */\nexport function formatSecondsAfterMidnight(\n seconds: number,\n timeFormat: string\n): string {\n const time = add(startOfDay(new Date()), { seconds });\n return format(time, timeFormat);\n}\n\n/**\n * Uses Intl.DateTimeFormat() api to get the user's time zone. In a test\n * environment, pulls timezone information from an env variable. Default to\n * GMT+0 if the Intl API is unavailable.\n */\nexport function getUserTimezone(fallbackTimezone = \"Etc/Greenwich\"): string {\n if (process.env.NODE_ENV === \"test\") return process.env.TZ;\n return Intl?.DateTimeFormat().resolvedOptions().timeZone || fallbackTimezone;\n}\n\n/**\n * Formats current time for use in OTP query\n * The conversion to the user's timezone is needed for testing purposes.\n */\nexport function getCurrentTime(timezone = getUserTimezone()): string {\n return format(utcToZonedTime(Date.now(), timezone), OTP_API_TIME_FORMAT);\n}\n\n/**\n * Formats current date for use in OTP query\n * The conversion to the user's timezone is needed for testing purposes.\n */\nexport function getCurrentDate(timezone = getUserTimezone()): string {\n return format(\n utcToZonedTime(Date.now(), timezone),\n OTP_API_DATE_FORMAT_DATE_FNS\n );\n}\n"],"file":"time.js"}
package/esm/ui.js CHANGED
@@ -8,7 +8,7 @@ export function isMobile() {
8
8
  */
9
9
 
10
10
  export function isIE() {
11
- return bowser.name === "Internet Explorer";
11
+ return bowser.parse(navigator.userAgent).browser === "Internet Explorer";
12
12
  }
13
13
  /**
14
14
  * Enables scrolling for a specified selector, while disabling scrolling for all
package/esm/ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ui.js"],"names":["bowser","isMobile","test","navigator","userAgent","isIE","name","enableScrollForSelector","selector","overlay","document","querySelector","clientY","isOverlayTotallyScrolled","scrollHeight","scrollTop","clientHeight","disableRubberBand","event","clientYDelta","targetTouches","preventDefault","addEventListener","length"],"mappings":"AAAA,OAAOA,MAAP,M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oBG,MAApB,KAA+B,CAAnC,EAAsC;AACpC;AACAN,MAAAA,iBAAiB,CAACC,KAAD,CAAjB;AACD;AACF,GAPH,EAQE,KARF;AAUD","sourcesContent":["import bowser from \"bowser\";\n\nexport function isMobile() {\n // TODO: consider using 3rd-party library?\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n}\n\n/**\n * Returns true if the user is using a [redacted] browser\n */\nexport function isIE() {\n return bowser.name === \"Internet Explorer\";\n}\n\n/**\n * Enables scrolling for a specified selector, while disabling scrolling for all\n * other targets. This is adapted from https://stackoverflow.com/a/41601290/915811\n * and intended to fix issues with iOS elastic scrolling, e.g.,\n * https://github.com/conveyal/trimet-mod-otp/issues/92.\n */\nexport function enableScrollForSelector(selector) {\n const overlay = document.querySelector(selector);\n let clientY = null; // remember Y position on touch start\n\n function isOverlayTotallyScrolled() {\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions\n return overlay.scrollHeight - overlay.scrollTop <= overlay.clientHeight;\n }\n\n function disableRubberBand(event) {\n const clientYDelta = event.targetTouches[0].clientY - clientY;\n\n if (overlay.scrollTop === 0 && clientYDelta > 0) {\n // element is at the top of its scroll\n event.preventDefault();\n }\n\n if (isOverlayTotallyScrolled() && clientYDelta < 0) {\n // element is at the top of its scroll\n event.preventDefault();\n }\n }\n\n overlay.addEventListener(\n \"touchstart\",\n function(event) {\n if (event.targetTouches.length === 1) {\n // detect single touch\n clientY = event.targetTouches[0].clientY;\n }\n },\n false\n );\n\n overlay.addEventListener(\n \"touchmove\",\n function(event) {\n if (event.targetTouches.length === 1) {\n // detect single touch\n disableRubberBand(event);\n }\n },\n false\n );\n}\n"],"file":"ui.js"}
1
+ {"version":3,"sources":["../src/ui.ts"],"names":["bowser","isMobile","test","navigator","userAgent","isIE","parse","browser","enableScrollForSelector","selector","overlay","document","querySelector","clientY","isOverlayTotallyScrolled","scrollHeight","scrollTop","clientHeight","disableRubberBand","event","clientYDelta","targetTouches","preventDefault","addEventListener","length"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,QAAnB;AAEA,OAAO,SAASC,QAAT,GAA6B;AAClC;AACA,SAAO,iEAAiEC,IAAjE,CACLC,SAAS,CAACC,SADL,CAAP;AAGD;AAED;AACA;AACA;;AACA,OAAO,SAASC,IAAT,GAAyB;AAC9B,SAAOL,MAAM,CAACM,KAAP,CAAaH,SAAS,CAACC,SAAvB,EAAkCG,OAAlC,KAA8C,mBAArD;AACD;AAED;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASC,uBAAT,CAAiCC,QAAjC,EAAyD;AAC9D,MAAMC,OAAO,GAAGC,QAAQ,CAACC,aAAT,CAAuBH,QAAvB,CAAhB;AACA,MAAII,OAAO,GAAG,IAAd,CAF8D,CAE1C;;AAEpB,WAASC,wBAAT,GAA6C;AAC3C;AACA,WAAOJ,OAAO,CAACK,YAAR,GAAuBL,OAAO,CAACM,SAA/B,IAA4CN,OAAO,CAACO,YAA3D;AACD;;AAED,WAASC,iBAAT,CAA2BC,KAA3B,EAA8C;AAC5C,QAAMC,YAAY,GAAGD,KAAK,CAACE,aAAN,CAAoB,CAApB,EAAuBR,OAAvB,GAAiCA,OAAtD;;AAEA,QAAIH,OAAO,CAACM,SAAR,KAAsB,CAAtB,IAA2BI,YAAY,GAAG,CAA9C,EAAiD;AAC/C;AACAD,MAAAA,KAAK,CAACG,cAAN;AACD;;AAED,QAAIR,wBAAwB,MAAMM,YAAY,GAAG,CAAjD,EAAoD;AAClD;AACAD,MAAAA,KAAK,CAACG,cAAN;AACD;AACF;;AAEDZ,EAAAA,OAAO,CAACa,gBAAR,CACE,YADF,EAEE,UAASJ,KAAT,EAA4B;AAC1B,QAAIA,KAAK,CAACE,aAAN,CAAoBG,MAApB,KAA+B,CAAnC,EAAsC;AACpC;AACAX,MAAAA,OAAO,GAAGM,KAAK,CAACE,aAAN,CAAoB,CAApB,EAAuBR,OAAjC;AACD;AACF,GAPH,EAQE,KARF;AAWAH,EAAAA,OAAO,CAACa,gBAAR,CACE,WADF,EAEE,UAASJ,KAAT,EAA4B;AAC1B,QAAIA,KAAK,CAACE,aAAN,CAAoBG,MAApB,KAA+B,CAAnC,EAAsC;AACpC;AACAN,MAAAA,iBAAiB,CAACC,KAAD,CAAjB;AACD;AACF,GAPH,EAQE,KARF;AAUD","sourcesContent":["import bowser from \"bowser\";\n\nexport function isMobile(): boolean {\n // TODO: consider using 3rd-party library?\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n}\n\n/**\n * Returns true if the user is using a [redacted] browser\n */\nexport function isIE(): boolean {\n return bowser.parse(navigator.userAgent).browser === \"Internet Explorer\";\n}\n\n/**\n * Enables scrolling for a specified selector, while disabling scrolling for all\n * other targets. This is adapted from https://stackoverflow.com/a/41601290/915811\n * and intended to fix issues with iOS elastic scrolling, e.g.,\n * https://github.com/conveyal/trimet-mod-otp/issues/92.\n */\nexport function enableScrollForSelector(selector: string): void {\n const overlay = document.querySelector(selector);\n let clientY = null; // remember Y position on touch start\n\n function isOverlayTotallyScrolled(): boolean {\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions\n return overlay.scrollHeight - overlay.scrollTop <= overlay.clientHeight;\n }\n\n function disableRubberBand(event: TouchEvent) {\n const clientYDelta = event.targetTouches[0].clientY - clientY;\n\n if (overlay.scrollTop === 0 && clientYDelta > 0) {\n // element is at the top of its scroll\n event.preventDefault();\n }\n\n if (isOverlayTotallyScrolled() && clientYDelta < 0) {\n // element is at the top of its scroll\n event.preventDefault();\n }\n }\n\n overlay.addEventListener(\n \"touchstart\",\n function(event: TouchEvent) {\n if (event.targetTouches.length === 1) {\n // detect single touch\n clientY = event.targetTouches[0].clientY;\n }\n },\n false\n );\n\n overlay.addEventListener(\n \"touchmove\",\n function(event: TouchEvent) {\n if (event.targetTouches.length === 1) {\n // detect single touch\n disableRubberBand(event);\n }\n },\n false\n );\n}\n"],"file":"ui.js"}
@@ -0,0 +1,23 @@
1
+ import { TimeOptions } from "@opentripplanner/types";
2
+ /**
3
+ * Formats a time value for display in narrative
4
+ * TODO: internationalization/timezone
5
+ * @param {number} ms epoch time value in milliseconds
6
+ * @returns {string} formatted text representation
7
+ */
8
+ export declare function formatTime(ms: number, options: TimeOptions): string;
9
+ /**
10
+ * Formats an elapsed time duration for display in narrative.
11
+ * TODO: internationalization
12
+ * @param {number} seconds duration in seconds
13
+ * @returns {string} formatted text representation
14
+ */
15
+ export declare function formatDuration(seconds: number, region: string): string;
16
+ /**
17
+ * Formats an elapsed time in seconds, minutes, hours duration for display in narrative
18
+ * @param {number} seconds duration in seconds
19
+ * @param {object} region an object that allows internationalization of the time
20
+ * @returns {string} formatted text representation
21
+ */
22
+ export declare function formatDurationWithSeconds(seconds: number, region: string): string;
23
+ //# sourceMappingURL=deprecated-with-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deprecated-with-types.d.ts","sourceRoot":"","sources":["../src/deprecated-with-types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAYrD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,MAAM,CAOnE;AAED;;;;;GAKG;AAEH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAOtE;AAED;;;;;GAKG;AAEH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,MAAM,CAOR"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.formatTime = formatTime;
7
+ exports.formatDuration = formatDuration;
8
+ exports.formatDurationWithSeconds = formatDurationWithSeconds;
9
+
10
+ var _dateFns = require("date-fns");
11
+
12
+ var _deprecated = require("./deprecated");
13
+
14
+ var _time = require("./time");
15
+
16
+ /* eslint-disable import/no-cycle */
17
+ // time.ts
18
+
19
+ /**
20
+ * Formats a time value for display in narrative
21
+ * TODO: internationalization/timezone
22
+ * @param {number} ms epoch time value in milliseconds
23
+ * @returns {string} formatted text representation
24
+ */
25
+ function formatTime(ms, options) {
26
+ (0, _deprecated.logDeprecationWarning)("formatTime", "formatjs");
27
+ return (0, _dateFns.format)((0, _time.offsetTime)(ms, options), (options === null || options === void 0 ? void 0 : options.format) || _time.OTP_API_TIME_FORMAT);
28
+ }
29
+ /**
30
+ * Formats an elapsed time duration for display in narrative.
31
+ * TODO: internationalization
32
+ * @param {number} seconds duration in seconds
33
+ * @returns {string} formatted text representation
34
+ */
35
+ // TS TODO: region as type?
36
+
37
+
38
+ function formatDuration(seconds, region) {
39
+ (0, _deprecated.logDeprecationWarning)("formatDuration", "formatjs");
40
+ return (0, _time.formatDurationLikeMoment)(seconds, false, {
41
+ enabled: true,
42
+ code: region
43
+ });
44
+ }
45
+ /**
46
+ * Formats an elapsed time in seconds, minutes, hours duration for display in narrative
47
+ * @param {number} seconds duration in seconds
48
+ * @param {object} region an object that allows internationalization of the time
49
+ * @returns {string} formatted text representation
50
+ */
51
+ // TS TODO: region as type?
52
+
53
+
54
+ function formatDurationWithSeconds(seconds, region) {
55
+ (0, _deprecated.logDeprecationWarning)("formatDurationWithSeconds", "formatjs");
56
+ return (0, _time.formatDurationLikeMoment)(seconds, true, {
57
+ enabled: true,
58
+ code: region
59
+ });
60
+ }
61
+ //# sourceMappingURL=deprecated-with-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/deprecated-with-types.ts"],"names":["formatTime","ms","options","format","OTP_API_TIME_FORMAT","formatDuration","seconds","region","enabled","code","formatDurationWithSeconds"],"mappings":";;;;;;;;;AAEA;;AAEA;;AACA;;AALA;AAWA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,UAAT,CAAoBC,EAApB,EAAgCC,OAAhC,EAA8D;AACnE,yCAAsB,YAAtB,EAAoC,UAApC;AAEA,SAAO,qBACL,sBAAWD,EAAX,EAAeC,OAAf,CADK,EAEL,CAAAA,OAAO,SAAP,IAAAA,OAAO,WAAP,YAAAA,OAAO,CAAEC,MAAT,KAAmBC,yBAFd,CAAP;AAID;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASC,cAAT,CAAwBC,OAAxB,EAAyCC,MAAzC,EAAiE;AACtE,yCAAsB,gBAAtB,EAAwC,UAAxC;AAEA,SAAO,oCAAyBD,OAAzB,EAAkC,KAAlC,EAAyC;AAC9CE,IAAAA,OAAO,EAAE,IADqC;AAE9CC,IAAAA,IAAI,EAAEF;AAFwC,GAAzC,CAAP;AAID;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASG,yBAAT,CACLJ,OADK,EAELC,MAFK,EAGG;AACR,yCAAsB,2BAAtB,EAAmD,UAAnD;AAEA,SAAO,oCAAyBD,OAAzB,EAAkC,IAAlC,EAAwC;AAC7CE,IAAAA,OAAO,EAAE,IADoC;AAE7CC,IAAAA,IAAI,EAAEF;AAFuC,GAAxC,CAAP;AAID","sourcesContent":["/* eslint-disable import/no-cycle */\nimport { TimeOptions } from \"@opentripplanner/types\";\nimport { format } from \"date-fns\";\n\nimport { logDeprecationWarning } from \"./deprecated\";\nimport {\n formatDurationLikeMoment,\n offsetTime,\n OTP_API_TIME_FORMAT\n} from \"./time\";\n\n// time.ts\n\n/**\n * Formats a time value for display in narrative\n * TODO: internationalization/timezone\n * @param {number} ms epoch time value in milliseconds\n * @returns {string} formatted text representation\n */\nexport function formatTime(ms: number, options: TimeOptions): string {\n logDeprecationWarning(\"formatTime\", \"formatjs\");\n\n return format(\n offsetTime(ms, options),\n options?.format || OTP_API_TIME_FORMAT\n );\n}\n\n/**\n * Formats an elapsed time duration for display in narrative.\n * TODO: internationalization\n * @param {number} seconds duration in seconds\n * @returns {string} formatted text representation\n */\n// TS TODO: region as type?\nexport function formatDuration(seconds: number, region: string): string {\n logDeprecationWarning(\"formatDuration\", \"formatjs\");\n\n return formatDurationLikeMoment(seconds, false, {\n enabled: true,\n code: region\n });\n}\n\n/**\n * Formats an elapsed time in seconds, minutes, hours duration for display in narrative\n * @param {number} seconds duration in seconds\n * @param {object} region an object that allows internationalization of the time\n * @returns {string} formatted text representation\n */\n// TS TODO: region as type?\nexport function formatDurationWithSeconds(\n seconds: number,\n region: string\n): string {\n logDeprecationWarning(\"formatDurationWithSeconds\", \"formatjs\");\n\n return formatDurationLikeMoment(seconds, true, {\n enabled: true,\n code: region\n });\n}\n"],"file":"deprecated-with-types.js"}
package/lib/deprecated.js CHANGED
@@ -18,6 +18,7 @@ exports.latlngToString = latlngToString;
18
18
  exports.coordsToString = coordsToString;
19
19
  exports.getDetailText = getDetailText;
20
20
  exports.summarizeQuery = summarizeQuery;
21
+ exports.getTimeZoneOffset = getTimeZoneOffset;
21
22
 
22
23
  var _moment = _interopRequireDefault(require("moment"));
23
24
 
@@ -343,4 +344,12 @@ function summarizeQuery(query, locations = []) {
343
344
  const mode = require("./itinerary").hasTransit(query.mode) ? "Transit" : require("./itinerary").toSentenceCase(query.mode);
344
345
  return `${mode} from ${from} to ${to}`;
345
346
  }
347
+
348
+ function getTimeZoneOffset(itinerary) {
349
+ logDeprecationWarning("getTimeZoneOffset");
350
+ if (!itinerary.legs || !itinerary.legs.length) return 0; // Determine if there is a DST offset between now and the itinerary start date
351
+
352
+ const dstOffset = new Date(itinerary.startTime).getTimezoneOffset() - new Date().getTimezoneOffset();
353
+ return itinerary.legs[0].agencyTimeZoneOffset + (new Date().getTimezoneOffset() + dstOffset) * 60000;
354
+ }
346
355
  //# sourceMappingURL=deprecated.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deprecated.js"],"names":["logDeprecationWarning","method","alternative","console","warn","getStepDirection","step","relativeDirection","absoluteDirection","toLowerCase","getStepInstructions","conjunction","streetName","getStepStreetName","getLegModeLabel","leg","mode","hailedCar","routeLongName","indexOf","require","toSentenceCase","getModeForPlace","place","vertexType","getPlaceName","companies","address","split","networks","company","getCompanyForNetwork","label","name","getTransitFare","fareComponent","digits","transitFare","symbol","currencyCode","defaultFractionDigits","currency","cents","centsToString","dollars","toFixed","dollarsToString","calculateFares","itinerary","multiple","minTNCFare","maxTNCFare","tncCurrencyCode","legs","forEach","tncData","maxCost","minCost","transitFares","fare","Object","keys","fareKey","regular","transitCurrencyCode","latlngToString","latlng","lat","lng","lon","coordsToString","coords","length","map","c","join","getDetailText","location","detailText","type","id","timestamp","fromNow","summarizeQuery","query","locations","findLocationType","ls","types","match","find","l","matchLatLon","from","to","hasTransit"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;AAEA;AACA;AACA;AACA;;AACA;;AAEA;AACA;AACA;AACO,SAASA,qBAAT,CAA+BC,MAA/B,EAAuCC,WAAvC,EAAoD;AACzDC,EAAAA,OAAO,CAACC,IAAR,CACG,GAAEH,MAAM,IACP,aAAc;AACpB,UACUC,WAAW,GACN;AACf;AACA,cAAcA,WAAY,+EAHL,GAIP,EACL,EATP;AAWD,C,CAED;;;AAEO,SAASG,gBAAT,CAA0BC,IAA1B,EAAgC;AACrCN,EAAAA,qBAAqB,CAAC,kBAAD,CAArB;;AAEA,UAAQM,IAAI,CAACC,iBAAb;AACE,SAAK,QAAL;AACE,aAAQ,QAAOD,IAAI,CAACE,iBAAL,CAAuBC,WAAvB,EAAqC,EAApD;;AACF,SAAK,MAAL;AACE,aAAO,MAAP;;AACF,SAAK,WAAL;AACE,aAAO,WAAP;;AACF,SAAK,eAAL;AACE,aAAO,aAAP;;AACF,SAAK,UAAL;AACE,aAAO,UAAP;;AACF,SAAK,gBAAL;AACE,aAAO,cAAP;;AACF,SAAK,OAAL;AACE,aAAO,OAAP;;AACF,SAAK,YAAL;AACE,aAAO,YAAP;;AACF,SAAK,kBAAL;AACE,aAAO,yBAAP;;AACF,SAAK,yBAAL;AACE,aAAO,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AEEU,EAAE,GAAG,EAFP,EAGEC,KAAK,GAAG,CAAC,MAAD,EAAS,MAAT,EAAiB,WAAjB,CAHV,EAIE;AACA,UAAMC,KAAK,GAAGF,EAAE,CAACG,IAAH,CAAQC,CAAC,IAAIvE,OAAO,CAAC,OAAD,CAAP,CAAiBwE,WAAjB,CAA6BD,CAA7B,EAAgCd,QAAhC,CAAb,CAAd;AACA,WAAOY,KAAK,IAAID,KAAK,CAACrE,OAAN,CAAcsE,KAAK,CAACV,IAApB,MAA8B,CAAC,CAAxC,GAA4CU,KAAK,CAACV,IAAlD,GAAyD,IAAhE;AACD;;AAED,QAAMc,IAAI,GACRP,gBAAgB,CAACF,KAAK,CAACS,IAAP,EAAaR,SAAb,CAAhB,IAA2CD,KAAK,CAACS,IAAN,CAAW5D,IAAX,CAAgBL,KAAhB,CAAsB,GAAtB,EAA2B,CAA3B,CAD7C;AAEA,QAAMkE,EAAE,GACNR,gBAAgB,CAACF,KAAK,CAACU,EAAP,EAAWT,SAAX,CAAhB,IAAyCD,KAAK,CAACU,EAAN,CAAS7D,IAAT,CAAcL,KAAd,CAAoB,GAApB,EAAyB,CAAzB,CAD3C;AAEA,QAAMZ,IAAI,GAAGI,OAAO,CAAC,aAAD,CAAP,CAAuB2E,UAAvB,CAAkCX,KAAK,CAACpE,IAAxC,IACT,SADS,GAETI,OAAO,CAAC,aAAD,CAAP,CAAuBC,cAAvB,CAAsC+D,KAAK,CAACpE,IAA5C,CAFJ;AAGA,SAAQ,GAAEA,IAAK,SAAQ6E,IAAK,OAAMC,EAAG,EAArC;AACD","sourcesContent":["import moment from \"moment\";\n\n/**\n * To disable cyclic dependency resolution we need to require() within methods\n * This is a good reason to disable this eslint-rule\n */\n/* eslint-disable global-require */\n\n/**\n * Generates a warning to tell developer that they are using deprecated methods!\n */\nexport function logDeprecationWarning(method, alternative) {\n console.warn(\n `${method ||\n \"This method\"} is deprecated and will be removed in a future otp-ui release. All language functionality should be handled using react-intl.\n ${\n alternative\n ? `\n\n Use ${alternative} instead, which provides a new interface that doesn't return English strings.`\n : \"\"\n }`\n );\n}\n\n// itinerary.js\n\nexport function getStepDirection(step) {\n logDeprecationWarning(\"getStepDirection\");\n\n switch (step.relativeDirection) {\n case \"DEPART\":\n return `Head ${step.absoluteDirection.toLowerCase()}`;\n case \"LEFT\":\n return \"Left\";\n case \"HARD_LEFT\":\n return \"Hard left\";\n case \"SLIGHTLY_LEFT\":\n return \"Slight left\";\n case \"CONTINUE\":\n return \"Continue\";\n case \"SLIGHTLY_RIGHT\":\n return \"Slight right\";\n case \"RIGHT\":\n return \"Right\";\n case \"HARD_RIGHT\":\n return \"Hard right\";\n case \"CIRCLE_CLOCKWISE\":\n return \"Follow circle clockwise\";\n case \"CIRCLE_COUNTERCLOCKWISE\":\n return \"Follow circle counterclockwise\";\n case \"ELEVATOR\":\n return \"Take elevator\";\n case \"UTURN_LEFT\":\n return \"Left U-turn\";\n case \"UTURN_RIGHT\":\n return \"Right U-turn\";\n default:\n return step.relativeDirection;\n }\n}\n\nexport function getStepInstructions(step) {\n logDeprecationWarning(\"getStepInstructions\");\n\n const conjunction = step.relativeDirection === \"ELEVATOR\" ? \"to\" : \"on\";\n return `${getStepDirection(step)} ${conjunction} ${step.streetName}`;\n}\n\nexport function getStepStreetName(step) {\n logDeprecationWarning(\"getStepStreetName\");\n\n if (step.streetName === \"road\") return \"Unnamed Road\";\n if (step.streetName === \"path\") return \"Unnamed Path\";\n return step.streetName;\n}\n\nexport function getLegModeLabel(leg) {\n logDeprecationWarning(\"getLegModeLabel\");\n\n switch (leg.mode) {\n case \"BICYCLE_RENT\":\n return \"Biketown\";\n case \"CAR\":\n return leg.hailedCar ? \"Ride\" : \"Drive\";\n case \"GONDOLA\":\n return \"Aerial Tram\";\n case \"TRAM\":\n if (leg.routeLongName.toLowerCase().indexOf(\"streetcar\") !== -1)\n return \"Streetcar\";\n return \"Light Rail\";\n case \"MICROMOBILITY\":\n case \"SCOOTER\":\n return \"Ride\";\n default:\n return require(\"./itinerary\").toSentenceCase(leg.mode);\n }\n}\n\n/**\n * Returns mode name by checking the vertex type (VertexType class in OTP) for\n * the provided place. NOTE: this is currently only intended for vehicles at\n * the moment (not transit or walking).\n *\n * @param {string} place place from itinerary leg\n */\nexport function getModeForPlace(place) {\n logDeprecationWarning(\"getModeForPlace\");\n\n switch (place.vertexType) {\n case \"CARSHARE\":\n return \"car\";\n case \"VEHICLERENTAL\":\n return \"E-scooter\";\n // TODO: Should the type change depending on bike vertex type?\n case \"BIKESHARE\":\n case \"BIKEPARK\":\n return \"bike\";\n // If company offers more than one mode, default to `vehicle` string.\n default:\n return \"vehicle\";\n }\n}\n\nexport function getPlaceName(place, companies) {\n logDeprecationWarning(\"getPlaceName\");\n\n // If address is provided (i.e. for carshare station, use it)\n if (place.address) return place.address.split(\",\")[0];\n if (place.networks && place.vertexType === \"VEHICLERENTAL\") {\n // For vehicle rental pick up, do not use the place name. Rather, use\n // company name + vehicle type (e.g., SPIN E-scooter). Place name is often just\n // a UUID that has no relevance to the actual vehicle. For bikeshare, however,\n // there are often hubs or bikes that have relevant names to the user.\n const company = require(\"./itinerary\").getCompanyForNetwork(\n place.networks[0],\n companies\n );\n if (company) {\n return `${company.label} ${getModeForPlace(place)}`;\n }\n }\n // Default to place name\n return place.name;\n}\n\n/**\n * For a given fare component (either total fare or component parts), returns\n * an object with string formatters and the fare value (in cents).\n */\nexport function getTransitFare(fareComponent) {\n logDeprecationWarning(\"getTransitFare\", \"the fare object and getTncFare\");\n\n // Default values (if fare component is not valid).\n let digits = 2;\n let transitFare = 0;\n let symbol = \"$\";\n let currencyCode = \"USD\";\n if (fareComponent) {\n // Assign values without declaration. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_without_declaration\n ({\n currencyCode,\n defaultFractionDigits: digits,\n symbol\n } = fareComponent.currency);\n transitFare = fareComponent.cents;\n }\n // For cents to string conversion, use digits from fare component.\n const centsToString = cents => {\n const dollars = (cents / 10 ** digits).toFixed(digits);\n return `${symbol}${dollars}`;\n };\n // For dollars to string conversion, assume we're rounding to two digits.\n const dollarsToString = dollars => `${symbol}${dollars.toFixed(2)}`;\n return {\n centsToString,\n currencyCode,\n dollarsToString,\n transitFare\n };\n}\n\n/**\n * For an itinerary, calculates the transit/TNC fares and returns an object with\n * these values, currency info, as well as string formatters.\n * It is assumed that the same currency is used for transit and TNC legs.\n *\n * multiple being set to true will change the output behavior:\n * - dollarsToString and centsToString will be returned as part of each fare\n * - currencyCode will be returned separately for each fare\n * - tnc currency code will be returned separately\n * - each fare type will be returned separately within a new transitFares property\n *\n * FIXME: a new approach to fare calculation must be found:\n * the current approach is not sustainable, as centsToString and DollarsToString\n * must be replaced by i18n anyway.\n *\n * However, the current behavior should ideally be kept to avoid a breaking change.\n * The \"multiple\" mode is helpful, but only prevents tnc fare calculation from being duplicated.\n * This method could be split out into a new one, along with tnc fare calculation.\n * If this is done, the individual fare calculation should also be modified to support\n * a default fare not being called \"regular\". However, this again would be a breaking change.\n * This breaking change is avoided by adding the \"multiple\" parameter.\n *\n * When centsToString and dollarsToString are removed, this method should be split into\n * individual fare calculation on a variable fare key, fare calculation of an entire leg,\n * which will get fares for every fare key in the leg, and a method to calculate the fare of\n * a tnc ride within the leg. This will make typescripting easier, as the types will be cleaner.\n */\nexport function calculateFares(itinerary, multiple = false) {\n logDeprecationWarning(\"calculateFares\", \"the fare object and getTncFare\");\n\n // Process any TNC fares\n let minTNCFare = 0;\n let maxTNCFare = 0;\n let tncCurrencyCode;\n itinerary.legs.forEach(leg => {\n if (leg.mode === \"CAR\" && leg.hailedCar && leg.tncData) {\n const { currency, maxCost, minCost } = leg.tncData;\n // TODO: Support non-USD\n minTNCFare += minCost;\n maxTNCFare += maxCost;\n tncCurrencyCode = currency;\n }\n });\n\n if (multiple) {\n // Return object of fares\n const transitFares = {};\n if (itinerary && itinerary.fare && itinerary.fare.fare) {\n Object.keys(itinerary.fare.fare).forEach(fareKey => {\n const fareComponent = itinerary.fare.fare[fareKey];\n transitFares[fareKey] = getTransitFare(fareComponent);\n });\n }\n\n return {\n maxTNCFare,\n minTNCFare,\n tncCurrencyCode,\n transitFares\n };\n }\n\n // Extract fare total from itinerary fares.\n const fareComponent =\n itinerary.fare && itinerary.fare.fare && itinerary.fare.fare.regular;\n // Get string formatters and itinerary fare.\n const {\n centsToString,\n currencyCode: transitCurrencyCode,\n dollarsToString,\n transitFare\n } = getTransitFare(fareComponent);\n\n return {\n centsToString,\n currencyCode: transitCurrencyCode || tncCurrencyCode,\n dollarsToString,\n maxTNCFare,\n minTNCFare,\n transitFare\n };\n}\n\n// map.js\n\nexport function latlngToString(latlng) {\n logDeprecationWarning(\"latlngToString\", \"the latlng object\");\n\n return (\n latlng &&\n `${latlng.lat.toFixed(5)}, ${(latlng.lng || latlng.lon).toFixed(5)}`\n );\n}\n\nexport function coordsToString(coords) {\n logDeprecationWarning(\"coordsToString\", \"the coords object\");\n\n return coords.length && coords.map(c => (+c).toFixed(5)).join(\", \");\n}\n\nexport function getDetailText(location) {\n let detailText;\n if (location.type === \"home\" || location.type === \"work\") {\n detailText = location.name;\n }\n if (location.type === \"stop\") {\n detailText = location.id;\n } else if (location.type === \"recent\" && location.timestamp) {\n detailText = moment(location.timestamp).fromNow();\n }\n return detailText;\n}\n\n// query.js\n\nexport function summarizeQuery(query, locations = []) {\n logDeprecationWarning(\"summarizeQuery\");\n\n function findLocationType(\n location,\n ls = [],\n types = [\"home\", \"work\", \"suggested\"]\n ) {\n const match = ls.find(l => require(\"./map\").matchLatLon(l, location));\n return match && types.indexOf(match.type) !== -1 ? match.type : null;\n }\n\n const from =\n findLocationType(query.from, locations) || query.from.name.split(\",\")[0];\n const to =\n findLocationType(query.to, locations) || query.to.name.split(\",\")[0];\n const mode = require(\"./itinerary\").hasTransit(query.mode)\n ? \"Transit\"\n : require(\"./itinerary\").toSentenceCase(query.mode);\n return `${mode} from ${from} to ${to}`;\n}\n"],"file":"deprecated.js"}
1
+ {"version":3,"sources":["../src/deprecated.js"],"names":["logDeprecationWarning","method","alternative","console","warn","getStepDirection","step","relativeDirection","absoluteDirection","toLowerCase","getStepInstructions","conjunction","streetName","getStepStreetName","getLegModeLabel","leg","mode","hailedCar","routeLongName","indexOf","require","toSentenceCase","getModeForPlace","place","vertexType","getPlaceName","companies","address","split","networks","company","getCompanyForNetwork","label","name","getTransitFare","fareComponent","digits","transitFare","symbol","currencyCode","defaultFractionDigits","currency","cents","centsToString","dollars","toFixed","dollarsToString","calculateFares","itinerary","multiple","minTNCFare","maxTNCFare","tncCurrencyCode","legs","forEach","tncData","maxCost","minCost","transitFares","fare","Object","keys","fareKey","regular","transitCurrencyCode","latlngToString","latlng","lat","lng","lon","coordsToString","coords","length","map","c","join","getDetailText","location","detailText","type","id","timestamp","fromNow","summarizeQuery","query","locations","findLocationType","ls","types","match","find","l","matchLatLon","from","to","hasTransit","getTimeZoneOffset","dstOffset","Date","startTime","getTimezoneOffset","agencyTimeZoneOffset"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;;AAEA;AACA;AACA;AACA;;AACA;;AAEA;AACA;AACA;AACO,SAASA,qBAAT,CAA+BC,MAA/B,EAAuCC,WAAvC,EAAoD;AACzDC,EAAAA,OAAO,CAACC,IAAR,CACG,GAAEH,MAAM,IACP,aAAc;AACpB,UACUC,WAAW,GACN;AACf;AACA,cAAcA,WAAY,+EAHL,GAIP,EACL,EATP;AAWD,C,CAED;;;AAEO,SAASG,gBAAT,CAA0BC,IAA1B,EAAgC;AACrCN,EAAAA,qBAAqB,CAAC,kBAAD,CAArB;;AAEA,UAAQM,IAAI,CAACC,iBAAb;AACE,SAAK,QAAL;AACE,aAAQ,QAAOD,IAAI,CAACE,iBAAL,CAAuBC,WAAvB,EAAqC,EAApD;;AACF,SAAK,MAAL;AACE,aAAO,MAAP;;AACF,SAAK,WAAL;AACE,aAAO,WAAP;;AACF,SAAK,eAAL;AACE,aAAO,aAAP;;AACF,SAAK,UAAL;AACE,aAAO,UAAP;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CAArB;AAEA,MAAI,CAACgD,SAAS,CAACK,IAAX,IAAmB,CAACL,SAAS,CAACK,IAAV,CAAemB,MAAvC,EAA+C,OAAO,CAAP,CAHJ,CAK3C;;AACA,QAAMyB,SAAS,GACb,IAAIC,IAAJ,CAASlD,SAAS,CAACmD,SAAnB,EAA8BC,iBAA9B,KACA,IAAIF,IAAJ,GAAWE,iBAAX,EAFF;AAIA,SACEpD,SAAS,CAACK,IAAV,CAAe,CAAf,EAAkBgD,oBAAlB,GACA,CAAC,IAAIH,IAAJ,GAAWE,iBAAX,KAAiCH,SAAlC,IAA+C,KAFjD;AAID","sourcesContent":["import moment from \"moment\";\n\n/**\n * To disable cyclic dependency resolution we need to require() within methods\n * This is a good reason to disable this eslint-rule\n */\n/* eslint-disable global-require */\n\n/**\n * Generates a warning to tell developer that they are using deprecated methods!\n */\nexport function logDeprecationWarning(method, alternative) {\n console.warn(\n `${method ||\n \"This method\"} is deprecated and will be removed in a future otp-ui release. All language functionality should be handled using react-intl.\n ${\n alternative\n ? `\n\n Use ${alternative} instead, which provides a new interface that doesn't return English strings.`\n : \"\"\n }`\n );\n}\n\n// itinerary.js\n\nexport function getStepDirection(step) {\n logDeprecationWarning(\"getStepDirection\");\n\n switch (step.relativeDirection) {\n case \"DEPART\":\n return `Head ${step.absoluteDirection.toLowerCase()}`;\n case \"LEFT\":\n return \"Left\";\n case \"HARD_LEFT\":\n return \"Hard left\";\n case \"SLIGHTLY_LEFT\":\n return \"Slight left\";\n case \"CONTINUE\":\n return \"Continue\";\n case \"SLIGHTLY_RIGHT\":\n return \"Slight right\";\n case \"RIGHT\":\n return \"Right\";\n case \"HARD_RIGHT\":\n return \"Hard right\";\n case \"CIRCLE_CLOCKWISE\":\n return \"Follow circle clockwise\";\n case \"CIRCLE_COUNTERCLOCKWISE\":\n return \"Follow circle counterclockwise\";\n case \"ELEVATOR\":\n return \"Take elevator\";\n case \"UTURN_LEFT\":\n return \"Left U-turn\";\n case \"UTURN_RIGHT\":\n return \"Right U-turn\";\n default:\n return step.relativeDirection;\n }\n}\n\nexport function getStepInstructions(step) {\n logDeprecationWarning(\"getStepInstructions\");\n\n const conjunction = step.relativeDirection === \"ELEVATOR\" ? \"to\" : \"on\";\n return `${getStepDirection(step)} ${conjunction} ${step.streetName}`;\n}\n\nexport function getStepStreetName(step) {\n logDeprecationWarning(\"getStepStreetName\");\n\n if (step.streetName === \"road\") return \"Unnamed Road\";\n if (step.streetName === \"path\") return \"Unnamed Path\";\n return step.streetName;\n}\n\nexport function getLegModeLabel(leg) {\n logDeprecationWarning(\"getLegModeLabel\");\n\n switch (leg.mode) {\n case \"BICYCLE_RENT\":\n return \"Biketown\";\n case \"CAR\":\n return leg.hailedCar ? \"Ride\" : \"Drive\";\n case \"GONDOLA\":\n return \"Aerial Tram\";\n case \"TRAM\":\n if (leg.routeLongName.toLowerCase().indexOf(\"streetcar\") !== -1)\n return \"Streetcar\";\n return \"Light Rail\";\n case \"MICROMOBILITY\":\n case \"SCOOTER\":\n return \"Ride\";\n default:\n return require(\"./itinerary\").toSentenceCase(leg.mode);\n }\n}\n\n/**\n * Returns mode name by checking the vertex type (VertexType class in OTP) for\n * the provided place. NOTE: this is currently only intended for vehicles at\n * the moment (not transit or walking).\n *\n * @param {string} place place from itinerary leg\n */\nexport function getModeForPlace(place) {\n logDeprecationWarning(\"getModeForPlace\");\n\n switch (place.vertexType) {\n case \"CARSHARE\":\n return \"car\";\n case \"VEHICLERENTAL\":\n return \"E-scooter\";\n // TODO: Should the type change depending on bike vertex type?\n case \"BIKESHARE\":\n case \"BIKEPARK\":\n return \"bike\";\n // If company offers more than one mode, default to `vehicle` string.\n default:\n return \"vehicle\";\n }\n}\n\nexport function getPlaceName(place, companies) {\n logDeprecationWarning(\"getPlaceName\");\n\n // If address is provided (i.e. for carshare station, use it)\n if (place.address) return place.address.split(\",\")[0];\n if (place.networks && place.vertexType === \"VEHICLERENTAL\") {\n // For vehicle rental pick up, do not use the place name. Rather, use\n // company name + vehicle type (e.g., SPIN E-scooter). Place name is often just\n // a UUID that has no relevance to the actual vehicle. For bikeshare, however,\n // there are often hubs or bikes that have relevant names to the user.\n const company = require(\"./itinerary\").getCompanyForNetwork(\n place.networks[0],\n companies\n );\n if (company) {\n return `${company.label} ${getModeForPlace(place)}`;\n }\n }\n // Default to place name\n return place.name;\n}\n\n/**\n * For a given fare component (either total fare or component parts), returns\n * an object with string formatters and the fare value (in cents).\n */\nexport function getTransitFare(fareComponent) {\n logDeprecationWarning(\"getTransitFare\", \"the fare object and getTncFare\");\n\n // Default values (if fare component is not valid).\n let digits = 2;\n let transitFare = 0;\n let symbol = \"$\";\n let currencyCode = \"USD\";\n if (fareComponent) {\n // Assign values without declaration. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_without_declaration\n ({\n currencyCode,\n defaultFractionDigits: digits,\n symbol\n } = fareComponent.currency);\n transitFare = fareComponent.cents;\n }\n // For cents to string conversion, use digits from fare component.\n const centsToString = cents => {\n const dollars = (cents / 10 ** digits).toFixed(digits);\n return `${symbol}${dollars}`;\n };\n // For dollars to string conversion, assume we're rounding to two digits.\n const dollarsToString = dollars => `${symbol}${dollars.toFixed(2)}`;\n return {\n centsToString,\n currencyCode,\n dollarsToString,\n transitFare\n };\n}\n\n/**\n * For an itinerary, calculates the transit/TNC fares and returns an object with\n * these values, currency info, as well as string formatters.\n * It is assumed that the same currency is used for transit and TNC legs.\n *\n * multiple being set to true will change the output behavior:\n * - dollarsToString and centsToString will be returned as part of each fare\n * - currencyCode will be returned separately for each fare\n * - tnc currency code will be returned separately\n * - each fare type will be returned separately within a new transitFares property\n *\n * FIXME: a new approach to fare calculation must be found:\n * the current approach is not sustainable, as centsToString and DollarsToString\n * must be replaced by i18n anyway.\n *\n * However, the current behavior should ideally be kept to avoid a breaking change.\n * The \"multiple\" mode is helpful, but only prevents tnc fare calculation from being duplicated.\n * This method could be split out into a new one, along with tnc fare calculation.\n * If this is done, the individual fare calculation should also be modified to support\n * a default fare not being called \"regular\". However, this again would be a breaking change.\n * This breaking change is avoided by adding the \"multiple\" parameter.\n *\n * When centsToString and dollarsToString are removed, this method should be split into\n * individual fare calculation on a variable fare key, fare calculation of an entire leg,\n * which will get fares for every fare key in the leg, and a method to calculate the fare of\n * a tnc ride within the leg. This will make typescripting easier, as the types will be cleaner.\n */\nexport function calculateFares(itinerary, multiple = false) {\n logDeprecationWarning(\"calculateFares\", \"the fare object and getTncFare\");\n\n // Process any TNC fares\n let minTNCFare = 0;\n let maxTNCFare = 0;\n let tncCurrencyCode;\n itinerary.legs.forEach(leg => {\n if (leg.mode === \"CAR\" && leg.hailedCar && leg.tncData) {\n const { currency, maxCost, minCost } = leg.tncData;\n // TODO: Support non-USD\n minTNCFare += minCost;\n maxTNCFare += maxCost;\n tncCurrencyCode = currency;\n }\n });\n\n if (multiple) {\n // Return object of fares\n const transitFares = {};\n if (itinerary && itinerary.fare && itinerary.fare.fare) {\n Object.keys(itinerary.fare.fare).forEach(fareKey => {\n const fareComponent = itinerary.fare.fare[fareKey];\n transitFares[fareKey] = getTransitFare(fareComponent);\n });\n }\n\n return {\n maxTNCFare,\n minTNCFare,\n tncCurrencyCode,\n transitFares\n };\n }\n\n // Extract fare total from itinerary fares.\n const fareComponent =\n itinerary.fare && itinerary.fare.fare && itinerary.fare.fare.regular;\n // Get string formatters and itinerary fare.\n const {\n centsToString,\n currencyCode: transitCurrencyCode,\n dollarsToString,\n transitFare\n } = getTransitFare(fareComponent);\n\n return {\n centsToString,\n currencyCode: transitCurrencyCode || tncCurrencyCode,\n dollarsToString,\n maxTNCFare,\n minTNCFare,\n transitFare\n };\n}\n\n// map.js\n\nexport function latlngToString(latlng) {\n logDeprecationWarning(\"latlngToString\", \"the latlng object\");\n\n return (\n latlng &&\n `${latlng.lat.toFixed(5)}, ${(latlng.lng || latlng.lon).toFixed(5)}`\n );\n}\n\nexport function coordsToString(coords) {\n logDeprecationWarning(\"coordsToString\", \"the coords object\");\n\n return coords.length && coords.map(c => (+c).toFixed(5)).join(\", \");\n}\n\nexport function getDetailText(location) {\n let detailText;\n if (location.type === \"home\" || location.type === \"work\") {\n detailText = location.name;\n }\n if (location.type === \"stop\") {\n detailText = location.id;\n } else if (location.type === \"recent\" && location.timestamp) {\n detailText = moment(location.timestamp).fromNow();\n }\n return detailText;\n}\n\n// query.js\n\nexport function summarizeQuery(query, locations = []) {\n logDeprecationWarning(\"summarizeQuery\");\n\n function findLocationType(\n location,\n ls = [],\n types = [\"home\", \"work\", \"suggested\"]\n ) {\n const match = ls.find(l => require(\"./map\").matchLatLon(l, location));\n return match && types.indexOf(match.type) !== -1 ? match.type : null;\n }\n\n const from =\n findLocationType(query.from, locations) || query.from.name.split(\",\")[0];\n const to =\n findLocationType(query.to, locations) || query.to.name.split(\",\")[0];\n const mode = require(\"./itinerary\").hasTransit(query.mode)\n ? \"Transit\"\n : require(\"./itinerary\").toSentenceCase(query.mode);\n return `${mode} from ${from} to ${to}`;\n}\n\nexport function getTimeZoneOffset(itinerary) {\n logDeprecationWarning(\"getTimeZoneOffset\");\n\n if (!itinerary.legs || !itinerary.legs.length) return 0;\n\n // Determine if there is a DST offset between now and the itinerary start date\n const dstOffset =\n new Date(itinerary.startTime).getTimezoneOffset() -\n new Date().getTimezoneOffset();\n\n return (\n itinerary.legs[0].agencyTimeZoneOffset +\n (new Date().getTimezoneOffset() + dstOffset) * 60000\n );\n}\n"],"file":"deprecated.js"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import * as itinerary from "./itinerary";
2
+ import * as map from "./map";
3
+ import * as route from "./route";
4
+ import * as storage from "./storage";
5
+ import * as time from "./time";
6
+ import * as ui from "./ui";
7
+ declare const core: {
8
+ itinerary: typeof itinerary;
9
+ map: typeof map;
10
+ profile: any;
11
+ query: any;
12
+ queryParams: any;
13
+ route: typeof route;
14
+ storage: typeof storage;
15
+ time: typeof time;
16
+ ui: typeof ui;
17
+ };
18
+ export default core;
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,GAAG,MAAM,OAAO,CAAC;AAI7B,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,MAAM,CAAC;AAE3B,QAAA,MAAM,IAAI;;;;;;;;;;CAUT,CAAC;AAEF,eAAe,IAAI,CAAC"}
package/lib/index.js CHANGED
@@ -9,8 +9,6 @@ var itinerary = _interopRequireWildcard(require("./itinerary"));
9
9
 
10
10
  var map = _interopRequireWildcard(require("./map"));
11
11
 
12
- var messages = _interopRequireWildcard(require("./messages"));
13
-
14
12
  var profile = _interopRequireWildcard(require("./profile"));
15
13
 
16
14
  var query = _interopRequireWildcard(require("./query"));
@@ -23,8 +21,6 @@ var storage = _interopRequireWildcard(require("./storage"));
23
21
 
24
22
  var time = _interopRequireWildcard(require("./time"));
25
23
 
26
- var types = _interopRequireWildcard(require("./types"));
27
-
28
24
  var ui = _interopRequireWildcard(require("./ui"));
29
25
 
30
26
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
@@ -34,14 +30,12 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj &&
34
30
  const core = {
35
31
  itinerary,
36
32
  map,
37
- messages,
38
33
  profile,
39
34
  query,
40
35
  queryParams,
41
36
  route,
42
37
  storage,
43
38
  time,
44
- types,
45
39
  ui
46
40
  };
47
41
  var _default = core;
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["core","itinerary","map","messages","profile","query","queryParams","route","storage","time","types","ui"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;AAEA,MAAMA,IAAI,GAAG;AACXC,EAAAA,SADW;AAEXC,EAAAA,GAFW;AAGXC,EAAAA,QAHW;AAIXC,EAAAA,OAJW;AAKXC,EAAAA,KALW;AAMXC,EAAAA,WANW;AAOXC,EAAAA,KAPW;AAQXC,EAAAA,OARW;AASXC,EAAAA,IATW;AAUXC,EAAAA,KAVW;AAWXC,EAAAA;AAXW,CAAb;eAceX,I","sourcesContent":["import * as itinerary from \"./itinerary\";\nimport * as map from \"./map\";\nimport * as messages from \"./messages\";\nimport * as profile from \"./profile\";\nimport * as query from \"./query\";\nimport * as queryParams from \"./query-params\";\nimport * as route from \"./route\";\nimport * as storage from \"./storage\";\nimport * as time from \"./time\";\nimport * as types from \"./types\";\nimport * as ui from \"./ui\";\n\nconst core = {\n itinerary,\n map,\n messages,\n profile,\n query,\n queryParams,\n route,\n storage,\n time,\n types,\n ui\n};\n\nexport default core;\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["core","itinerary","map","profile","query","queryParams","route","storage","time","ui"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;AAEA,MAAMA,IAAI,GAAG;AACXC,EAAAA,SADW;AAEXC,EAAAA,GAFW;AAGXC,EAAAA,OAHW;AAIXC,EAAAA,KAJW;AAKXC,EAAAA,WALW;AAMXC,EAAAA,KANW;AAOXC,EAAAA,OAPW;AAQXC,EAAAA,IARW;AASXC,EAAAA;AATW,CAAb;eAYeT,I","sourcesContent":["import * as itinerary from \"./itinerary\";\nimport * as map from \"./map\";\nimport * as profile from \"./profile\";\nimport * as query from \"./query\";\nimport * as queryParams from \"./query-params\";\nimport * as route from \"./route\";\nimport * as storage from \"./storage\";\nimport * as time from \"./time\";\nimport * as ui from \"./ui\";\n\nconst core = {\n itinerary,\n map,\n profile,\n query,\n queryParams,\n route,\n storage,\n time,\n ui\n};\n\nexport default core;\n"],"file":"index.js"}