@wener/common 2.0.2 → 2.0.3
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.
- package/lib/ai/qwen3vl/index.js +2 -0
- package/lib/ai/qwen3vl/index.js.map +1 -0
- package/lib/ai/qwen3vl/utils.js +31 -0
- package/lib/ai/qwen3vl/utils.js.map +1 -0
- package/lib/ai/vision/DocLayoutElementTypeSchema.js +28 -0
- package/lib/ai/vision/DocLayoutElementTypeSchema.js.map +1 -0
- package/lib/ai/vision/ImageAnnotationSchema.js +50 -0
- package/lib/ai/vision/ImageAnnotationSchema.js.map +1 -0
- package/lib/ai/vision/index.js +3 -0
- package/lib/ai/vision/index.js.map +1 -0
- package/lib/ai/vision/resolveImageAnnotation.js +105 -0
- package/lib/ai/vision/resolveImageAnnotation.js.map +1 -0
- package/lib/cn/ChineseResidentIdNo.js +21 -14
- package/lib/cn/ChineseResidentIdNo.js.map +1 -0
- package/lib/cn/ChineseResidentIdNo.test.js +1 -1
- package/lib/cn/DivisionCode.js +30 -25
- package/lib/cn/DivisionCode.js.map +1 -0
- package/lib/cn/DivisionCode.test.js +1 -1
- package/lib/cn/Mod11.js +38 -81
- package/lib/cn/Mod11.js.map +1 -0
- package/lib/cn/Mod31.js +41 -90
- package/lib/cn/Mod31.js.map +1 -0
- package/lib/cn/UnifiedSocialCreditCode.js +43 -34
- package/lib/cn/UnifiedSocialCreditCode.js.map +1 -0
- package/lib/cn/UnifiedSocialCreditCode.test.js +1 -1
- package/lib/cn/formatChineseAmount.js +77 -0
- package/lib/cn/formatChineseAmount.js.map +1 -0
- package/lib/cn/index.js +7 -1
- package/lib/cn/index.js.map +1 -0
- package/lib/cn/parseChineseNumber.js +94 -0
- package/lib/cn/parseChineseNumber.js.map +1 -0
- package/lib/cn/parseChineseNumber.test.js +278 -0
- package/lib/cn/pinyin/cartesianProduct.js +22 -0
- package/lib/cn/pinyin/cartesianProduct.js.map +1 -0
- package/lib/cn/pinyin/cartesianProduct.test.js +179 -0
- package/lib/cn/pinyin/data.json +23573 -0
- package/lib/cn/pinyin/loader.js +14 -0
- package/lib/cn/pinyin/loader.js.map +1 -0
- package/lib/cn/pinyin/preload.js +3 -0
- package/lib/cn/pinyin/preload.js.map +1 -0
- package/lib/cn/pinyin/toPinyin.test.js +167 -0
- package/lib/cn/pinyin/toPinyinPure.js +33 -0
- package/lib/cn/pinyin/toPinyinPure.js.map +1 -0
- package/lib/cn/pinyin/transform.js +14 -0
- package/lib/cn/pinyin/transform.js.map +1 -0
- package/lib/cn/types.d.js +2 -0
- package/lib/cn/types.d.js.map +1 -0
- package/lib/consola/createStandardConsolaReporter.js +6 -6
- package/lib/consola/createStandardConsolaReporter.js.map +1 -0
- package/lib/consola/formatLogObject.js +65 -145
- package/lib/consola/formatLogObject.js.map +1 -0
- package/lib/consola/formatLogObject.test.js +184 -0
- package/lib/consola/index.js +1 -0
- package/lib/consola/index.js.map +1 -0
- package/lib/data/formatSort.js +6 -5
- package/lib/data/formatSort.js.map +1 -0
- package/lib/data/index.js +1 -0
- package/lib/data/index.js.map +1 -0
- package/lib/data/maybeNumber.js +5 -7
- package/lib/data/maybeNumber.js.map +1 -0
- package/lib/data/parseSort.js +22 -28
- package/lib/data/parseSort.js.map +1 -0
- package/lib/data/resolvePagination.js +13 -17
- package/lib/data/resolvePagination.js.map +1 -0
- package/lib/data/types.d.js +2 -0
- package/lib/data/types.d.js.map +1 -0
- package/lib/dayjs/dayjs.js +21 -19
- package/lib/dayjs/dayjs.js.map +1 -0
- package/lib/dayjs/formatDuration.js +15 -14
- package/lib/dayjs/formatDuration.js.map +1 -0
- package/lib/dayjs/index.js +2 -0
- package/lib/dayjs/index.js.map +1 -0
- package/lib/dayjs/parseDuration.js +5 -8
- package/lib/dayjs/parseDuration.js.map +1 -0
- package/lib/dayjs/parseRelativeTime.js +90 -0
- package/lib/dayjs/parseRelativeTime.js.map +1 -0
- package/lib/dayjs/parseRelativeTime.test.js +247 -0
- package/lib/dayjs/resolveRelativeTime.js +158 -0
- package/lib/dayjs/resolveRelativeTime.js.map +1 -0
- package/lib/dayjs/resolveRelativeTime.test.js +310 -0
- package/lib/decimal/index.js +1 -0
- package/lib/decimal/index.js.map +1 -0
- package/lib/decimal/parseDecimal.js +3 -1
- package/lib/decimal/parseDecimal.js.map +1 -0
- package/lib/emittery/emitter.js +10 -0
- package/lib/emittery/emitter.js.map +1 -0
- package/lib/emittery/index.js +2 -0
- package/lib/emittery/index.js.map +1 -0
- package/lib/foundation/schema/SexType.js +5 -3
- package/lib/foundation/schema/SexType.js.map +1 -0
- package/lib/foundation/schema/index.js +1 -0
- package/lib/foundation/schema/index.js.map +1 -0
- package/lib/foundation/schema/parseSexType.js +1 -0
- package/lib/foundation/schema/parseSexType.js.map +1 -0
- package/lib/foundation/schema/types.js +4 -2
- package/lib/foundation/schema/types.js.map +1 -0
- package/lib/fs/FileSystemError.js +23 -0
- package/lib/fs/FileSystemError.js.map +1 -0
- package/lib/fs/IFileSystem.d.js +3 -0
- package/lib/fs/IFileSystem.d.js.map +1 -0
- package/lib/fs/MemoryFileSystem.test.js +188 -0
- package/lib/fs/createBrowserFileSystem.js +248 -0
- package/lib/fs/createBrowserFileSystem.js.map +1 -0
- package/lib/fs/createMemoryFileSystem.js +516 -0
- package/lib/fs/createMemoryFileSystem.js.map +1 -0
- package/lib/fs/createSandboxFileSystem.js +108 -0
- package/lib/fs/createSandboxFileSystem.js.map +1 -0
- package/lib/fs/createWebDavFileSystem.js +137 -0
- package/lib/fs/createWebDavFileSystem.js.map +1 -0
- package/lib/fs/findMimeType.js +17 -0
- package/lib/fs/findMimeType.js.map +1 -0
- package/lib/fs/index.js +8 -0
- package/lib/fs/index.js.map +1 -0
- package/lib/fs/orpc/FileSystemContract.js +93 -0
- package/lib/fs/orpc/FileSystemContract.js.map +1 -0
- package/lib/fs/orpc/createContractClientFileSystem.js +93 -0
- package/lib/fs/orpc/createContractClientFileSystem.js.map +1 -0
- package/lib/fs/orpc/index.js +3 -0
- package/lib/fs/orpc/index.js.map +1 -0
- package/lib/fs/orpc/server/createFileSystemContractImpl.js +63 -0
- package/lib/fs/orpc/server/createFileSystemContractImpl.js.map +1 -0
- package/lib/fs/orpc/server/index.js +2 -0
- package/lib/fs/orpc/server/index.js.map +1 -0
- package/lib/fs/s3/createS3MiniFileSystem.js +705 -0
- package/lib/fs/s3/createS3MiniFileSystem.js.map +1 -0
- package/lib/fs/s3/index.js +2 -0
- package/lib/fs/s3/index.js.map +1 -0
- package/lib/fs/s3/s3mini.test.js +584 -0
- package/lib/fs/scandir.js +59 -0
- package/lib/fs/scandir.js.map +1 -0
- package/lib/fs/server/createDatabaseFileSystem.js +750 -0
- package/lib/fs/server/createDatabaseFileSystem.js.map +1 -0
- package/lib/fs/server/createNodeFileSystem.js +401 -0
- package/lib/fs/server/createNodeFileSystem.js.map +1 -0
- package/lib/fs/server/dbfs.test.js +221 -0
- package/lib/fs/server/index.js +2 -0
- package/lib/fs/server/index.js.map +1 -0
- package/lib/fs/server/loadTestDatabase.js +127 -0
- package/lib/fs/server/loadTestDatabase.js.map +1 -0
- package/lib/fs/tests/runFileSystemTest.js +318 -0
- package/lib/fs/tests/runFileSystemTest.js.map +1 -0
- package/lib/fs/types.js +27 -0
- package/lib/fs/types.js.map +1 -0
- package/lib/fs/utils/getFileUrl.js +35 -0
- package/lib/fs/utils/getFileUrl.js.map +1 -0
- package/lib/fs/utils.js +22 -0
- package/lib/fs/utils.js.map +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -0
- package/lib/jsonschema/JsonSchema.js +146 -172
- package/lib/jsonschema/JsonSchema.js.map +1 -0
- package/lib/jsonschema/forEachJsonSchema.js +44 -0
- package/lib/jsonschema/forEachJsonSchema.js.map +1 -0
- package/lib/jsonschema/index.js +2 -0
- package/lib/jsonschema/index.js.map +1 -0
- package/lib/jsonschema/types.d.js +2 -0
- package/lib/jsonschema/types.d.js.map +1 -0
- package/lib/meta/defineFileType.js +20 -103
- package/lib/meta/defineFileType.js.map +1 -0
- package/lib/meta/defineInit.js +31 -250
- package/lib/meta/defineInit.js.map +1 -0
- package/lib/meta/defineMetadata.js +24 -140
- package/lib/meta/defineMetadata.js.map +1 -0
- package/lib/meta/index.js +1 -0
- package/lib/meta/index.js.map +1 -0
- package/lib/orpc/createOpenApiContractClient.js +27 -0
- package/lib/orpc/createOpenApiContractClient.js.map +1 -0
- package/lib/orpc/createRpcContractClient.js +34 -0
- package/lib/orpc/createRpcContractClient.js.map +1 -0
- package/lib/orpc/index.js +3 -0
- package/lib/orpc/index.js.map +1 -0
- package/lib/orpc/resolveLinkPlugins.js +28 -0
- package/lib/orpc/resolveLinkPlugins.js.map +1 -0
- package/lib/password/PHC.js +63 -87
- package/lib/password/PHC.js.map +1 -0
- package/lib/password/PHC.test.js +11 -3
- package/lib/password/Password.js +29 -294
- package/lib/password/Password.js.map +1 -0
- package/lib/password/Password.test.js +35 -22
- package/lib/password/createArgon2PasswordAlgorithm.js +35 -191
- package/lib/password/createArgon2PasswordAlgorithm.js.map +1 -0
- package/lib/password/createBase64PasswordAlgorithm.js +8 -141
- package/lib/password/createBase64PasswordAlgorithm.js.map +1 -0
- package/lib/password/createBcryptPasswordAlgorithm.js +13 -168
- package/lib/password/createBcryptPasswordAlgorithm.js.map +1 -0
- package/lib/password/createPBKDF2PasswordAlgorithm.js +46 -228
- package/lib/password/createPBKDF2PasswordAlgorithm.js.map +1 -0
- package/lib/password/createScryptPasswordAlgorithm.js +55 -211
- package/lib/password/createScryptPasswordAlgorithm.js.map +1 -0
- package/lib/password/index.js +1 -0
- package/lib/password/index.js.map +1 -0
- package/lib/password/server/index.js +1 -0
- package/lib/password/server/index.js.map +1 -0
- package/lib/resource/Identifiable.js +2 -0
- package/lib/resource/Identifiable.js.map +1 -0
- package/lib/resource/ListQuery.js +21 -93
- package/lib/resource/ListQuery.js.map +1 -0
- package/lib/resource/getTitleOfResource.js +3 -5
- package/lib/resource/getTitleOfResource.js.map +1 -0
- package/lib/resource/index.js +1 -0
- package/lib/resource/index.js.map +1 -0
- package/lib/resource/schema/AnyResourceSchema.js +2 -1
- package/lib/resource/schema/AnyResourceSchema.js.map +1 -0
- package/lib/resource/schema/BaseResourceSchema.js +2 -1
- package/lib/resource/schema/BaseResourceSchema.js.map +1 -0
- package/lib/resource/schema/ResourceActionType.js +6 -4
- package/lib/resource/schema/ResourceActionType.js.map +1 -0
- package/lib/resource/schema/ResourceStatus.js +5 -3
- package/lib/resource/schema/ResourceStatus.js.map +1 -0
- package/lib/resource/schema/ResourceType.js +5 -3
- package/lib/resource/schema/ResourceType.js.map +1 -0
- package/lib/resource/schema/index.js +1 -0
- package/lib/resource/schema/index.js.map +1 -0
- package/lib/resource/schema/types.js +16 -20
- package/lib/resource/schema/types.js.map +1 -0
- package/lib/s3/formatS3Url.js +65 -0
- package/lib/s3/formatS3Url.js.map +1 -0
- package/lib/s3/formatS3Url.test.js +262 -0
- package/lib/s3/index.js +3 -0
- package/lib/s3/index.js.map +1 -0
- package/lib/s3/parseS3Url.js +65 -0
- package/lib/s3/parseS3Url.js.map +1 -0
- package/lib/s3/parseS3Url.test.js +270 -0
- package/lib/schema/SchemaRegistry.js +38 -38
- package/lib/schema/SchemaRegistry.js.map +1 -0
- package/lib/schema/TypeSchema.d.js +2 -0
- package/lib/schema/TypeSchema.d.js.map +1 -0
- package/lib/schema/createSchemaData.js +26 -125
- package/lib/schema/createSchemaData.js.map +1 -0
- package/lib/schema/findJsonSchemaByPath.js +13 -36
- package/lib/schema/findJsonSchemaByPath.js.map +1 -0
- package/lib/schema/formatZodError.js +140 -0
- package/lib/schema/formatZodError.js.map +1 -0
- package/lib/schema/formatZodError.test.js +196 -0
- package/lib/schema/getSchemaCache.js +5 -5
- package/lib/schema/getSchemaCache.js.map +1 -0
- package/lib/schema/getSchemaOptions.js +8 -11
- package/lib/schema/getSchemaOptions.js.map +1 -0
- package/lib/schema/index.js +2 -1
- package/lib/schema/index.js.map +1 -0
- package/lib/schema/toJsonSchema.js +47 -290
- package/lib/schema/toJsonSchema.js.map +1 -0
- package/lib/schema/validate.js +33 -45
- package/lib/schema/validate.js.map +1 -0
- package/lib/tools/generateSchema.js +39 -197
- package/lib/tools/generateSchema.js.map +1 -0
- package/lib/tools/renderJsonSchemaToMarkdownDoc.js +55 -143
- package/lib/tools/renderJsonSchemaToMarkdownDoc.js.map +1 -0
- package/lib/utils/buildBaseUrl.js +13 -0
- package/lib/utils/buildBaseUrl.js.map +1 -0
- package/lib/utils/buildRedactorFormSchema.js +59 -0
- package/lib/utils/buildRedactorFormSchema.js.map +1 -0
- package/lib/utils/getEstimateProcessTime.js +12 -11
- package/lib/utils/getEstimateProcessTime.js.map +1 -0
- package/lib/utils/index.js +3 -0
- package/lib/utils/index.js.map +1 -0
- package/lib/utils/resolveFeatureOptions.js +12 -0
- package/lib/utils/resolveFeatureOptions.js.map +1 -0
- package/package.json +61 -13
- package/src/ai/qwen3vl/index.ts +1 -0
- package/src/ai/qwen3vl/utils.ts +36 -0
- package/src/ai/vision/DocLayoutElementTypeSchema.ts +30 -0
- package/src/ai/vision/ImageAnnotationSchema.ts +60 -0
- package/src/ai/vision/index.ts +2 -0
- package/src/ai/vision/resolveImageAnnotation.ts +135 -0
- package/src/cn/ChineseResidentIdNo.test.ts +1 -1
- package/src/cn/ChineseResidentIdNo.ts +8 -0
- package/src/cn/DivisionCode.test.ts +1 -1
- package/src/cn/DivisionCode.ts +8 -0
- package/src/cn/UnifiedSocialCreditCode.test.ts +1 -1
- package/src/cn/UnifiedSocialCreditCode.ts +15 -0
- package/src/cn/__snapshots__/UnifiedSocialCreditCode.test.ts.snap +23 -0
- package/src/cn/formatChineseAmount.ts +61 -0
- package/src/cn/index.ts +7 -1
- package/src/cn/parseChineseNumber.test.ts +159 -0
- package/src/cn/parseChineseNumber.ts +97 -0
- package/src/cn/pinyin/cartesianProduct.test.ts +64 -0
- package/src/cn/pinyin/cartesianProduct.ts +24 -0
- package/src/cn/pinyin/data.json +23573 -0
- package/src/cn/pinyin/loader.ts +12 -0
- package/src/cn/pinyin/preload.ts +3 -0
- package/src/cn/pinyin/toPinyin.test.ts +12 -0
- package/src/cn/pinyin/toPinyinPure.ts +43 -0
- package/src/cn/pinyin/transform.ts +12 -0
- package/src/consola/formatLogObject.test.ts +27 -0
- package/src/consola/formatLogObject.ts +34 -6
- package/src/dayjs/dayjs.ts +18 -18
- package/src/dayjs/index.ts +3 -1
- package/src/dayjs/parseRelativeTime.test.ts +185 -0
- package/src/dayjs/parseRelativeTime.ts +115 -0
- package/src/dayjs/resolveRelativeTime.test.ts +357 -0
- package/src/dayjs/resolveRelativeTime.ts +167 -0
- package/src/emittery/emitter.ts +9 -0
- package/src/emittery/index.ts +1 -0
- package/src/fs/FileSystemError.ts +26 -0
- package/src/fs/IFileSystem.d.ts +102 -0
- package/src/fs/MemoryFileSystem.test.ts +37 -0
- package/src/fs/createBrowserFileSystem.ts +291 -0
- package/src/fs/createMemoryFileSystem.ts +604 -0
- package/src/fs/createSandboxFileSystem.ts +136 -0
- package/src/fs/createWebDavFileSystem.ts +172 -0
- package/src/fs/findMimeType.ts +23 -0
- package/src/fs/index.ts +8 -0
- package/src/fs/orpc/FileSystemContract.ts +92 -0
- package/src/fs/orpc/createContractClientFileSystem.ts +115 -0
- package/src/fs/orpc/index.ts +2 -0
- package/src/fs/orpc/server/createFileSystemContractImpl.ts +64 -0
- package/src/fs/orpc/server/index.ts +1 -0
- package/src/fs/s3/createS3MiniFileSystem.ts +830 -0
- package/src/fs/s3/index.ts +1 -0
- package/src/fs/s3/s3mini.test.ts +264 -0
- package/src/fs/scandir.ts +75 -0
- package/src/fs/server/createDatabaseFileSystem.ts +668 -0
- package/src/fs/server/createNodeFileSystem.ts +499 -0
- package/src/fs/server/dbfs.test.ts +47 -0
- package/src/fs/server/index.ts +1 -0
- package/src/fs/server/loadTestDatabase.ts +131 -0
- package/src/fs/tests/runFileSystemTest.ts +288 -0
- package/src/fs/types.ts +29 -0
- package/src/fs/utils/getFileUrl.ts +44 -0
- package/src/fs/utils.ts +23 -0
- package/src/jsonschema/JsonSchema.ts +118 -110
- package/src/jsonschema/forEachJsonSchema.ts +50 -0
- package/src/jsonschema/index.ts +1 -0
- package/src/orpc/createOpenApiContractClient.ts +52 -0
- package/src/orpc/createRpcContractClient.ts +50 -0
- package/src/orpc/index.ts +2 -0
- package/src/orpc/resolveLinkPlugins.ts +29 -0
- package/src/password/PHC.ts +3 -3
- package/src/password/Password.test.ts +1 -1
- package/src/password/createPBKDF2PasswordAlgorithm.ts +2 -2
- package/src/resource/schema/AnyResourceSchema.ts +16 -2
- package/src/s3/formatS3Url.test.ts +254 -0
- package/src/s3/formatS3Url.ts +84 -0
- package/src/s3/index.ts +2 -0
- package/src/s3/parseS3Url.test.ts +258 -0
- package/src/s3/parseS3Url.ts +88 -0
- package/src/schema/SchemaRegistry.ts +35 -33
- package/src/schema/formatZodError.test.ts +196 -0
- package/src/schema/formatZodError.ts +151 -0
- package/src/schema/getSchemaOptions.ts +2 -2
- package/src/schema/index.ts +1 -1
- package/src/utils/buildBaseUrl.ts +12 -0
- package/src/utils/buildRedactorFormSchema.ts +85 -0
- package/src/utils/index.ts +4 -0
- package/src/utils/resolveFeatureOptions.ts +14 -0
- package/src/cn/ChineseResidentIdNo.mod.ts +0 -7
- package/src/cn/DivisionCode.mod.ts +0 -7
- package/src/cn/UnifiedSocialCreditCode.mod.ts +0 -7
- package/src/cn/mod.ts +0 -3
- package/src/schema/SchemaRegistry.mod.ts +0 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import dayjs from "dayjs";
|
|
2
|
+
import { checkDurationUnit, RelativeDurationUnits } from "./resolveRelativeTime.js";
|
|
3
|
+
/**
|
|
4
|
+
* Parses a relative time string and returns an array of operations.
|
|
5
|
+
*
|
|
6
|
+
* @param s - The relative time string to parse (must start with "now")
|
|
7
|
+
* @returns Array of operations that can be applied sequentially
|
|
8
|
+
* @throws {Error} When the format is invalid
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* parseRelativeTime('now-1h+30m') // [{ operator: '-', duration: dayjs.duration(1, 'h') }, { operator: '+', duration: dayjs.duration(30, 'm') }]
|
|
13
|
+
* parseRelativeTime('now+1d6h') // [{ operator: '+', duration: dayjs.duration({ days: 1, hours: 6 }) }]
|
|
14
|
+
* parseRelativeTime('now/d') // [{ operator: '/', unit: 'd' }]
|
|
15
|
+
* parseRelativeTime('now\\M') // [{ operator: '\\', unit: 'M' }]
|
|
16
|
+
* parseRelativeTime('now-1M/M') // [{ operator: '-', duration: dayjs.duration(1, 'M') }, { operator: '/', unit: 'M' }]
|
|
17
|
+
* parseRelativeTime('now+500ms') // [{ operator: '+', duration: dayjs.duration(500, 'ms') }]
|
|
18
|
+
* ```
|
|
19
|
+
*/ export function parseRelativeTime(s) {
|
|
20
|
+
if (typeof s !== "string" || !s.startsWith("now")) {
|
|
21
|
+
throw new Error(`Invalid relative time format: ${s}`);
|
|
22
|
+
}
|
|
23
|
+
const remaining = s.slice(3); // Remove 'now'
|
|
24
|
+
if (!remaining) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
const operations = [];
|
|
28
|
+
// Single regex to match all operations: <op><duration_spec> or <op><unit>
|
|
29
|
+
// Where duration_spec can be: 1h, 1d6h, 500ms, etc.
|
|
30
|
+
const operationRegex = /([+\-/\\])([^+\-/\\]+)/g;
|
|
31
|
+
let match;
|
|
32
|
+
let lastIndex = 0;
|
|
33
|
+
while ((match = operationRegex.exec(remaining)) !== null) {
|
|
34
|
+
const [, operator, operand] = match;
|
|
35
|
+
if (operator === "/" || operator === "\\") {
|
|
36
|
+
// Truncation operation - single unit only
|
|
37
|
+
checkDurationUnit(operand.trim());
|
|
38
|
+
operations.push({
|
|
39
|
+
operator: operator,
|
|
40
|
+
unit: operand.trim()
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
// Addition or subtraction operation - parse complex duration
|
|
45
|
+
const parsedDuration = parseDurationSpec(operand.trim());
|
|
46
|
+
operations.push({
|
|
47
|
+
operator: operator,
|
|
48
|
+
duration: parsedDuration
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
lastIndex = operationRegex.lastIndex;
|
|
52
|
+
}
|
|
53
|
+
// Check if we parsed the entire remaining string
|
|
54
|
+
if (lastIndex < remaining.length) {
|
|
55
|
+
throw new Error(`Invalid relative time format: ${s}`);
|
|
56
|
+
}
|
|
57
|
+
return operations;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Parses a duration specification like "1h", "1d6h", "500ms" into a dayjs Duration.
|
|
61
|
+
* Supports multiple units in a single specification.
|
|
62
|
+
*/ function parseDurationSpec(spec) {
|
|
63
|
+
// Match all number+unit pairs: 1d, 6h, 30m, 500ms, etc.
|
|
64
|
+
const durationRegex = /(\d+)(ms|[smhdwMQy])/g;
|
|
65
|
+
const durationObj = {};
|
|
66
|
+
let match;
|
|
67
|
+
let hasMatch = false;
|
|
68
|
+
while ((match = durationRegex.exec(spec)) !== null) {
|
|
69
|
+
const [, amountStr, unit] = match;
|
|
70
|
+
checkDurationUnit(unit);
|
|
71
|
+
const amount = parseInt(amountStr, 10);
|
|
72
|
+
// Dayjs duration supports unit strings directly
|
|
73
|
+
durationObj[unit] = (durationObj[unit] || 0) + amount;
|
|
74
|
+
hasMatch = true;
|
|
75
|
+
}
|
|
76
|
+
if (!hasMatch) {
|
|
77
|
+
// Check if there are invalid units by looking for number+invalid_unit patterns
|
|
78
|
+
const invalidUnitRegex = /\d+([a-zA-Z]+)/g;
|
|
79
|
+
let invalidMatch;
|
|
80
|
+
while ((invalidMatch = invalidUnitRegex.exec(spec)) !== null) {
|
|
81
|
+
const [, unit] = invalidMatch;
|
|
82
|
+
if (!RelativeDurationUnits.includes(unit)) {
|
|
83
|
+
throw new Error(`Invalid unit: ${unit}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`Invalid duration specification: ${spec}`);
|
|
87
|
+
}
|
|
88
|
+
return dayjs.duration(durationObj);
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=parseRelativeTime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/dayjs/parseRelativeTime.ts"],"sourcesContent":["import dayjs from 'dayjs';\nimport type { Duration } from 'dayjs/plugin/duration';\nimport { checkDurationUnit, RelativeDurationUnits, type RelativeDurationUnit } from './resolveRelativeTime';\n\nexport type TimeOperation =\n\t| {\n\t\t\toperator: '+' | '-';\n\t\t\tduration: Duration;\n\t }\n\t| {\n\t\t\toperator: '/' | '\\\\';\n\t\t\tunit: RelativeDurationUnit;\n\t };\n\n/**\n * Parses a relative time string and returns an array of operations.\n *\n * @param s - The relative time string to parse (must start with \"now\")\n * @returns Array of operations that can be applied sequentially\n * @throws {Error} When the format is invalid\n *\n * @example\n * ```typescript\n * parseRelativeTime('now-1h+30m') // [{ operator: '-', duration: dayjs.duration(1, 'h') }, { operator: '+', duration: dayjs.duration(30, 'm') }]\n * parseRelativeTime('now+1d6h') // [{ operator: '+', duration: dayjs.duration({ days: 1, hours: 6 }) }]\n * parseRelativeTime('now/d') // [{ operator: '/', unit: 'd' }]\n * parseRelativeTime('now\\\\M') // [{ operator: '\\\\', unit: 'M' }]\n * parseRelativeTime('now-1M/M') // [{ operator: '-', duration: dayjs.duration(1, 'M') }, { operator: '/', unit: 'M' }]\n * parseRelativeTime('now+500ms') // [{ operator: '+', duration: dayjs.duration(500, 'ms') }]\n * ```\n */\nexport function parseRelativeTime(s: string): TimeOperation[] {\n\tif (typeof s !== 'string' || !s.startsWith('now')) {\n\t\tthrow new Error(`Invalid relative time format: ${s}`);\n\t}\n\n\tconst remaining = s.slice(3); // Remove 'now'\n\n\tif (!remaining) {\n\t\treturn [];\n\t}\n\n\tconst operations: TimeOperation[] = [];\n\n\t// Single regex to match all operations: <op><duration_spec> or <op><unit>\n\t// Where duration_spec can be: 1h, 1d6h, 500ms, etc.\n\tconst operationRegex = /([+\\-/\\\\])([^+\\-/\\\\]+)/g;\n\tlet match: RegExpExecArray | null;\n\tlet lastIndex = 0;\n\n\twhile ((match = operationRegex.exec(remaining)) !== null) {\n\t\tconst [, operator, operand] = match;\n\n\t\tif (operator === '/' || operator === '\\\\') {\n\t\t\t// Truncation operation - single unit only\n\t\t\tcheckDurationUnit(operand.trim());\n\t\t\toperations.push({\n\t\t\t\toperator: operator as '/' | '\\\\',\n\t\t\t\tunit: operand.trim() as RelativeDurationUnit,\n\t\t\t});\n\t\t} else {\n\t\t\t// Addition or subtraction operation - parse complex duration\n\t\t\tconst parsedDuration = parseDurationSpec(operand.trim());\n\t\t\toperations.push({\n\t\t\t\toperator: operator as '+' | '-',\n\t\t\t\tduration: parsedDuration,\n\t\t\t});\n\t\t}\n\t\tlastIndex = operationRegex.lastIndex;\n\t}\n\n\t// Check if we parsed the entire remaining string\n\tif (lastIndex < remaining.length) {\n\t\tthrow new Error(`Invalid relative time format: ${s}`);\n\t}\n\n\treturn operations;\n}\n\n/**\n * Parses a duration specification like \"1h\", \"1d6h\", \"500ms\" into a dayjs Duration.\n * Supports multiple units in a single specification.\n */\nfunction parseDurationSpec(spec: string): Duration {\n\t// Match all number+unit pairs: 1d, 6h, 30m, 500ms, etc.\n\tconst durationRegex = /(\\d+)(ms|[smhdwMQy])/g;\n\tconst durationObj: Record<string, number> = {};\n\tlet match: RegExpExecArray | null;\n\tlet hasMatch = false;\n\n\twhile ((match = durationRegex.exec(spec)) !== null) {\n\t\tconst [, amountStr, unit] = match;\n\t\tcheckDurationUnit(unit);\n\t\tconst amount = parseInt(amountStr, 10);\n\n\t\t// Dayjs duration supports unit strings directly\n\t\tdurationObj[unit] = (durationObj[unit] || 0) + amount;\n\t\thasMatch = true;\n\t}\n\n\tif (!hasMatch) {\n\t\t// Check if there are invalid units by looking for number+invalid_unit patterns\n\t\tconst invalidUnitRegex = /\\d+([a-zA-Z]+)/g;\n\t\tlet invalidMatch: RegExpExecArray | null;\n\t\twhile ((invalidMatch = invalidUnitRegex.exec(spec)) !== null) {\n\t\t\tconst [, unit] = invalidMatch;\n\t\t\tif (!RelativeDurationUnits.includes(unit as RelativeDurationUnit)) {\n\t\t\t\tthrow new Error(`Invalid unit: ${unit}`);\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Invalid duration specification: ${spec}`);\n\t}\n\n\treturn dayjs.duration(durationObj);\n}\n"],"names":["dayjs","checkDurationUnit","RelativeDurationUnits","parseRelativeTime","s","startsWith","Error","remaining","slice","operations","operationRegex","match","lastIndex","exec","operator","operand","trim","push","unit","parsedDuration","parseDurationSpec","duration","length","spec","durationRegex","durationObj","hasMatch","amountStr","amount","parseInt","invalidUnitRegex","invalidMatch","includes"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAE1B,SAASC,iBAAiB,EAAEC,qBAAqB,QAAmC,wBAAwB;AAY5G;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,kBAAkBC,CAAS;IAC1C,IAAI,OAAOA,MAAM,YAAY,CAACA,EAAEC,UAAU,CAAC,QAAQ;QAClD,MAAM,IAAIC,MAAM,CAAC,8BAA8B,EAAEF,GAAG;IACrD;IAEA,MAAMG,YAAYH,EAAEI,KAAK,CAAC,IAAI,eAAe;IAE7C,IAAI,CAACD,WAAW;QACf,OAAO,EAAE;IACV;IAEA,MAAME,aAA8B,EAAE;IAEtC,0EAA0E;IAC1E,oDAAoD;IACpD,MAAMC,iBAAiB;IACvB,IAAIC;IACJ,IAAIC,YAAY;IAEhB,MAAO,AAACD,CAAAA,QAAQD,eAAeG,IAAI,CAACN,UAAS,MAAO,KAAM;QACzD,MAAM,GAAGO,UAAUC,QAAQ,GAAGJ;QAE9B,IAAIG,aAAa,OAAOA,aAAa,MAAM;YAC1C,0CAA0C;YAC1Cb,kBAAkBc,QAAQC,IAAI;YAC9BP,WAAWQ,IAAI,CAAC;gBACfH,UAAUA;gBACVI,MAAMH,QAAQC,IAAI;YACnB;QACD,OAAO;YACN,6DAA6D;YAC7D,MAAMG,iBAAiBC,kBAAkBL,QAAQC,IAAI;YACrDP,WAAWQ,IAAI,CAAC;gBACfH,UAAUA;gBACVO,UAAUF;YACX;QACD;QACAP,YAAYF,eAAeE,SAAS;IACrC;IAEA,iDAAiD;IACjD,IAAIA,YAAYL,UAAUe,MAAM,EAAE;QACjC,MAAM,IAAIhB,MAAM,CAAC,8BAA8B,EAAEF,GAAG;IACrD;IAEA,OAAOK;AACR;AAEA;;;CAGC,GACD,SAASW,kBAAkBG,IAAY;IACtC,wDAAwD;IACxD,MAAMC,gBAAgB;IACtB,MAAMC,cAAsC,CAAC;IAC7C,IAAId;IACJ,IAAIe,WAAW;IAEf,MAAO,AAACf,CAAAA,QAAQa,cAAcX,IAAI,CAACU,KAAI,MAAO,KAAM;QACnD,MAAM,GAAGI,WAAWT,KAAK,GAAGP;QAC5BV,kBAAkBiB;QAClB,MAAMU,SAASC,SAASF,WAAW;QAEnC,gDAAgD;QAChDF,WAAW,CAACP,KAAK,GAAG,AAACO,CAAAA,WAAW,CAACP,KAAK,IAAI,CAAA,IAAKU;QAC/CF,WAAW;IACZ;IAEA,IAAI,CAACA,UAAU;QACd,+EAA+E;QAC/E,MAAMI,mBAAmB;QACzB,IAAIC;QACJ,MAAO,AAACA,CAAAA,eAAeD,iBAAiBjB,IAAI,CAACU,KAAI,MAAO,KAAM;YAC7D,MAAM,GAAGL,KAAK,GAAGa;YACjB,IAAI,CAAC7B,sBAAsB8B,QAAQ,CAACd,OAA+B;gBAClE,MAAM,IAAIZ,MAAM,CAAC,cAAc,EAAEY,MAAM;YACxC;QACD;QACA,MAAM,IAAIZ,MAAM,CAAC,gCAAgC,EAAEiB,MAAM;IAC1D;IAEA,OAAOvB,MAAMqB,QAAQ,CAACI;AACvB"}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) {
|
|
3
|
+
Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
obj[key] = value;
|
|
12
|
+
}
|
|
13
|
+
return obj;
|
|
14
|
+
}
|
|
15
|
+
import dayjs from "dayjs";
|
|
16
|
+
import duration from "dayjs/plugin/duration";
|
|
17
|
+
import { describe, expect, it } from "vitest";
|
|
18
|
+
import { parseRelativeTime } from "./parseRelativeTime.js";
|
|
19
|
+
dayjs.extend(duration);
|
|
20
|
+
describe("parseRelativeTime", function () {
|
|
21
|
+
it("should return empty array for \"now\"", function () {
|
|
22
|
+
var result = parseRelativeTime("now");
|
|
23
|
+
expect(result).toEqual([]);
|
|
24
|
+
});
|
|
25
|
+
it("should parse simple addition operations", function () {
|
|
26
|
+
var result = parseRelativeTime("now+1h");
|
|
27
|
+
expect(result).toHaveLength(1);
|
|
28
|
+
expect(result[0]).toEqual({
|
|
29
|
+
operator: "+",
|
|
30
|
+
duration: dayjs.duration({
|
|
31
|
+
hours: 1
|
|
32
|
+
})
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
it("should parse simple subtraction operations", function () {
|
|
36
|
+
var result = parseRelativeTime("now-30m");
|
|
37
|
+
expect(result).toHaveLength(1);
|
|
38
|
+
expect(result[0]).toEqual({
|
|
39
|
+
operator: "-",
|
|
40
|
+
duration: dayjs.duration({
|
|
41
|
+
minutes: 30
|
|
42
|
+
})
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
it("should parse milliseconds", function () {
|
|
46
|
+
var result = parseRelativeTime("now+500ms");
|
|
47
|
+
expect(result).toHaveLength(1);
|
|
48
|
+
expect(result[0]).toEqual({
|
|
49
|
+
operator: "+",
|
|
50
|
+
duration: dayjs.duration({
|
|
51
|
+
milliseconds: 500
|
|
52
|
+
})
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
it("should parse complex duration combinations", function () {
|
|
56
|
+
var result = parseRelativeTime("now+1d6h30m");
|
|
57
|
+
expect(result).toHaveLength(1);
|
|
58
|
+
expect(result[0]).toEqual({
|
|
59
|
+
operator: "+",
|
|
60
|
+
duration: dayjs.duration({
|
|
61
|
+
days: 1,
|
|
62
|
+
hours: 6,
|
|
63
|
+
minutes: 30
|
|
64
|
+
})
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
it("should parse truncation operations", function () {
|
|
68
|
+
var result = parseRelativeTime("now/d");
|
|
69
|
+
expect(result).toHaveLength(1);
|
|
70
|
+
expect(result[0]).toEqual({
|
|
71
|
+
operator: "/",
|
|
72
|
+
unit: "d"
|
|
73
|
+
});
|
|
74
|
+
var result2 = parseRelativeTime("now\\M");
|
|
75
|
+
expect(result2).toHaveLength(1);
|
|
76
|
+
expect(result2[0]).toEqual({
|
|
77
|
+
operator: "\\",
|
|
78
|
+
unit: "M"
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
it("should parse multiple operations", function () {
|
|
82
|
+
var result = parseRelativeTime("now-1h+30m");
|
|
83
|
+
expect(result).toHaveLength(2);
|
|
84
|
+
expect(result[0]).toEqual({
|
|
85
|
+
operator: "-",
|
|
86
|
+
duration: dayjs.duration({
|
|
87
|
+
hours: 1
|
|
88
|
+
})
|
|
89
|
+
});
|
|
90
|
+
expect(result[1]).toEqual({
|
|
91
|
+
operator: "+",
|
|
92
|
+
duration: dayjs.duration({
|
|
93
|
+
minutes: 30
|
|
94
|
+
})
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
it("should parse mixed arithmetic and truncation operations", function () {
|
|
98
|
+
var result = parseRelativeTime("now-1M/M");
|
|
99
|
+
expect(result).toHaveLength(2);
|
|
100
|
+
expect(result[0]).toEqual({
|
|
101
|
+
operator: "-",
|
|
102
|
+
duration: dayjs.duration({
|
|
103
|
+
months: 1
|
|
104
|
+
})
|
|
105
|
+
});
|
|
106
|
+
expect(result[1]).toEqual({
|
|
107
|
+
operator: "/",
|
|
108
|
+
unit: "M"
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
it("should handle all supported units", function () {
|
|
112
|
+
var units = [
|
|
113
|
+
"ms",
|
|
114
|
+
"s",
|
|
115
|
+
"m",
|
|
116
|
+
"h",
|
|
117
|
+
"d",
|
|
118
|
+
"w",
|
|
119
|
+
"M",
|
|
120
|
+
"Q",
|
|
121
|
+
"y"
|
|
122
|
+
];
|
|
123
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
124
|
+
try {
|
|
125
|
+
for (var _iterator = units[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
|
126
|
+
var unit = _step.value;
|
|
127
|
+
var result = parseRelativeTime("now+1".concat(unit));
|
|
128
|
+
expect(result).toHaveLength(1);
|
|
129
|
+
expect(result[0]).toEqual({
|
|
130
|
+
operator: "+",
|
|
131
|
+
duration: dayjs.duration(_define_property({}, unit, 1))
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
_didIteratorError = true;
|
|
137
|
+
_iteratorError = err;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
try {
|
|
141
|
+
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
142
|
+
_iterator.return();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
if (_didIteratorError) {
|
|
147
|
+
throw _iteratorError;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
it("should handle complex multi-unit expressions", function () {
|
|
153
|
+
var result = parseRelativeTime("now+1y2M3w4d5h6m7s8ms");
|
|
154
|
+
expect(result).toHaveLength(1);
|
|
155
|
+
expect(result[0]).toEqual({
|
|
156
|
+
operator: "+",
|
|
157
|
+
duration: dayjs.duration({
|
|
158
|
+
years: 1,
|
|
159
|
+
months: 2,
|
|
160
|
+
weeks: 3,
|
|
161
|
+
days: 4,
|
|
162
|
+
hours: 5,
|
|
163
|
+
minutes: 6,
|
|
164
|
+
seconds: 7,
|
|
165
|
+
milliseconds: 8
|
|
166
|
+
})
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
it("should handle same unit multiple times (should sum)", function () {
|
|
170
|
+
var result = parseRelativeTime("now+1h2h3h");
|
|
171
|
+
expect(result).toHaveLength(1);
|
|
172
|
+
expect(result[0]).toEqual({
|
|
173
|
+
operator: "+",
|
|
174
|
+
duration: dayjs.duration({
|
|
175
|
+
hours: 6
|
|
176
|
+
})
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
it("should throw error for invalid format", function () {
|
|
180
|
+
expect(function () {
|
|
181
|
+
return parseRelativeTime("invalid");
|
|
182
|
+
}).toThrow("Invalid relative time format");
|
|
183
|
+
expect(function () {
|
|
184
|
+
return parseRelativeTime("now+");
|
|
185
|
+
}).toThrow("Invalid relative time format");
|
|
186
|
+
expect(function () {
|
|
187
|
+
return parseRelativeTime("now+abc");
|
|
188
|
+
}).toThrow("Invalid duration specification");
|
|
189
|
+
});
|
|
190
|
+
it("should throw error for invalid units in truncation", function () {
|
|
191
|
+
expect(function () {
|
|
192
|
+
return parseRelativeTime("now/invalid");
|
|
193
|
+
}).toThrow("Invalid unit");
|
|
194
|
+
});
|
|
195
|
+
it("should throw error for invalid units in duration", function () {
|
|
196
|
+
expect(function () {
|
|
197
|
+
return parseRelativeTime("now+1invalid");
|
|
198
|
+
}).toThrow("Invalid unit");
|
|
199
|
+
});
|
|
200
|
+
it("should handle whitespace correctly", function () {
|
|
201
|
+
// The regex should handle operands without extra whitespace issues
|
|
202
|
+
var result = parseRelativeTime("now+1h30m");
|
|
203
|
+
expect(result).toHaveLength(1);
|
|
204
|
+
expect(result[0]).toEqual({
|
|
205
|
+
operator: "+",
|
|
206
|
+
duration: dayjs.duration({
|
|
207
|
+
hours: 1,
|
|
208
|
+
minutes: 30
|
|
209
|
+
})
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
it("should parse real-world examples", function () {
|
|
213
|
+
// Last 24 hours
|
|
214
|
+
var result1 = parseRelativeTime("now-24h");
|
|
215
|
+
expect(result1).toHaveLength(1);
|
|
216
|
+
expect(result1[0]).toEqual({
|
|
217
|
+
operator: "-",
|
|
218
|
+
duration: dayjs.duration({
|
|
219
|
+
hours: 24
|
|
220
|
+
})
|
|
221
|
+
});
|
|
222
|
+
// Start of previous month
|
|
223
|
+
var result2 = parseRelativeTime("now-1M/M");
|
|
224
|
+
expect(result2).toHaveLength(2);
|
|
225
|
+
expect(result2[0]).toEqual({
|
|
226
|
+
operator: "-",
|
|
227
|
+
duration: dayjs.duration({
|
|
228
|
+
months: 1
|
|
229
|
+
})
|
|
230
|
+
});
|
|
231
|
+
expect(result2[1]).toEqual({
|
|
232
|
+
operator: "/",
|
|
233
|
+
unit: "M"
|
|
234
|
+
});
|
|
235
|
+
// Complex time ago
|
|
236
|
+
var result3 = parseRelativeTime("now-1w2d3h");
|
|
237
|
+
expect(result3).toHaveLength(1);
|
|
238
|
+
expect(result3[0]).toEqual({
|
|
239
|
+
operator: "-",
|
|
240
|
+
duration: dayjs.duration({
|
|
241
|
+
weeks: 1,
|
|
242
|
+
days: 2,
|
|
243
|
+
hours: 3
|
|
244
|
+
})
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import dayjs from "dayjs";
|
|
2
|
+
import duration from "dayjs/plugin/duration";
|
|
3
|
+
import quarterOfYear from "dayjs/plugin/quarterOfYear";
|
|
4
|
+
import weekOfYear from "dayjs/plugin/weekOfYear";
|
|
5
|
+
dayjs.extend(duration);
|
|
6
|
+
dayjs.extend(quarterOfYear);
|
|
7
|
+
dayjs.extend(weekOfYear);
|
|
8
|
+
/**
|
|
9
|
+
* Resolves a Grafana-style relative time string and returns the corresponding Date.
|
|
10
|
+
*
|
|
11
|
+
* @param s - The relative time string to parse (must start with "now")
|
|
12
|
+
* @param now - Optional reference date. If undefined, uses current time
|
|
13
|
+
* @returns The calculated Date based on the relative time expression
|
|
14
|
+
*
|
|
15
|
+
* @throws {Error} When the format is invalid or contains unsupported operators/units
|
|
16
|
+
*
|
|
17
|
+
* ## Syntax
|
|
18
|
+
*
|
|
19
|
+
* All expressions must start with `now` followed by optional operations:
|
|
20
|
+
*
|
|
21
|
+
* ### Operators
|
|
22
|
+
* - `-` - Subtraction (e.g., `now-1h` for one hour ago)
|
|
23
|
+
* - `+` - Addition (e.g., `now+1d` for one day from now)
|
|
24
|
+
* - `/` - Truncation to beginning of time unit (e.g., `now/d` for start of current day)
|
|
25
|
+
* - `\` - Truncation to end of time unit (e.g., `now\d` for end of current day)
|
|
26
|
+
*
|
|
27
|
+
* ### Time Units
|
|
28
|
+
* - `s` - seconds
|
|
29
|
+
* - `m` - minutes
|
|
30
|
+
* - `h` - hours
|
|
31
|
+
* - `d` - days
|
|
32
|
+
* - `w` - weeks
|
|
33
|
+
* - `M` - months
|
|
34
|
+
* - `Q` - quarters
|
|
35
|
+
* - `y` - years
|
|
36
|
+
*
|
|
37
|
+
* ### Operations
|
|
38
|
+
* Operations are processed sequentially from left to right:
|
|
39
|
+
* - **Addition/Subtraction**: `now±{count}{unit}` (e.g., `now-24h`, `now+1d`)
|
|
40
|
+
* - **Truncation to start**: `now/{unit}` (e.g., `now/d`, `now/M`)
|
|
41
|
+
* - **Truncation to end**: `now\{unit}` (e.g., `now\d`, `now\M`)
|
|
42
|
+
* - **Complex**: Multiple operations can be chained (e.g., `now-1M/M`, `now\d`, `now-1y\y`)
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* // Basic usage
|
|
47
|
+
* resolveRelativeTime('now') // Current time
|
|
48
|
+
* resolveRelativeTime('now-1h') // One hour ago
|
|
49
|
+
* resolveRelativeTime('now+1d') // One day from now
|
|
50
|
+
* resolveRelativeTime('now/d') // Start of current day
|
|
51
|
+
* resolveRelativeTime('now\\d') // End of current day
|
|
52
|
+
*
|
|
53
|
+
* // Common patterns
|
|
54
|
+
* resolveRelativeTime('now-24h') // Last 24 hours
|
|
55
|
+
* resolveRelativeTime('now-7d') // Last 7 days
|
|
56
|
+
* resolveRelativeTime('now/M') // Start of current month
|
|
57
|
+
* resolveRelativeTime('now\\M') // End of current month
|
|
58
|
+
* resolveRelativeTime('now-1M/M') // Start of previous month
|
|
59
|
+
* resolveRelativeTime('now-1M\\M') // End of previous month
|
|
60
|
+
* resolveRelativeTime('now/w') // Start of current week
|
|
61
|
+
* resolveRelativeTime('now\\w') // End of current week
|
|
62
|
+
* resolveRelativeTime('now/y') // Start of current year
|
|
63
|
+
* resolveRelativeTime('now\\y') // End of current year
|
|
64
|
+
*
|
|
65
|
+
* // Complex expressions
|
|
66
|
+
* resolveRelativeTime('now/d+1d-1s') // End of current day (alternative method)
|
|
67
|
+
* resolveRelativeTime('now\\d') // End of current day (direct method)
|
|
68
|
+
* resolveRelativeTime('now-1w+2d-3h') // 1 week ago, plus 2 days, minus 3 hours
|
|
69
|
+
*
|
|
70
|
+
* // With reference date
|
|
71
|
+
* const refDate = new Date('2024-03-15T14:30:45.123Z');
|
|
72
|
+
* resolveRelativeTime('now-1h', refDate); // One hour before reference date
|
|
73
|
+
* resolveRelativeTime('now\\d', refDate); // End of reference day
|
|
74
|
+
* ```
|
|
75
|
+
*/ export function resolveRelativeTime(s, now) {
|
|
76
|
+
{
|
|
77
|
+
let out;
|
|
78
|
+
if (!s) {} else if (s instanceof Date) {
|
|
79
|
+
out = s;
|
|
80
|
+
} else if (typeof s === 'number') {
|
|
81
|
+
out = new Date(s);
|
|
82
|
+
} else if (!s.startsWith('now')) {
|
|
83
|
+
out = new Date(s);
|
|
84
|
+
}
|
|
85
|
+
if (out) {
|
|
86
|
+
if (isNaN(out.getTime())) {
|
|
87
|
+
throw new Error(`Invalid date: ${s}`);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (typeof s !== 'string' || !s.startsWith('now')) {
|
|
93
|
+
throw new Error(`Invalid relative time format: ${s}`);
|
|
94
|
+
}
|
|
95
|
+
let current = dayjs(now);
|
|
96
|
+
const remaining = s.slice(3); // Remove 'now'
|
|
97
|
+
if (!remaining) {
|
|
98
|
+
return current.toDate();
|
|
99
|
+
}
|
|
100
|
+
// Split by operators while keeping them in the result
|
|
101
|
+
const parts = remaining.split(/([+\-/\\])/).filter((part)=>part !== '');
|
|
102
|
+
for(let i = 0; i < parts.length; i += 2){
|
|
103
|
+
const operator = parts[i];
|
|
104
|
+
const operand = parts[i + 1];
|
|
105
|
+
if (!operator || !operand) {
|
|
106
|
+
throw new Error(`Invalid relative time format: ${s}`);
|
|
107
|
+
}
|
|
108
|
+
if (operator === '/') {
|
|
109
|
+
// Truncation to start operation
|
|
110
|
+
checkDurationUnit(operand);
|
|
111
|
+
current = current.startOf(operand);
|
|
112
|
+
} else if (operator === '\\') {
|
|
113
|
+
// Truncation to end operation
|
|
114
|
+
checkDurationUnit(operand);
|
|
115
|
+
current = current.endOf(operand);
|
|
116
|
+
} else {
|
|
117
|
+
// Addition or subtraction operation
|
|
118
|
+
const match = operand.match(/^(\d+)([smhdwMQy])$/);
|
|
119
|
+
if (!match) {
|
|
120
|
+
throw new Error(`Invalid time operand: ${operand}`);
|
|
121
|
+
}
|
|
122
|
+
const [, amountStr, unit] = match;
|
|
123
|
+
checkDurationUnit(unit);
|
|
124
|
+
const amount = parseInt(amountStr, 10);
|
|
125
|
+
if (operator === '+') {
|
|
126
|
+
current = current.add(amount, unit);
|
|
127
|
+
} else if (operator === '-') {
|
|
128
|
+
current = current.subtract(amount, unit);
|
|
129
|
+
} else {
|
|
130
|
+
throw new Error(`Invalid operator: ${operator}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return current.toDate();
|
|
135
|
+
}
|
|
136
|
+
/** Array of all valid time units */ export const RelativeDurationUnits = [
|
|
137
|
+
'ms',
|
|
138
|
+
's',
|
|
139
|
+
'm',
|
|
140
|
+
'h',
|
|
141
|
+
'd',
|
|
142
|
+
'w',
|
|
143
|
+
'M',
|
|
144
|
+
'Q',
|
|
145
|
+
'y'
|
|
146
|
+
];
|
|
147
|
+
/**
|
|
148
|
+
* Type guard to validate and assert that a string is a valid time unit.
|
|
149
|
+
*
|
|
150
|
+
* @param u - The string to check
|
|
151
|
+
* @throws {Error} When the unit is not supported
|
|
152
|
+
*/ export function checkDurationUnit(u) {
|
|
153
|
+
if (!RelativeDurationUnits.includes(u)) {
|
|
154
|
+
throw new Error(`Invalid unit: ${u}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
//# sourceMappingURL=resolveRelativeTime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/dayjs/resolveRelativeTime.ts"],"sourcesContent":["import dayjs from 'dayjs';\nimport duration from 'dayjs/plugin/duration';\nimport quarterOfYear from 'dayjs/plugin/quarterOfYear';\nimport weekOfYear from 'dayjs/plugin/weekOfYear';\n\ndayjs.extend(duration);\ndayjs.extend(quarterOfYear);\ndayjs.extend(weekOfYear);\n\n/**\n * Resolves a Grafana-style relative time string and returns the corresponding Date.\n *\n * @param s - The relative time string to parse (must start with \"now\")\n * @param now - Optional reference date. If undefined, uses current time\n * @returns The calculated Date based on the relative time expression\n *\n * @throws {Error} When the format is invalid or contains unsupported operators/units\n *\n * ## Syntax\n *\n * All expressions must start with `now` followed by optional operations:\n *\n * ### Operators\n * - `-` - Subtraction (e.g., `now-1h` for one hour ago)\n * - `+` - Addition (e.g., `now+1d` for one day from now)\n * - `/` - Truncation to beginning of time unit (e.g., `now/d` for start of current day)\n * - `\\` - Truncation to end of time unit (e.g., `now\\d` for end of current day)\n *\n * ### Time Units\n * - `s` - seconds\n * - `m` - minutes\n * - `h` - hours\n * - `d` - days\n * - `w` - weeks\n * - `M` - months\n * - `Q` - quarters\n * - `y` - years\n *\n * ### Operations\n * Operations are processed sequentially from left to right:\n * - **Addition/Subtraction**: `now±{count}{unit}` (e.g., `now-24h`, `now+1d`)\n * - **Truncation to start**: `now/{unit}` (e.g., `now/d`, `now/M`)\n * - **Truncation to end**: `now\\{unit}` (e.g., `now\\d`, `now\\M`)\n * - **Complex**: Multiple operations can be chained (e.g., `now-1M/M`, `now\\d`, `now-1y\\y`)\n *\n * @example\n * ```typescript\n * // Basic usage\n * resolveRelativeTime('now') // Current time\n * resolveRelativeTime('now-1h') // One hour ago\n * resolveRelativeTime('now+1d') // One day from now\n * resolveRelativeTime('now/d') // Start of current day\n * resolveRelativeTime('now\\\\d') // End of current day\n *\n * // Common patterns\n * resolveRelativeTime('now-24h') // Last 24 hours\n * resolveRelativeTime('now-7d') // Last 7 days\n * resolveRelativeTime('now/M') // Start of current month\n * resolveRelativeTime('now\\\\M') // End of current month\n * resolveRelativeTime('now-1M/M') // Start of previous month\n * resolveRelativeTime('now-1M\\\\M') // End of previous month\n * resolveRelativeTime('now/w') // Start of current week\n * resolveRelativeTime('now\\\\w') // End of current week\n * resolveRelativeTime('now/y') // Start of current year\n * resolveRelativeTime('now\\\\y') // End of current year\n *\n * // Complex expressions\n * resolveRelativeTime('now/d+1d-1s') // End of current day (alternative method)\n * resolveRelativeTime('now\\\\d') // End of current day (direct method)\n * resolveRelativeTime('now-1w+2d-3h') // 1 week ago, plus 2 days, minus 3 hours\n *\n * // With reference date\n * const refDate = new Date('2024-03-15T14:30:45.123Z');\n * resolveRelativeTime('now-1h', refDate); // One hour before reference date\n * resolveRelativeTime('now\\\\d', refDate); // End of reference day\n * ```\n */\nexport function resolveRelativeTime(s: string | Date | number, now?: Date | undefined): Date {\n\t{\n\t\tlet out: Date | undefined;\n\t\tif (!s) {\n\t\t} else if (s instanceof Date) {\n\t\t\tout = s;\n\t\t} else if (typeof s === 'number') {\n\t\t\tout = new Date(s);\n\t\t} else if (!s.startsWith('now')) {\n\t\t\tout = new Date(s);\n\t\t}\n\t\tif (out) {\n\t\t\tif (isNaN(out.getTime())) {\n\t\t\t\tthrow new Error(`Invalid date: ${s}`);\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t}\n\n\tif (typeof s !== 'string' || !s.startsWith('now')) {\n\t\tthrow new Error(`Invalid relative time format: ${s}`);\n\t}\n\n\tlet current = dayjs(now);\n\tconst remaining = s.slice(3); // Remove 'now'\n\n\tif (!remaining) {\n\t\treturn current.toDate();\n\t}\n\n\t// Split by operators while keeping them in the result\n\tconst parts = remaining.split(/([+\\-/\\\\])/).filter((part) => part !== '');\n\n\tfor (let i = 0; i < parts.length; i += 2) {\n\t\tconst operator = parts[i];\n\t\tconst operand = parts[i + 1];\n\n\t\tif (!operator || !operand) {\n\t\t\tthrow new Error(`Invalid relative time format: ${s}`);\n\t\t}\n\n\t\tif (operator === '/') {\n\t\t\t// Truncation to start operation\n\t\t\tcheckDurationUnit(operand);\n\t\t\tcurrent = current.startOf(operand);\n\t\t} else if (operator === '\\\\') {\n\t\t\t// Truncation to end operation\n\t\t\tcheckDurationUnit(operand);\n\t\t\tcurrent = current.endOf(operand);\n\t\t} else {\n\t\t\t// Addition or subtraction operation\n\t\t\tconst match = operand.match(/^(\\d+)([smhdwMQy])$/);\n\t\t\tif (!match) {\n\t\t\t\tthrow new Error(`Invalid time operand: ${operand}`);\n\t\t\t}\n\n\t\t\tconst [, amountStr, unit] = match;\n\t\t\tcheckDurationUnit(unit);\n\t\t\tconst amount = parseInt(amountStr, 10);\n\n\t\t\tif (operator === '+') {\n\t\t\t\tcurrent = current.add(amount, unit as 'w');\n\t\t\t} else if (operator === '-') {\n\t\t\t\tcurrent = current.subtract(amount, unit as 'Q');\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Invalid operator: ${operator}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn current.toDate();\n}\n\n/** Array of all valid time units */\nexport const RelativeDurationUnits = ['ms', 's', 'm', 'h', 'd', 'w', 'M', 'Q', 'y'] as const;\n\n/** Valid time units for relative time expressions */\nexport type RelativeDurationUnit = (typeof RelativeDurationUnits)[number];\n\n/**\n * Type guard to validate and assert that a string is a valid time unit.\n *\n * @param u - The string to check\n * @throws {Error} When the unit is not supported\n */\nexport function checkDurationUnit(u: string): asserts u is RelativeDurationUnit {\n\tif (!RelativeDurationUnits.includes(u as RelativeDurationUnit)) {\n\t\tthrow new Error(`Invalid unit: ${u}`);\n\t}\n}\n"],"names":["dayjs","duration","quarterOfYear","weekOfYear","extend","resolveRelativeTime","s","now","out","Date","startsWith","isNaN","getTime","Error","current","remaining","slice","toDate","parts","split","filter","part","i","length","operator","operand","checkDurationUnit","startOf","endOf","match","amountStr","unit","amount","parseInt","add","subtract","RelativeDurationUnits","u","includes"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAC1B,OAAOC,cAAc,wBAAwB;AAC7C,OAAOC,mBAAmB,6BAA6B;AACvD,OAAOC,gBAAgB,0BAA0B;AAEjDH,MAAMI,MAAM,CAACH;AACbD,MAAMI,MAAM,CAACF;AACbF,MAAMI,MAAM,CAACD;AAEb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GACD,OAAO,SAASE,oBAAoBC,CAAyB,EAAEC,GAAsB;IACpF;QACC,IAAIC;QACJ,IAAI,CAACF,GAAG,CACR,OAAO,IAAIA,aAAaG,MAAM;YAC7BD,MAAMF;QACP,OAAO,IAAI,OAAOA,MAAM,UAAU;YACjCE,MAAM,IAAIC,KAAKH;QAChB,OAAO,IAAI,CAACA,EAAEI,UAAU,CAAC,QAAQ;YAChCF,MAAM,IAAIC,KAAKH;QAChB;QACA,IAAIE,KAAK;YACR,IAAIG,MAAMH,IAAII,OAAO,KAAK;gBACzB,MAAM,IAAIC,MAAM,CAAC,cAAc,EAAEP,GAAG;YACrC;YACA,OAAOE;QACR;IACD;IAEA,IAAI,OAAOF,MAAM,YAAY,CAACA,EAAEI,UAAU,CAAC,QAAQ;QAClD,MAAM,IAAIG,MAAM,CAAC,8BAA8B,EAAEP,GAAG;IACrD;IAEA,IAAIQ,UAAUd,MAAMO;IACpB,MAAMQ,YAAYT,EAAEU,KAAK,CAAC,IAAI,eAAe;IAE7C,IAAI,CAACD,WAAW;QACf,OAAOD,QAAQG,MAAM;IACtB;IAEA,sDAAsD;IACtD,MAAMC,QAAQH,UAAUI,KAAK,CAAC,cAAcC,MAAM,CAAC,CAACC,OAASA,SAAS;IAEtE,IAAK,IAAIC,IAAI,GAAGA,IAAIJ,MAAMK,MAAM,EAAED,KAAK,EAAG;QACzC,MAAME,WAAWN,KAAK,CAACI,EAAE;QACzB,MAAMG,UAAUP,KAAK,CAACI,IAAI,EAAE;QAE5B,IAAI,CAACE,YAAY,CAACC,SAAS;YAC1B,MAAM,IAAIZ,MAAM,CAAC,8BAA8B,EAAEP,GAAG;QACrD;QAEA,IAAIkB,aAAa,KAAK;YACrB,gCAAgC;YAChCE,kBAAkBD;YAClBX,UAAUA,QAAQa,OAAO,CAACF;QAC3B,OAAO,IAAID,aAAa,MAAM;YAC7B,8BAA8B;YAC9BE,kBAAkBD;YAClBX,UAAUA,QAAQc,KAAK,CAACH;QACzB,OAAO;YACN,oCAAoC;YACpC,MAAMI,QAAQJ,QAAQI,KAAK,CAAC;YAC5B,IAAI,CAACA,OAAO;gBACX,MAAM,IAAIhB,MAAM,CAAC,sBAAsB,EAAEY,SAAS;YACnD;YAEA,MAAM,GAAGK,WAAWC,KAAK,GAAGF;YAC5BH,kBAAkBK;YAClB,MAAMC,SAASC,SAASH,WAAW;YAEnC,IAAIN,aAAa,KAAK;gBACrBV,UAAUA,QAAQoB,GAAG,CAACF,QAAQD;YAC/B,OAAO,IAAIP,aAAa,KAAK;gBAC5BV,UAAUA,QAAQqB,QAAQ,CAACH,QAAQD;YACpC,OAAO;gBACN,MAAM,IAAIlB,MAAM,CAAC,kBAAkB,EAAEW,UAAU;YAChD;QACD;IACD;IAEA,OAAOV,QAAQG,MAAM;AACtB;AAEA,kCAAkC,GAClC,OAAO,MAAMmB,wBAAwB;IAAC;IAAM;IAAK;IAAK;IAAK;IAAK;IAAK;IAAK;IAAK;CAAI,CAAU;AAK7F;;;;;CAKC,GACD,OAAO,SAASV,kBAAkBW,CAAS;IAC1C,IAAI,CAACD,sBAAsBE,QAAQ,CAACD,IAA4B;QAC/D,MAAM,IAAIxB,MAAM,CAAC,cAAc,EAAEwB,GAAG;IACrC;AACD"}
|