@kikiutils/shared 10.1.2 → 10.2.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.
- package/dist/consola.cjs.map +1 -1
- package/dist/consola.mjs.map +1 -1
- package/dist/datetime.cjs.map +1 -1
- package/dist/datetime.mjs.map +1 -1
- package/dist/general.cjs.map +1 -1
- package/dist/general.mjs.map +1 -1
- package/dist/hash.cjs.map +1 -1
- package/dist/hash.mjs.map +1 -1
- package/dist/math.cjs.map +1 -1
- package/dist/math.mjs.map +1 -1
- package/dist/number.cjs.map +1 -1
- package/dist/number.mjs.map +1 -1
- package/dist/object.cjs +55 -0
- package/dist/object.cjs.map +1 -0
- package/dist/object.d.ts +25 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.mjs +53 -0
- package/dist/object.mjs.map +1 -0
- package/dist/pino.cjs.map +1 -1
- package/dist/pino.mjs.map +1 -1
- package/dist/storage/enhanced/local/core.cjs.map +1 -1
- package/dist/storage/enhanced/local/core.mjs.map +1 -1
- package/dist/storage/enhanced/redis/core.cjs.map +1 -1
- package/dist/storage/enhanced/redis/core.mjs.map +1 -1
- package/dist/url.cjs.map +1 -1
- package/dist/url.mjs.map +1 -1
- package/dist/web.cjs.map +1 -1
- package/dist/web.mjs.map +1 -1
- package/package.json +9 -9
- package/src/object.ts +61 -0
package/dist/consola.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consola.cjs","sources":["../src/consola.ts"],"sourcesContent":["import { createConsola } from 'consola';\n\n/**\n * A consola logger instance.\n *\n * The logger's level is determined based on the `CONSOLA_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `CONSOLA_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `0`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://github.com/unjs/consola?tab=readme-ov-file#log-level).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/consola';\n *\n * logger.info('test'); // ℹ test 3:56:30 AM\n *\n * // Manually change the level\n * logger.level = 3;\n * ```\n */\nexport const consolaLogger = createConsola();\nexport const logger = consolaLogger;\nif (process.env.CONSOLA_LOGGER_LEVEL !== undefined) consolaLogger.level = +process.env.CONSOLA_LOGGER_LEVEL;\nelse consolaLogger.level = process.env.NODE_ENV === 'production' ? 0 : consolaLogger.level;\n"],"names":["createConsola"],"mappings":";;;;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;
|
|
1
|
+
{"version":3,"file":"consola.cjs","sources":["../src/consola.ts"],"sourcesContent":["import { createConsola } from 'consola';\n\n/**\n * A consola logger instance.\n *\n * The logger's level is determined based on the `CONSOLA_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `CONSOLA_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `0`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://github.com/unjs/consola?tab=readme-ov-file#log-level).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/consola';\n *\n * logger.info('test'); // ℹ test 3:56:30 AM\n *\n * // Manually change the level\n * logger.level = 3;\n * ```\n */\nexport const consolaLogger = createConsola();\nexport const logger = consolaLogger;\nif (process.env.CONSOLA_LOGGER_LEVEL !== undefined) consolaLogger.level = +process.env.CONSOLA_LOGGER_LEVEL;\nelse consolaLogger.level = process.env.NODE_ENV === 'production' ? 0 : consolaLogger.level;\n"],"names":["createConsola"],"mappings":";;;;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,aAAa,GAAGA,qBAAa;AACnC,MAAM,MAAM,GAAG;AACtB,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,KAAK,SAAS;IAAE,aAAa,CAAC,KAAK,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB;;IACtG,aAAa,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,GAAG,CAAC,GAAG,aAAa,CAAC,KAAK;;;;;"}
|
package/dist/consola.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consola.mjs","sources":["../src/consola.ts"],"sourcesContent":["import { createConsola } from 'consola';\n\n/**\n * A consola logger instance.\n *\n * The logger's level is determined based on the `CONSOLA_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `CONSOLA_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `0`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://github.com/unjs/consola?tab=readme-ov-file#log-level).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/consola';\n *\n * logger.info('test'); // ℹ test 3:56:30 AM\n *\n * // Manually change the level\n * logger.level = 3;\n * ```\n */\nexport const consolaLogger = createConsola();\nexport const logger = consolaLogger;\nif (process.env.CONSOLA_LOGGER_LEVEL !== undefined) consolaLogger.level = +process.env.CONSOLA_LOGGER_LEVEL;\nelse consolaLogger.level = process.env.NODE_ENV === 'production' ? 0 : consolaLogger.level;\n"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;
|
|
1
|
+
{"version":3,"file":"consola.mjs","sources":["../src/consola.ts"],"sourcesContent":["import { createConsola } from 'consola';\n\n/**\n * A consola logger instance.\n *\n * The logger's level is determined based on the `CONSOLA_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `CONSOLA_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `0`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://github.com/unjs/consola?tab=readme-ov-file#log-level).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/consola';\n *\n * logger.info('test'); // ℹ test 3:56:30 AM\n *\n * // Manually change the level\n * logger.level = 3;\n * ```\n */\nexport const consolaLogger = createConsola();\nexport const logger = consolaLogger;\nif (process.env.CONSOLA_LOGGER_LEVEL !== undefined) consolaLogger.level = +process.env.CONSOLA_LOGGER_LEVEL;\nelse consolaLogger.level = process.env.NODE_ENV === 'production' ? 0 : consolaLogger.level;\n"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,aAAa,GAAG,aAAa;AACnC,MAAM,MAAM,GAAG;AACtB,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,KAAK,SAAS;IAAE,aAAa,CAAC,KAAK,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB;;IACtG,aAAa,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,GAAG,CAAC,GAAG,aAAa,CAAC,KAAK;;;;"}
|
package/dist/datetime.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime.cjs","sources":["../src/datetime.ts"],"sourcesContent":["import {\n format as dateFnsFormat,\n endOfDay,\n endOfMonth,\n endOfWeek,\n startOfDay,\n startOfMonth,\n startOfWeek,\n subDays,\n subMonths,\n subWeeks,\n} from 'date-fns';\nimport type {\n DateArg,\n Day,\n FormatOptions,\n} from 'date-fns';\n\nexport type DateRangeType = 'lastMonth' | 'lastWeek' | 'thisMonth' | 'thisWeek' | 'today' | 'yesterday';\n\n/**\n * Formats a given date, timestamp, or date string into a specified format.\n *\n * This function is a wrapper around `date-fns/format`.\n *\n * @param {DateArg<Date>} date - The input date to format. Can be a Date object, a timestamp, or a string.\n * @param {string} [format] - The target format string.\n * @param {FormatOptions} [options] - Optional formatting options passed to `date-fns/format`.\n *\n * @returns {string} The formatted date string.\n *\n * @example\n * ```typescript\n * import { formatDate } from '@kikiutils/shared/datetime';\n *\n * // Format a Date object\n * console.log(formatDate(new Date(), 'yyyy-MM-dd')); // 2024-07-10\n *\n * // Format a timestamp\n * console.log(formatDate(1657814400000, 'yyyy-MM-dd')); // 2022-07-15\n *\n * // Format a date string\n * console.log(formatDate('2024-07-10T00:00:00Z', 'yyyy-MM-dd')); // 2024-07-10\n * ```\n *\n * @see https://date-fns.org/docs/format\n */\nexport function formatDate(date: DateArg<Date> & {}, format: string = 'yyyy-MM-dd HH:mm:ss', options?: FormatOptions) {\n return dateFnsFormat(date, format, options);\n}\n\n/**\n * Get the date range (start and end) based on a given date and range type.\n *\n * Supports common range types like 'lastMonth', 'lastWeek', 'thisMonth', 'thisWeek', 'today', and 'yesterday'.\n *\n * @param {Date} date - The reference date.\n * @param {DateRangeType} type - The range type to compute.\n * @param {object} [options] - Optional settings.\n * @param {boolean} [options.setEndDateToNextDayStart] - If true, set `endDate` to 00:00:00.000 of the next day.\n * @param {Day} [options.weekStartsOn] - The start day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).\n *\n * @returns {{ startDate: Date, endDate: Date }} An object with `startDate` and `endDate`.\n *\n * @example\n * ```typescript\n * import { getDateRangeFromDate } from '@kikiutils/shared/datetime';\n *\n * // Get the date range for last month\n * const date = new Date('2023-07-01');\n * console.log(getDateRangeFromDate(date, 'lastMonth'));\n * // { startDate: 2023-06-01T00:00:00.000Z, endDate: 2023-06-30T23:59:59.999Z }\n *\n * // Get this week's range with Sunday as the first day\n * console.log(getDateRangeFromDate(date, 'thisWeek', { weekStartsOn: 0 }));\n * // { startDate: 2023-06-25T00:00:00.000Z, endDate: 2023-07-01T23:59:59.999Z }\n * ```\n */\nexport function getDateRangeFromDate(\n date: Date,\n type: DateRangeType,\n options?: {\n setEndDateToNextDayStart?: boolean;\n weekStartsOn?: Day;\n },\n) {\n let endDate: Date;\n let startDate: Date;\n switch (type) {\n case 'lastMonth':\n {\n const lastMonth = subMonths(date, 1);\n endDate = endOfMonth(lastMonth);\n startDate = startOfMonth(lastMonth);\n }\n\n break;\n case 'lastWeek':\n {\n const lastWeek = subWeeks(date, 1);\n endDate = endOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n }\n\n break;\n case 'thisMonth':\n endDate = endOfMonth(date);\n startDate = startOfMonth(date);\n break;\n case 'thisWeek':\n endDate = endOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n break;\n case 'today':\n endDate = endOfDay(date);\n startDate = startOfDay(date);\n break;\n case 'yesterday':\n {\n const yesterday = subDays(date, 1);\n endDate = endOfDay(yesterday);\n startDate = startOfDay(yesterday);\n }\n\n break;\n default: throw new Error(`Unsupported date range type: ${type}.`);\n }\n\n if (options?.setEndDateToNextDayStart) endDate.setHours(24, 0, 0, 0);\n return {\n endDate,\n startDate,\n };\n}\n\n/**\n * Returns a `Date` object set to midnight (00:00:00) of today, with an optional day offset.\n *\n * @param {number} [offsetDays] - Number of days to offset from today. Can be negative.\n *\n * @returns {Date} A `Date` object at 00:00:00 of the offset day.\n *\n * @example\n * ```typescript\n * import { getMidnightDateFromToday } from '@kikiutils/shared/datetime';\n *\n * console.log(getMidnightDateFromToday()); // today at 00:00:00\n * console.log(getMidnightDateFromToday(3)); // 3 days from today at 00:00:00\n * console.log(getMidnightDateFromToday(-1)); // yesterday at 00:00:00\n * ```\n */\nexport function getMidnightDateFromToday(offsetDays: number = 0) {\n const date = new Date();\n date.setDate(date.getDate() + offsetDays);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n"],"names":["dateFnsFormat","subMonths","endOfMonth","startOfMonth","subWeeks","endOfWeek","startOfWeek","endOfDay","startOfDay","subDays"],"mappings":";;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,UAAU,CAAC,IAAwB,EAAE,
|
|
1
|
+
{"version":3,"file":"datetime.cjs","sources":["../src/datetime.ts"],"sourcesContent":["import {\n format as dateFnsFormat,\n endOfDay,\n endOfMonth,\n endOfWeek,\n startOfDay,\n startOfMonth,\n startOfWeek,\n subDays,\n subMonths,\n subWeeks,\n} from 'date-fns';\nimport type {\n DateArg,\n Day,\n FormatOptions,\n} from 'date-fns';\n\nexport type DateRangeType = 'lastMonth' | 'lastWeek' | 'thisMonth' | 'thisWeek' | 'today' | 'yesterday';\n\n/**\n * Formats a given date, timestamp, or date string into a specified format.\n *\n * This function is a wrapper around `date-fns/format`.\n *\n * @param {DateArg<Date>} date - The input date to format. Can be a Date object, a timestamp, or a string.\n * @param {string} [format] - The target format string.\n * @param {FormatOptions} [options] - Optional formatting options passed to `date-fns/format`.\n *\n * @returns {string} The formatted date string.\n *\n * @example\n * ```typescript\n * import { formatDate } from '@kikiutils/shared/datetime';\n *\n * // Format a Date object\n * console.log(formatDate(new Date(), 'yyyy-MM-dd')); // 2024-07-10\n *\n * // Format a timestamp\n * console.log(formatDate(1657814400000, 'yyyy-MM-dd')); // 2022-07-15\n *\n * // Format a date string\n * console.log(formatDate('2024-07-10T00:00:00Z', 'yyyy-MM-dd')); // 2024-07-10\n * ```\n *\n * @see https://date-fns.org/docs/format\n */\nexport function formatDate(date: DateArg<Date> & {}, format: string = 'yyyy-MM-dd HH:mm:ss', options?: FormatOptions) {\n return dateFnsFormat(date, format, options);\n}\n\n/**\n * Get the date range (start and end) based on a given date and range type.\n *\n * Supports common range types like 'lastMonth', 'lastWeek', 'thisMonth', 'thisWeek', 'today', and 'yesterday'.\n *\n * @param {Date} date - The reference date.\n * @param {DateRangeType} type - The range type to compute.\n * @param {object} [options] - Optional settings.\n * @param {boolean} [options.setEndDateToNextDayStart] - If true, set `endDate` to 00:00:00.000 of the next day.\n * @param {Day} [options.weekStartsOn] - The start day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).\n *\n * @returns {{ startDate: Date, endDate: Date }} An object with `startDate` and `endDate`.\n *\n * @example\n * ```typescript\n * import { getDateRangeFromDate } from '@kikiutils/shared/datetime';\n *\n * // Get the date range for last month\n * const date = new Date('2023-07-01');\n * console.log(getDateRangeFromDate(date, 'lastMonth'));\n * // { startDate: 2023-06-01T00:00:00.000Z, endDate: 2023-06-30T23:59:59.999Z }\n *\n * // Get this week's range with Sunday as the first day\n * console.log(getDateRangeFromDate(date, 'thisWeek', { weekStartsOn: 0 }));\n * // { startDate: 2023-06-25T00:00:00.000Z, endDate: 2023-07-01T23:59:59.999Z }\n * ```\n */\nexport function getDateRangeFromDate(\n date: Date,\n type: DateRangeType,\n options?: {\n setEndDateToNextDayStart?: boolean;\n weekStartsOn?: Day;\n },\n) {\n let endDate: Date;\n let startDate: Date;\n switch (type) {\n case 'lastMonth':\n {\n const lastMonth = subMonths(date, 1);\n endDate = endOfMonth(lastMonth);\n startDate = startOfMonth(lastMonth);\n }\n\n break;\n case 'lastWeek':\n {\n const lastWeek = subWeeks(date, 1);\n endDate = endOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n }\n\n break;\n case 'thisMonth':\n endDate = endOfMonth(date);\n startDate = startOfMonth(date);\n break;\n case 'thisWeek':\n endDate = endOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n break;\n case 'today':\n endDate = endOfDay(date);\n startDate = startOfDay(date);\n break;\n case 'yesterday':\n {\n const yesterday = subDays(date, 1);\n endDate = endOfDay(yesterday);\n startDate = startOfDay(yesterday);\n }\n\n break;\n default: throw new Error(`Unsupported date range type: ${type}.`);\n }\n\n if (options?.setEndDateToNextDayStart) endDate.setHours(24, 0, 0, 0);\n return {\n endDate,\n startDate,\n };\n}\n\n/**\n * Returns a `Date` object set to midnight (00:00:00) of today, with an optional day offset.\n *\n * @param {number} [offsetDays] - Number of days to offset from today. Can be negative.\n *\n * @returns {Date} A `Date` object at 00:00:00 of the offset day.\n *\n * @example\n * ```typescript\n * import { getMidnightDateFromToday } from '@kikiutils/shared/datetime';\n *\n * console.log(getMidnightDateFromToday()); // today at 00:00:00\n * console.log(getMidnightDateFromToday(3)); // 3 days from today at 00:00:00\n * console.log(getMidnightDateFromToday(-1)); // yesterday at 00:00:00\n * ```\n */\nexport function getMidnightDateFromToday(offsetDays: number = 0) {\n const date = new Date();\n date.setDate(date.getDate() + offsetDays);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n"],"names":["dateFnsFormat","subMonths","endOfMonth","startOfMonth","subWeeks","endOfWeek","startOfWeek","endOfDay","startOfDay","subDays"],"mappings":";;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,UAAU,CAAC,IAAwB,EAAE,MAAA,GAAiB,qBAAqB,EAAE,OAAuB,EAAA;IAChH,OAAOA,cAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC;AAC/C;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;SACa,oBAAoB,CAChC,IAAU,EACV,IAAmB,EACnB,OAGC,EAAA;AAED,IAAA,IAAI,OAAa;AACjB,IAAA,IAAI,SAAe;IACnB,QAAQ,IAAI;AACR,QAAA,KAAK,WAAW;YACZ;gBACI,MAAM,SAAS,GAAGC,iBAAS,CAAC,IAAI,EAAE,CAAC,CAAC;AACpC,gBAAA,OAAO,GAAGC,kBAAU,CAAC,SAAS,CAAC;AAC/B,gBAAA,SAAS,GAAGC,oBAAY,CAAC,SAAS,CAAC;;YAGvC;AACJ,QAAA,KAAK,UAAU;YACX;gBACI,MAAM,QAAQ,GAAGC,gBAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AAClC,gBAAA,OAAO,GAAGC,iBAAS,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,IAAI,CAAC,EAAE,CAAC;AAC3E,gBAAA,SAAS,GAAGC,mBAAW,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,IAAI,CAAC,EAAE,CAAC;;YAGnF;AACJ,QAAA,KAAK,WAAW;AACZ,YAAA,OAAO,GAAG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;;;;;"}
|
package/dist/datetime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime.mjs","sources":["../src/datetime.ts"],"sourcesContent":["import {\n format as dateFnsFormat,\n endOfDay,\n endOfMonth,\n endOfWeek,\n startOfDay,\n startOfMonth,\n startOfWeek,\n subDays,\n subMonths,\n subWeeks,\n} from 'date-fns';\nimport type {\n DateArg,\n Day,\n FormatOptions,\n} from 'date-fns';\n\nexport type DateRangeType = 'lastMonth' | 'lastWeek' | 'thisMonth' | 'thisWeek' | 'today' | 'yesterday';\n\n/**\n * Formats a given date, timestamp, or date string into a specified format.\n *\n * This function is a wrapper around `date-fns/format`.\n *\n * @param {DateArg<Date>} date - The input date to format. Can be a Date object, a timestamp, or a string.\n * @param {string} [format] - The target format string.\n * @param {FormatOptions} [options] - Optional formatting options passed to `date-fns/format`.\n *\n * @returns {string} The formatted date string.\n *\n * @example\n * ```typescript\n * import { formatDate } from '@kikiutils/shared/datetime';\n *\n * // Format a Date object\n * console.log(formatDate(new Date(), 'yyyy-MM-dd')); // 2024-07-10\n *\n * // Format a timestamp\n * console.log(formatDate(1657814400000, 'yyyy-MM-dd')); // 2022-07-15\n *\n * // Format a date string\n * console.log(formatDate('2024-07-10T00:00:00Z', 'yyyy-MM-dd')); // 2024-07-10\n * ```\n *\n * @see https://date-fns.org/docs/format\n */\nexport function formatDate(date: DateArg<Date> & {}, format: string = 'yyyy-MM-dd HH:mm:ss', options?: FormatOptions) {\n return dateFnsFormat(date, format, options);\n}\n\n/**\n * Get the date range (start and end) based on a given date and range type.\n *\n * Supports common range types like 'lastMonth', 'lastWeek', 'thisMonth', 'thisWeek', 'today', and 'yesterday'.\n *\n * @param {Date} date - The reference date.\n * @param {DateRangeType} type - The range type to compute.\n * @param {object} [options] - Optional settings.\n * @param {boolean} [options.setEndDateToNextDayStart] - If true, set `endDate` to 00:00:00.000 of the next day.\n * @param {Day} [options.weekStartsOn] - The start day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).\n *\n * @returns {{ startDate: Date, endDate: Date }} An object with `startDate` and `endDate`.\n *\n * @example\n * ```typescript\n * import { getDateRangeFromDate } from '@kikiutils/shared/datetime';\n *\n * // Get the date range for last month\n * const date = new Date('2023-07-01');\n * console.log(getDateRangeFromDate(date, 'lastMonth'));\n * // { startDate: 2023-06-01T00:00:00.000Z, endDate: 2023-06-30T23:59:59.999Z }\n *\n * // Get this week's range with Sunday as the first day\n * console.log(getDateRangeFromDate(date, 'thisWeek', { weekStartsOn: 0 }));\n * // { startDate: 2023-06-25T00:00:00.000Z, endDate: 2023-07-01T23:59:59.999Z }\n * ```\n */\nexport function getDateRangeFromDate(\n date: Date,\n type: DateRangeType,\n options?: {\n setEndDateToNextDayStart?: boolean;\n weekStartsOn?: Day;\n },\n) {\n let endDate: Date;\n let startDate: Date;\n switch (type) {\n case 'lastMonth':\n {\n const lastMonth = subMonths(date, 1);\n endDate = endOfMonth(lastMonth);\n startDate = startOfMonth(lastMonth);\n }\n\n break;\n case 'lastWeek':\n {\n const lastWeek = subWeeks(date, 1);\n endDate = endOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n }\n\n break;\n case 'thisMonth':\n endDate = endOfMonth(date);\n startDate = startOfMonth(date);\n break;\n case 'thisWeek':\n endDate = endOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n break;\n case 'today':\n endDate = endOfDay(date);\n startDate = startOfDay(date);\n break;\n case 'yesterday':\n {\n const yesterday = subDays(date, 1);\n endDate = endOfDay(yesterday);\n startDate = startOfDay(yesterday);\n }\n\n break;\n default: throw new Error(`Unsupported date range type: ${type}.`);\n }\n\n if (options?.setEndDateToNextDayStart) endDate.setHours(24, 0, 0, 0);\n return {\n endDate,\n startDate,\n };\n}\n\n/**\n * Returns a `Date` object set to midnight (00:00:00) of today, with an optional day offset.\n *\n * @param {number} [offsetDays] - Number of days to offset from today. Can be negative.\n *\n * @returns {Date} A `Date` object at 00:00:00 of the offset day.\n *\n * @example\n * ```typescript\n * import { getMidnightDateFromToday } from '@kikiutils/shared/datetime';\n *\n * console.log(getMidnightDateFromToday()); // today at 00:00:00\n * console.log(getMidnightDateFromToday(3)); // 3 days from today at 00:00:00\n * console.log(getMidnightDateFromToday(-1)); // yesterday at 00:00:00\n * ```\n */\nexport function getMidnightDateFromToday(offsetDays: number = 0) {\n const date = new Date();\n date.setDate(date.getDate() + offsetDays);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n"],"names":["format","dateFnsFormat"],"mappings":";;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,UAAU,CAAC,IAAwB,EAAEA,
|
|
1
|
+
{"version":3,"file":"datetime.mjs","sources":["../src/datetime.ts"],"sourcesContent":["import {\n format as dateFnsFormat,\n endOfDay,\n endOfMonth,\n endOfWeek,\n startOfDay,\n startOfMonth,\n startOfWeek,\n subDays,\n subMonths,\n subWeeks,\n} from 'date-fns';\nimport type {\n DateArg,\n Day,\n FormatOptions,\n} from 'date-fns';\n\nexport type DateRangeType = 'lastMonth' | 'lastWeek' | 'thisMonth' | 'thisWeek' | 'today' | 'yesterday';\n\n/**\n * Formats a given date, timestamp, or date string into a specified format.\n *\n * This function is a wrapper around `date-fns/format`.\n *\n * @param {DateArg<Date>} date - The input date to format. Can be a Date object, a timestamp, or a string.\n * @param {string} [format] - The target format string.\n * @param {FormatOptions} [options] - Optional formatting options passed to `date-fns/format`.\n *\n * @returns {string} The formatted date string.\n *\n * @example\n * ```typescript\n * import { formatDate } from '@kikiutils/shared/datetime';\n *\n * // Format a Date object\n * console.log(formatDate(new Date(), 'yyyy-MM-dd')); // 2024-07-10\n *\n * // Format a timestamp\n * console.log(formatDate(1657814400000, 'yyyy-MM-dd')); // 2022-07-15\n *\n * // Format a date string\n * console.log(formatDate('2024-07-10T00:00:00Z', 'yyyy-MM-dd')); // 2024-07-10\n * ```\n *\n * @see https://date-fns.org/docs/format\n */\nexport function formatDate(date: DateArg<Date> & {}, format: string = 'yyyy-MM-dd HH:mm:ss', options?: FormatOptions) {\n return dateFnsFormat(date, format, options);\n}\n\n/**\n * Get the date range (start and end) based on a given date and range type.\n *\n * Supports common range types like 'lastMonth', 'lastWeek', 'thisMonth', 'thisWeek', 'today', and 'yesterday'.\n *\n * @param {Date} date - The reference date.\n * @param {DateRangeType} type - The range type to compute.\n * @param {object} [options] - Optional settings.\n * @param {boolean} [options.setEndDateToNextDayStart] - If true, set `endDate` to 00:00:00.000 of the next day.\n * @param {Day} [options.weekStartsOn] - The start day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).\n *\n * @returns {{ startDate: Date, endDate: Date }} An object with `startDate` and `endDate`.\n *\n * @example\n * ```typescript\n * import { getDateRangeFromDate } from '@kikiutils/shared/datetime';\n *\n * // Get the date range for last month\n * const date = new Date('2023-07-01');\n * console.log(getDateRangeFromDate(date, 'lastMonth'));\n * // { startDate: 2023-06-01T00:00:00.000Z, endDate: 2023-06-30T23:59:59.999Z }\n *\n * // Get this week's range with Sunday as the first day\n * console.log(getDateRangeFromDate(date, 'thisWeek', { weekStartsOn: 0 }));\n * // { startDate: 2023-06-25T00:00:00.000Z, endDate: 2023-07-01T23:59:59.999Z }\n * ```\n */\nexport function getDateRangeFromDate(\n date: Date,\n type: DateRangeType,\n options?: {\n setEndDateToNextDayStart?: boolean;\n weekStartsOn?: Day;\n },\n) {\n let endDate: Date;\n let startDate: Date;\n switch (type) {\n case 'lastMonth':\n {\n const lastMonth = subMonths(date, 1);\n endDate = endOfMonth(lastMonth);\n startDate = startOfMonth(lastMonth);\n }\n\n break;\n case 'lastWeek':\n {\n const lastWeek = subWeeks(date, 1);\n endDate = endOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(lastWeek, { weekStartsOn: options?.weekStartsOn ?? 1 });\n }\n\n break;\n case 'thisMonth':\n endDate = endOfMonth(date);\n startDate = startOfMonth(date);\n break;\n case 'thisWeek':\n endDate = endOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n startDate = startOfWeek(date, { weekStartsOn: options?.weekStartsOn ?? 1 });\n break;\n case 'today':\n endDate = endOfDay(date);\n startDate = startOfDay(date);\n break;\n case 'yesterday':\n {\n const yesterday = subDays(date, 1);\n endDate = endOfDay(yesterday);\n startDate = startOfDay(yesterday);\n }\n\n break;\n default: throw new Error(`Unsupported date range type: ${type}.`);\n }\n\n if (options?.setEndDateToNextDayStart) endDate.setHours(24, 0, 0, 0);\n return {\n endDate,\n startDate,\n };\n}\n\n/**\n * Returns a `Date` object set to midnight (00:00:00) of today, with an optional day offset.\n *\n * @param {number} [offsetDays] - Number of days to offset from today. Can be negative.\n *\n * @returns {Date} A `Date` object at 00:00:00 of the offset day.\n *\n * @example\n * ```typescript\n * import { getMidnightDateFromToday } from '@kikiutils/shared/datetime';\n *\n * console.log(getMidnightDateFromToday()); // today at 00:00:00\n * console.log(getMidnightDateFromToday(3)); // 3 days from today at 00:00:00\n * console.log(getMidnightDateFromToday(-1)); // yesterday at 00:00:00\n * ```\n */\nexport function getMidnightDateFromToday(offsetDays: number = 0) {\n const date = new Date();\n date.setDate(date.getDate() + offsetDays);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n"],"names":["format","dateFnsFormat"],"mappings":";;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,UAAU,CAAC,IAAwB,EAAEA,QAAA,GAAiB,qBAAqB,EAAE,OAAuB,EAAA;IAChH,OAAOC,MAAa,CAAC,IAAI,EAAED,QAAM,EAAE,OAAO,CAAC;AAC/C;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;SACa,oBAAoB,CAChC,IAAU,EACV,IAAmB,EACnB,OAGC,EAAA;AAED,IAAA,IAAI,OAAa;AACjB,IAAA,IAAI,S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CAAC;;YAGrC;QACJ,SAAS,MAAM,IAAI,KAAK,CAAC,CAAA,6BAAA,EAAgC,IAAI,CAAA,CAAA,CAAG,CAAC;;IAGrE,IAAI,OAAO,EAAE,wBAAwB;QAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACpE,OAAO;QACH,OAAO;QACP,SAAS;KACZ;AACL;AAEA;;;;;;;;;;;;;;;AAeG;AACG,SAAU,wBAAwB,CAAC,UAAA,GAAqB,CAAC,EAAA;AAC3D,IAAA,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE;IACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,UAAU,CAAC;IACzC,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACzB,IAAA,OAAO,IAAI;AACf;;;;"}
|
package/dist/general.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general.cjs","sources":["../src/general.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\n\n/**\n * Extracts the first value from an array or returns the value itself if it's not an array.\n *\n * - If `value` is an array, returns the first element.\n * - If `value` is not an array, returns `value` directly.\n * - If the result is `null` or `undefined`, and `defaultValue` is provided, returns `defaultValue` instead.\n *\n * @template T - The type of the input value(s).\n * @template D - The type of the default value (if provided).\n *\n * @param {T | T[]} value - A single value or an array of values.\n * @param {D} [defaultValue] - A fallback value if the result is `null` or `undefined`.\n *\n * @returns {T | D | undefined} The first value or the fallback.\n *\n * @example\n * ```typescript\n * import { extractFirstValue } from '@kikiutils/shared/general';\n *\n * console.log(extractFirstValue([1, 2, 3])); // 1\n * console.log(extractFirstValue('hello')); // hello\n * console.log(extractFirstValue([], 'default')); // default\n * console.log(extractFirstValue(undefined, 'fallback')); // fallback\n * ```\n */\nexport function extractFirstValue<T>(value: T | T[]): T | undefined;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue: D): D | NonNullable<T>;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue?: D) {\n return (Array.isArray(value) ? value[0] : value) ?? defaultValue;\n}\n\n/* eslint-enable jsdoc/check-param-names */\n"],"names":[],"mappings":";;AAAA;
|
|
1
|
+
{"version":3,"file":"general.cjs","sources":["../src/general.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\n\n/**\n * Extracts the first value from an array or returns the value itself if it's not an array.\n *\n * - If `value` is an array, returns the first element.\n * - If `value` is not an array, returns `value` directly.\n * - If the result is `null` or `undefined`, and `defaultValue` is provided, returns `defaultValue` instead.\n *\n * @template T - The type of the input value(s).\n * @template D - The type of the default value (if provided).\n *\n * @param {T | T[]} value - A single value or an array of values.\n * @param {D} [defaultValue] - A fallback value if the result is `null` or `undefined`.\n *\n * @returns {T | D | undefined} The first value or the fallback.\n *\n * @example\n * ```typescript\n * import { extractFirstValue } from '@kikiutils/shared/general';\n *\n * console.log(extractFirstValue([1, 2, 3])); // 1\n * console.log(extractFirstValue('hello')); // hello\n * console.log(extractFirstValue([], 'default')); // default\n * console.log(extractFirstValue(undefined, 'fallback')); // fallback\n * ```\n */\nexport function extractFirstValue<T>(value: T | T[]): T | undefined;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue: D): D | NonNullable<T>;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue?: D) {\n return (Array.isArray(value) ? value[0] : value) ?? defaultValue;\n}\n\n/* eslint-enable jsdoc/check-param-names */\n"],"names":[],"mappings":";;AAAA;AA6BM,SAAU,iBAAiB,CAAO,KAAc,EAAE,YAAgB,EAAA;IACpE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,YAAY;AACpE;AAEA;;;;"}
|
package/dist/general.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general.mjs","sources":["../src/general.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\n\n/**\n * Extracts the first value from an array or returns the value itself if it's not an array.\n *\n * - If `value` is an array, returns the first element.\n * - If `value` is not an array, returns `value` directly.\n * - If the result is `null` or `undefined`, and `defaultValue` is provided, returns `defaultValue` instead.\n *\n * @template T - The type of the input value(s).\n * @template D - The type of the default value (if provided).\n *\n * @param {T | T[]} value - A single value or an array of values.\n * @param {D} [defaultValue] - A fallback value if the result is `null` or `undefined`.\n *\n * @returns {T | D | undefined} The first value or the fallback.\n *\n * @example\n * ```typescript\n * import { extractFirstValue } from '@kikiutils/shared/general';\n *\n * console.log(extractFirstValue([1, 2, 3])); // 1\n * console.log(extractFirstValue('hello')); // hello\n * console.log(extractFirstValue([], 'default')); // default\n * console.log(extractFirstValue(undefined, 'fallback')); // fallback\n * ```\n */\nexport function extractFirstValue<T>(value: T | T[]): T | undefined;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue: D): D | NonNullable<T>;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue?: D) {\n return (Array.isArray(value) ? value[0] : value) ?? defaultValue;\n}\n\n/* eslint-enable jsdoc/check-param-names */\n"],"names":[],"mappings":"AAAA;
|
|
1
|
+
{"version":3,"file":"general.mjs","sources":["../src/general.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\n\n/**\n * Extracts the first value from an array or returns the value itself if it's not an array.\n *\n * - If `value` is an array, returns the first element.\n * - If `value` is not an array, returns `value` directly.\n * - If the result is `null` or `undefined`, and `defaultValue` is provided, returns `defaultValue` instead.\n *\n * @template T - The type of the input value(s).\n * @template D - The type of the default value (if provided).\n *\n * @param {T | T[]} value - A single value or an array of values.\n * @param {D} [defaultValue] - A fallback value if the result is `null` or `undefined`.\n *\n * @returns {T | D | undefined} The first value or the fallback.\n *\n * @example\n * ```typescript\n * import { extractFirstValue } from '@kikiutils/shared/general';\n *\n * console.log(extractFirstValue([1, 2, 3])); // 1\n * console.log(extractFirstValue('hello')); // hello\n * console.log(extractFirstValue([], 'default')); // default\n * console.log(extractFirstValue(undefined, 'fallback')); // fallback\n * ```\n */\nexport function extractFirstValue<T>(value: T | T[]): T | undefined;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue: D): D | NonNullable<T>;\nexport function extractFirstValue<T, D>(value: T | T[], defaultValue?: D) {\n return (Array.isArray(value) ? value[0] : value) ?? defaultValue;\n}\n\n/* eslint-enable jsdoc/check-param-names */\n"],"names":[],"mappings":"AAAA;AA6BM,SAAU,iBAAiB,CAAO,KAAc,EAAE,YAAgB,EAAA;IACpE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,YAAY;AACpE;AAEA;;;;"}
|
package/dist/hash.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.cjs","sources":["../src/hash.ts"],"sourcesContent":["/**\n * This file provides a set of functions for creating SHA-3 hash digests\n * using different bit lengths (224, 256, 384, 512).\n * These functions use the [@noble/hashes](https://github.com/paulmillr/noble-hashes) library to generate the hashes.\n * Can be used in the browser, mainly for Nuxt/Vue and other frameworks compiled and executed in the browser.\n *\n * @example\n * ```typescript\n * import { sha3256 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n * ```\n */\n\nimport {\n sha3_224,\n sha3_256,\n sha3_384,\n sha3_512,\n} from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport const sha3224 = (data: string | Uint8Array) => bytesToHex(sha3_224(data));\nexport const sha3256 = (data: string | Uint8Array) => bytesToHex(sha3_256(data));\nexport const sha3384 = (data: string | Uint8Array) => bytesToHex(sha3_384(data));\nexport const sha3512 = (data: string | Uint8Array) => bytesToHex(sha3_512(data));\n"],"names":["bytesToHex","sha3_224","sha3_256","sha3_384","sha3_512"],"mappings":";;;;;AAAA;;;;;;;;;;;;AAYG;
|
|
1
|
+
{"version":3,"file":"hash.cjs","sources":["../src/hash.ts"],"sourcesContent":["/**\n * This file provides a set of functions for creating SHA-3 hash digests\n * using different bit lengths (224, 256, 384, 512).\n * These functions use the [@noble/hashes](https://github.com/paulmillr/noble-hashes) library to generate the hashes.\n * Can be used in the browser, mainly for Nuxt/Vue and other frameworks compiled and executed in the browser.\n *\n * @example\n * ```typescript\n * import { sha3256 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n * ```\n */\n\nimport {\n sha3_224,\n sha3_256,\n sha3_384,\n sha3_512,\n} from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport const sha3224 = (data: string | Uint8Array) => bytesToHex(sha3_224(data));\nexport const sha3256 = (data: string | Uint8Array) => bytesToHex(sha3_256(data));\nexport const sha3384 = (data: string | Uint8Array) => bytesToHex(sha3_384(data));\nexport const sha3512 = (data: string | Uint8Array) => bytesToHex(sha3_512(data));\n"],"names":["bytesToHex","sha3_224","sha3_256","sha3_384","sha3_512"],"mappings":";;;;;AAAA;;;;;;;;;;;;AAYG;AAUI,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAKA,gBAAU,CAACC,aAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAKD,gBAAU,CAACE,aAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAKF,gBAAU,CAACG,aAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAKH,gBAAU,CAACI,aAAQ,CAAC,IAAI,CAAC;;;;;;;"}
|
package/dist/hash.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.mjs","sources":["../src/hash.ts"],"sourcesContent":["/**\n * This file provides a set of functions for creating SHA-3 hash digests\n * using different bit lengths (224, 256, 384, 512).\n * These functions use the [@noble/hashes](https://github.com/paulmillr/noble-hashes) library to generate the hashes.\n * Can be used in the browser, mainly for Nuxt/Vue and other frameworks compiled and executed in the browser.\n *\n * @example\n * ```typescript\n * import { sha3256 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n * ```\n */\n\nimport {\n sha3_224,\n sha3_256,\n sha3_384,\n sha3_512,\n} from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport const sha3224 = (data: string | Uint8Array) => bytesToHex(sha3_224(data));\nexport const sha3256 = (data: string | Uint8Array) => bytesToHex(sha3_256(data));\nexport const sha3384 = (data: string | Uint8Array) => bytesToHex(sha3_384(data));\nexport const sha3512 = (data: string | Uint8Array) => bytesToHex(sha3_512(data));\n"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;AAYG;
|
|
1
|
+
{"version":3,"file":"hash.mjs","sources":["../src/hash.ts"],"sourcesContent":["/**\n * This file provides a set of functions for creating SHA-3 hash digests\n * using different bit lengths (224, 256, 384, 512).\n * These functions use the [@noble/hashes](https://github.com/paulmillr/noble-hashes) library to generate the hashes.\n * Can be used in the browser, mainly for Nuxt/Vue and other frameworks compiled and executed in the browser.\n *\n * @example\n * ```typescript\n * import { sha3256 } from '@kikiutils/shared/hash';\n *\n * console.log(sha3256('test')); // 36f028580bb02cc8272a9a020f4200e346e276ae664e45ee80745574e2f5ab80\n * ```\n */\n\nimport {\n sha3_224,\n sha3_256,\n sha3_384,\n sha3_512,\n} from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\n\nexport const sha3224 = (data: string | Uint8Array) => bytesToHex(sha3_224(data));\nexport const sha3256 = (data: string | Uint8Array) => bytesToHex(sha3_256(data));\nexport const sha3384 = (data: string | Uint8Array) => bytesToHex(sha3_384(data));\nexport const sha3512 = (data: string | Uint8Array) => bytesToHex(sha3_512(data));\n"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;AAYG;AAUI,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAK,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAK,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAK,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;AACxE,MAAM,OAAO,GAAG,CAAC,IAAyB,KAAK,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;;;;"}
|
package/dist/math.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.cjs","sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction.\n * @param {CalculableValue} denominator - The denominator of the fraction.\n * @param {ToPercentageStringOptions} [options] - Optional output settings.\n *\n * @returns {string} Formatted percentage string.\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n const result = calculationResult.isNaN()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"names":["Decimal"],"mappings":";;;;AAuBA;;;;;;;;;;;;;;;;;;;;;AAqBG;SACa,kBAAkB,CAC9B,SAA0B,EAC1B,WAA4B,EAC5B,OAAmC,EAAA;IAEnC,MAAM,gBAAgB,GAAG,IAAIA,kBAAO,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC1D,MAAM,kBAAkB,GAAG,IAAIA,kBAAO,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;IAC9D,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,GAAG,CAAC,kBAAkB,CAAC;AAClE,IAAA,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK;AAClC,UAAE;AACF,UAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;AAEvE,IAAA,OAAO,OAAO,EAAE,UAAU,IAAI,IAAI,GAAG,CAAA,EAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"math.cjs","sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction.\n * @param {CalculableValue} denominator - The denominator of the fraction.\n * @param {ToPercentageStringOptions} [options] - Optional output settings.\n *\n * @returns {string} Formatted percentage string.\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n const result = calculationResult.isNaN()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"names":["Decimal"],"mappings":";;;;AAuBA;;;;;;;;;;;;;;;;;;;;;AAqBG;SACa,kBAAkB,CAC9B,SAA0B,EAC1B,WAA4B,EAC5B,OAAmC,EAAA;IAEnC,MAAM,gBAAgB,GAAG,IAAIA,kBAAO,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC1D,MAAM,kBAAkB,GAAG,IAAIA,kBAAO,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;IAC9D,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,GAAG,CAAC,kBAAkB,CAAC;AAClE,IAAA,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK;AAClC,UAAE;AACF,UAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;AAEvE,IAAA,OAAO,OAAO,EAAE,UAAU,IAAI,IAAI,GAAG,CAAA,EAAG,MAAM,CAAA,CAAA,CAAG,GAAG,MAAM;AAC9D;;;;"}
|
package/dist/math.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.mjs","sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction.\n * @param {CalculableValue} denominator - The denominator of the fraction.\n * @param {ToPercentageStringOptions} [options] - Optional output settings.\n *\n * @returns {string} Formatted percentage string.\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n const result = calculationResult.isNaN()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"names":[],"mappings":";;AAuBA;;;;;;;;;;;;;;;;;;;;;AAqBG;SACa,kBAAkB,CAC9B,SAA0B,EAC1B,WAA4B,EAC5B,OAAmC,EAAA;IAEnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC1D,MAAM,kBAAkB,GAAG,IAAI,OAAO,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;IAC9D,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,GAAG,CAAC,kBAAkB,CAAC;AAClE,IAAA,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK;AAClC,UAAE;AACF,UAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;AAEvE,IAAA,OAAO,OAAO,EAAE,UAAU,IAAI,IAAI,GAAG,CAAA,EAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"math.mjs","sources":["../src/math.ts"],"sourcesContent":["import { Decimal } from 'decimal.js';\n\ntype CalculableValue = Decimal.Value | { toString: () => string };\n\n/**\n * Options for configuring the output of `toPercentageString`.\n */\nexport interface ToPercentageStringOptions {\n /**\n * Number of decimal places to include in the result.\n *\n * @default 2\n */\n decimalPlaces?: number;\n\n /**\n * Whether to include the '%' symbol in the result.\n *\n * @default true\n */\n withSymbol?: boolean;\n}\n\n/**\n * Converts a fraction (numerator / denominator) into a percentage string.\n *\n * - Uses `decimal.js` for precise decimal calculations.\n * - Supports custom decimal places and optional percentage symbol.\n * - Returns `'0.00%'` if result is `NaN` or division is invalid.\n *\n * @param {CalculableValue} molecular - The numerator of the fraction.\n * @param {CalculableValue} denominator - The denominator of the fraction.\n * @param {ToPercentageStringOptions} [options] - Optional output settings.\n *\n * @returns {string} Formatted percentage string.\n *\n * @example\n * ```typescript\n * import { toPercentageString } from '@kikiutils/shared/math';\n *\n * console.log(toPercentageString(50, 200)); // 25.00%\n * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00\n * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0%\n * ```\n */\nexport function toPercentageString(\n molecular: CalculableValue,\n denominator: CalculableValue,\n options?: ToPercentageStringOptions,\n) {\n const molecularDecimal = new Decimal(molecular.toString());\n const denominatorDecimal = new Decimal(denominator.toString());\n const calculationResult = molecularDecimal.div(denominatorDecimal);\n const result = calculationResult.isNaN()\n ? '0.00'\n : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2);\n\n return options?.withSymbol ?? true ? `${result}%` : result;\n}\n"],"names":[],"mappings":";;AAuBA;;;;;;;;;;;;;;;;;;;;;AAqBG;SACa,kBAAkB,CAC9B,SAA0B,EAC1B,WAA4B,EAC5B,OAAmC,EAAA;IAEnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC1D,MAAM,kBAAkB,GAAG,IAAI,OAAO,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;IAC9D,MAAM,iBAAiB,GAAG,gBAAgB,CAAC,GAAG,CAAC,kBAAkB,CAAC;AAClE,IAAA,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK;AAClC,UAAE;AACF,UAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;AAEvE,IAAA,OAAO,OAAO,EAAE,UAAU,IAAI,IAAI,GAAG,CAAA,EAAG,MAAM,CAAA,CAAA,CAAG,GAAG,MAAM;AAC9D;;;;"}
|
package/dist/number.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.cjs","sources":["../src/number.ts"],"sourcesContent":["import { millify } from 'millify';\n\n/**\n * Converts a large number into a compact, human-readable string using `millify`.\n *\n * Applies lowercase units (e.g. 'k', 'm') and default precision of 2, unless overridden.\n *\n * @param {number} value - The number to format.\n * @param {Parameters<typeof millify>[1]} [options] - Optional configuration passed to `millify`.\n *\n * @returns {string} The compact number string.\n *\n * @example\n * ```typescript\n * import { toCompactNumberString } from '@kikiutils/shared/number';\n *\n * console.log(toCompactNumberString(1234567)); // 1.23m\n * console.log(toCompactNumberString(1234567, { precision: 3 })); // 1.235m\n * ```\n */\nexport function toCompactNumberString(value: number, options?: Parameters<typeof millify>[1]) {\n return millify(\n value,\n {\n lowercase: true,\n precision: 2,\n ...options,\n },\n );\n}\n"],"names":["millify"],"mappings":";;;;AAEA;;;;;;;;;;;;;;;;;AAiBG;
|
|
1
|
+
{"version":3,"file":"number.cjs","sources":["../src/number.ts"],"sourcesContent":["import { millify } from 'millify';\n\n/**\n * Converts a large number into a compact, human-readable string using `millify`.\n *\n * Applies lowercase units (e.g. 'k', 'm') and default precision of 2, unless overridden.\n *\n * @param {number} value - The number to format.\n * @param {Parameters<typeof millify>[1]} [options] - Optional configuration passed to `millify`.\n *\n * @returns {string} The compact number string.\n *\n * @example\n * ```typescript\n * import { toCompactNumberString } from '@kikiutils/shared/number';\n *\n * console.log(toCompactNumberString(1234567)); // 1.23m\n * console.log(toCompactNumberString(1234567, { precision: 3 })); // 1.235m\n * ```\n */\nexport function toCompactNumberString(value: number, options?: Parameters<typeof millify>[1]) {\n return millify(\n value,\n {\n lowercase: true,\n precision: 2,\n ...options,\n },\n );\n}\n"],"names":["millify"],"mappings":";;;;AAEA;;;;;;;;;;;;;;;;;AAiBG;AACG,SAAU,qBAAqB,CAAC,KAAa,EAAE,OAAuC,EAAA;IACxF,OAAOA,eAAO,CACV,KAAK,EACL;AACI,QAAA,SAAS,EAAE,IAAI;AACf,QAAA,SAAS,EAAE,CAAC;AACZ,QAAA,GAAG,OAAO;AACb,KAAA,CACJ;AACL;;;;"}
|
package/dist/number.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.mjs","sources":["../src/number.ts"],"sourcesContent":["import { millify } from 'millify';\n\n/**\n * Converts a large number into a compact, human-readable string using `millify`.\n *\n * Applies lowercase units (e.g. 'k', 'm') and default precision of 2, unless overridden.\n *\n * @param {number} value - The number to format.\n * @param {Parameters<typeof millify>[1]} [options] - Optional configuration passed to `millify`.\n *\n * @returns {string} The compact number string.\n *\n * @example\n * ```typescript\n * import { toCompactNumberString } from '@kikiutils/shared/number';\n *\n * console.log(toCompactNumberString(1234567)); // 1.23m\n * console.log(toCompactNumberString(1234567, { precision: 3 })); // 1.235m\n * ```\n */\nexport function toCompactNumberString(value: number, options?: Parameters<typeof millify>[1]) {\n return millify(\n value,\n {\n lowercase: true,\n precision: 2,\n ...options,\n },\n );\n}\n"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;;AAiBG;
|
|
1
|
+
{"version":3,"file":"number.mjs","sources":["../src/number.ts"],"sourcesContent":["import { millify } from 'millify';\n\n/**\n * Converts a large number into a compact, human-readable string using `millify`.\n *\n * Applies lowercase units (e.g. 'k', 'm') and default precision of 2, unless overridden.\n *\n * @param {number} value - The number to format.\n * @param {Parameters<typeof millify>[1]} [options] - Optional configuration passed to `millify`.\n *\n * @returns {string} The compact number string.\n *\n * @example\n * ```typescript\n * import { toCompactNumberString } from '@kikiutils/shared/number';\n *\n * console.log(toCompactNumberString(1234567)); // 1.23m\n * console.log(toCompactNumberString(1234567, { precision: 3 })); // 1.235m\n * ```\n */\nexport function toCompactNumberString(value: number, options?: Parameters<typeof millify>[1]) {\n return millify(\n value,\n {\n lowercase: true,\n precision: 2,\n ...options,\n },\n );\n}\n"],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;;;;AAiBG;AACG,SAAU,qBAAqB,CAAC,KAAa,EAAE,OAAuC,EAAA;IACxF,OAAO,OAAO,CACV,KAAK,EACL;AACI,QAAA,SAAS,EAAE,IAAI;AACf,QAAA,SAAS,EAAE,CAAC;AACZ,QAAA,GAAG,OAAO;AACb,KAAA,CACJ;AACL;;;;"}
|
package/dist/object.cjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Serializes a nested object into a deterministic, flat string format.
|
|
5
|
+
*
|
|
6
|
+
* This function recursively traverses the input object (including nested objects and arrays),
|
|
7
|
+
* flattens it into key paths using dot notation (e.g. "a.b.0.c"), sorts all keys,
|
|
8
|
+
* and joins each key-value pair into a string with customizable separators.
|
|
9
|
+
*
|
|
10
|
+
* It is designed for use cases such as signature generation, cache key construction,
|
|
11
|
+
* or any context requiring consistent and predictable object serialization.
|
|
12
|
+
*
|
|
13
|
+
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.
|
|
14
|
+
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=').
|
|
15
|
+
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').
|
|
16
|
+
* @returns {string} A deterministic string representation of the input object.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* import { stringifyObjectDeterministically } from '@kikiutils/shared/object';
|
|
21
|
+
*
|
|
22
|
+
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
23
|
+
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
function stringifyObjectDeterministically(input, kvSeparator = '=', pairSeparator = '&') {
|
|
27
|
+
const entries = [];
|
|
28
|
+
function walk(object, path = []) {
|
|
29
|
+
if (Array.isArray(object)) {
|
|
30
|
+
object.forEach((value, index) => {
|
|
31
|
+
walk(value, [
|
|
32
|
+
...path,
|
|
33
|
+
index.toString(),
|
|
34
|
+
]);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
else if (object !== null
|
|
38
|
+
&& typeof object === 'object'
|
|
39
|
+
&& Object.prototype.toString.call(object) === '[object Object]') {
|
|
40
|
+
Object.keys(object).sort().forEach((key) => {
|
|
41
|
+
walk(object[key], [
|
|
42
|
+
...path,
|
|
43
|
+
key,
|
|
44
|
+
]);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
else
|
|
48
|
+
entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);
|
|
49
|
+
}
|
|
50
|
+
walk(input);
|
|
51
|
+
return entries.sort().join(pairSeparator);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
exports.stringifyObjectDeterministically = stringifyObjectDeterministically;
|
|
55
|
+
//# sourceMappingURL=object.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object.cjs","sources":["../src/object.ts"],"sourcesContent":["/**\n * Serializes a nested object into a deterministic, flat string format.\n *\n * This function recursively traverses the input object (including nested objects and arrays),\n * flattens it into key paths using dot notation (e.g. \"a.b.0.c\"), sorts all keys,\n * and joins each key-value pair into a string with customizable separators.\n *\n * It is designed for use cases such as signature generation, cache key construction,\n * or any context requiring consistent and predictable object serialization.\n *\n * @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.\n * @param {string} kvSeparator - The string used to separate each key from its value (default: '=').\n * @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').\n * @returns {string} A deterministic string representation of the input object.\n *\n * @example\n * ```typescript\n * import { stringifyObjectDeterministically } from '@kikiutils/shared/object';\n *\n * console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2\n * console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar\n * ```\n */\nexport function stringifyObjectDeterministically(\n input: Record<string, any>,\n kvSeparator: string = '=',\n pairSeparator: string = '&',\n) {\n const entries: string[] = [];\n\n function walk(object: any, path: string[] = []) {\n if (Array.isArray(object)) {\n object.forEach((value, index) => {\n walk(\n value,\n [\n ...path,\n index.toString(),\n ],\n );\n });\n } else if (\n object !== null\n && typeof object === 'object'\n && Object.prototype.toString.call(object) === '[object Object]'\n ) {\n Object.keys(object).sort().forEach((key) => {\n walk(\n object[key],\n [\n ...path,\n key,\n ],\n );\n });\n } else entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);\n }\n\n walk(input);\n return entries.sort().join(pairSeparator);\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AACG,SAAU,gCAAgC,CAC5C,KAA0B,EAC1B,WAAA,GAAsB,GAAG,EACzB,aAAA,GAAwB,GAAG,EAAA;IAE3B,MAAM,OAAO,GAAa,EAAE;AAE5B,IAAA,SAAS,IAAI,CAAC,MAAW,EAAE,OAAiB,EAAE,EAAA;AAC1C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YACvB,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAI;gBAC5B,IAAI,CACA,KAAK,EACL;AACI,oBAAA,GAAG,IAAI;oBACP,KAAK,CAAC,QAAQ,EAAE;AACnB,iBAAA,CACJ;AACL,aAAC,CAAC;;aACC,IACH,MAAM,KAAK;eACR,OAAO,MAAM,KAAK;AAClB,eAAA,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,iBAAiB,EACjE;AACE,YAAA,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,KAAI;AACvC,gBAAA,IAAI,CACA,MAAM,CAAC,GAAG,CAAC,EACX;AACI,oBAAA,GAAG,IAAI;oBACP,GAAG;AACN,iBAAA,CACJ;AACL,aAAC,CAAC;;;AACC,YAAA,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA,EAAG,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA,CAAE,CAAC;;IAG3E,IAAI,CAAC,KAAK,CAAC;IACX,OAAO,OAAO,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC;AAC7C;;;;"}
|
package/dist/object.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes a nested object into a deterministic, flat string format.
|
|
3
|
+
*
|
|
4
|
+
* This function recursively traverses the input object (including nested objects and arrays),
|
|
5
|
+
* flattens it into key paths using dot notation (e.g. "a.b.0.c"), sorts all keys,
|
|
6
|
+
* and joins each key-value pair into a string with customizable separators.
|
|
7
|
+
*
|
|
8
|
+
* It is designed for use cases such as signature generation, cache key construction,
|
|
9
|
+
* or any context requiring consistent and predictable object serialization.
|
|
10
|
+
*
|
|
11
|
+
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.
|
|
12
|
+
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=').
|
|
13
|
+
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').
|
|
14
|
+
* @returns {string} A deterministic string representation of the input object.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { stringifyObjectDeterministically } from '@kikiutils/shared/object';
|
|
19
|
+
*
|
|
20
|
+
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
21
|
+
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function stringifyObjectDeterministically(input: Record<string, any>, kvSeparator?: string, pairSeparator?: string): string;
|
|
25
|
+
//# sourceMappingURL=object.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gCAAgC,CAC5C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1B,WAAW,GAAE,MAAY,EACzB,aAAa,GAAE,MAAY,UAkC9B"}
|
package/dist/object.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes a nested object into a deterministic, flat string format.
|
|
3
|
+
*
|
|
4
|
+
* This function recursively traverses the input object (including nested objects and arrays),
|
|
5
|
+
* flattens it into key paths using dot notation (e.g. "a.b.0.c"), sorts all keys,
|
|
6
|
+
* and joins each key-value pair into a string with customizable separators.
|
|
7
|
+
*
|
|
8
|
+
* It is designed for use cases such as signature generation, cache key construction,
|
|
9
|
+
* or any context requiring consistent and predictable object serialization.
|
|
10
|
+
*
|
|
11
|
+
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.
|
|
12
|
+
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=').
|
|
13
|
+
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').
|
|
14
|
+
* @returns {string} A deterministic string representation of the input object.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { stringifyObjectDeterministically } from '@kikiutils/shared/object';
|
|
19
|
+
*
|
|
20
|
+
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
21
|
+
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
function stringifyObjectDeterministically(input, kvSeparator = '=', pairSeparator = '&') {
|
|
25
|
+
const entries = [];
|
|
26
|
+
function walk(object, path = []) {
|
|
27
|
+
if (Array.isArray(object)) {
|
|
28
|
+
object.forEach((value, index) => {
|
|
29
|
+
walk(value, [
|
|
30
|
+
...path,
|
|
31
|
+
index.toString(),
|
|
32
|
+
]);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
else if (object !== null
|
|
36
|
+
&& typeof object === 'object'
|
|
37
|
+
&& Object.prototype.toString.call(object) === '[object Object]') {
|
|
38
|
+
Object.keys(object).sort().forEach((key) => {
|
|
39
|
+
walk(object[key], [
|
|
40
|
+
...path,
|
|
41
|
+
key,
|
|
42
|
+
]);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
else
|
|
46
|
+
entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);
|
|
47
|
+
}
|
|
48
|
+
walk(input);
|
|
49
|
+
return entries.sort().join(pairSeparator);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export { stringifyObjectDeterministically };
|
|
53
|
+
//# sourceMappingURL=object.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object.mjs","sources":["../src/object.ts"],"sourcesContent":["/**\n * Serializes a nested object into a deterministic, flat string format.\n *\n * This function recursively traverses the input object (including nested objects and arrays),\n * flattens it into key paths using dot notation (e.g. \"a.b.0.c\"), sorts all keys,\n * and joins each key-value pair into a string with customizable separators.\n *\n * It is designed for use cases such as signature generation, cache key construction,\n * or any context requiring consistent and predictable object serialization.\n *\n * @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.\n * @param {string} kvSeparator - The string used to separate each key from its value (default: '=').\n * @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').\n * @returns {string} A deterministic string representation of the input object.\n *\n * @example\n * ```typescript\n * import { stringifyObjectDeterministically } from '@kikiutils/shared/object';\n *\n * console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2\n * console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar\n * ```\n */\nexport function stringifyObjectDeterministically(\n input: Record<string, any>,\n kvSeparator: string = '=',\n pairSeparator: string = '&',\n) {\n const entries: string[] = [];\n\n function walk(object: any, path: string[] = []) {\n if (Array.isArray(object)) {\n object.forEach((value, index) => {\n walk(\n value,\n [\n ...path,\n index.toString(),\n ],\n );\n });\n } else if (\n object !== null\n && typeof object === 'object'\n && Object.prototype.toString.call(object) === '[object Object]'\n ) {\n Object.keys(object).sort().forEach((key) => {\n walk(\n object[key],\n [\n ...path,\n key,\n ],\n );\n });\n } else entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);\n }\n\n walk(input);\n return entries.sort().join(pairSeparator);\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AACG,SAAU,gCAAgC,CAC5C,KAA0B,EAC1B,WAAA,GAAsB,GAAG,EACzB,aAAA,GAAwB,GAAG,EAAA;IAE3B,MAAM,OAAO,GAAa,EAAE;AAE5B,IAAA,SAAS,IAAI,CAAC,MAAW,EAAE,OAAiB,EAAE,EAAA;AAC1C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YACvB,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAI;gBAC5B,IAAI,CACA,KAAK,EACL;AACI,oBAAA,GAAG,IAAI;oBACP,KAAK,CAAC,QAAQ,EAAE;AACnB,iBAAA,CACJ;AACL,aAAC,CAAC;;aACC,IACH,MAAM,KAAK;eACR,OAAO,MAAM,KAAK;AAClB,eAAA,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,iBAAiB,EACjE;AACE,YAAA,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,KAAI;AACvC,gBAAA,IAAI,CACA,MAAM,CAAC,GAAG,CAAC,EACX;AACI,oBAAA,GAAG,IAAI;oBACP,GAAG;AACN,iBAAA,CACJ;AACL,aAAC,CAAC;;;AACC,YAAA,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA,EAAG,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA,CAAE,CAAC;;IAG3E,IAAI,CAAC,KAAK,CAAC;IACX,OAAO,OAAO,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC;AAC7C;;;;"}
|
package/dist/pino.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pino.cjs","sources":["../src/pino.ts"],"sourcesContent":["import { pino } from 'pino';\nimport { PinoPretty } from 'pino-pretty';\n\n/**\n * Configure pinoPretty to enhance the log output.\n */\nconst stream = PinoPretty({\n colorize: true, // Enable colored output for better readability\n ignore: 'hostname,pid', // Exclude 'hostname' and 'pid' fields from the logs\n translateTime: 'SYS:yyyy-mm-dd HH:MM:ss.l', // Format the timestamp in 'yyyy-mm-dd HH:MM:ss.l' format\n});\n\n/**\n * A pino logger instance with the configured stream.\n *\n * The logger's level is determined based on the `PINO_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `PINO_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `error`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://getpino.io/#/docs/api?id=level-string).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/pino';\n *\n * logger.info('test'); // [2024-07-11 12:12:30.085] INFO: test\n *\n * // Manually change the level\n * logger.level = 'info';\n * ```\n */\nexport const pinoLogger = pino({}, stream);\nexport const logger = pinoLogger;\n// eslint-disable-next-line style/max-len\npinoLogger.level = process.env.PINO_LOGGER_LEVEL || (process.env.NODE_ENV === 'production' ? 'error' : pinoLogger.level);\n"],"names":["PinoPretty","pino"],"mappings":";;;;;AAGA;;AAEG;AACH,MAAM,MAAM,GAAGA,qBAAU,CAAC;IACtB,QAAQ,EAAE,IAAI;IACd,MAAM,EAAE,cAAc;IACtB,aAAa,EAAE,2BAA2B;AAC7C,CAAA,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;AAoBG;
|
|
1
|
+
{"version":3,"file":"pino.cjs","sources":["../src/pino.ts"],"sourcesContent":["import { pino } from 'pino';\nimport { PinoPretty } from 'pino-pretty';\n\n/**\n * Configure pinoPretty to enhance the log output.\n */\nconst stream = PinoPretty({\n colorize: true, // Enable colored output for better readability\n ignore: 'hostname,pid', // Exclude 'hostname' and 'pid' fields from the logs\n translateTime: 'SYS:yyyy-mm-dd HH:MM:ss.l', // Format the timestamp in 'yyyy-mm-dd HH:MM:ss.l' format\n});\n\n/**\n * A pino logger instance with the configured stream.\n *\n * The logger's level is determined based on the `PINO_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `PINO_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `error`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://getpino.io/#/docs/api?id=level-string).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/pino';\n *\n * logger.info('test'); // [2024-07-11 12:12:30.085] INFO: test\n *\n * // Manually change the level\n * logger.level = 'info';\n * ```\n */\nexport const pinoLogger = pino({}, stream);\nexport const logger = pinoLogger;\n// eslint-disable-next-line style/max-len\npinoLogger.level = process.env.PINO_LOGGER_LEVEL || (process.env.NODE_ENV === 'production' ? 'error' : pinoLogger.level);\n"],"names":["PinoPretty","pino"],"mappings":";;;;;AAGA;;AAEG;AACH,MAAM,MAAM,GAAGA,qBAAU,CAAC;IACtB,QAAQ,EAAE,IAAI;IACd,MAAM,EAAE,cAAc;IACtB,aAAa,EAAE,2BAA2B;AAC7C,CAAA,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,UAAU,GAAGC,SAAI,CAAC,EAAE,EAAE,MAAM;AAClC,MAAM,MAAM,GAAG;AACtB;AACA,UAAU,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,KAAK,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,GAAG,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC;;;;;"}
|
package/dist/pino.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pino.mjs","sources":["../src/pino.ts"],"sourcesContent":["import { pino } from 'pino';\nimport { PinoPretty } from 'pino-pretty';\n\n/**\n * Configure pinoPretty to enhance the log output.\n */\nconst stream = PinoPretty({\n colorize: true, // Enable colored output for better readability\n ignore: 'hostname,pid', // Exclude 'hostname' and 'pid' fields from the logs\n translateTime: 'SYS:yyyy-mm-dd HH:MM:ss.l', // Format the timestamp in 'yyyy-mm-dd HH:MM:ss.l' format\n});\n\n/**\n * A pino logger instance with the configured stream.\n *\n * The logger's level is determined based on the `PINO_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `PINO_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `error`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://getpino.io/#/docs/api?id=level-string).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/pino';\n *\n * logger.info('test'); // [2024-07-11 12:12:30.085] INFO: test\n *\n * // Manually change the level\n * logger.level = 'info';\n * ```\n */\nexport const pinoLogger = pino({}, stream);\nexport const logger = pinoLogger;\n// eslint-disable-next-line style/max-len\npinoLogger.level = process.env.PINO_LOGGER_LEVEL || (process.env.NODE_ENV === 'production' ? 'error' : pinoLogger.level);\n"],"names":[],"mappings":";;;AAGA;;AAEG;AACH,MAAM,MAAM,GAAG,UAAU,CAAC;IACtB,QAAQ,EAAE,IAAI;IACd,MAAM,EAAE,cAAc;IACtB,aAAa,EAAE,2BAA2B;AAC7C,CAAA,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;AAoBG;
|
|
1
|
+
{"version":3,"file":"pino.mjs","sources":["../src/pino.ts"],"sourcesContent":["import { pino } from 'pino';\nimport { PinoPretty } from 'pino-pretty';\n\n/**\n * Configure pinoPretty to enhance the log output.\n */\nconst stream = PinoPretty({\n colorize: true, // Enable colored output for better readability\n ignore: 'hostname,pid', // Exclude 'hostname' and 'pid' fields from the logs\n translateTime: 'SYS:yyyy-mm-dd HH:MM:ss.l', // Format the timestamp in 'yyyy-mm-dd HH:MM:ss.l' format\n});\n\n/**\n * A pino logger instance with the configured stream.\n *\n * The logger's level is determined based on the `PINO_LOGGER_LEVEL` and `NODE_ENV` environment variables.\n * If `PINO_LOGGER_LEVEL` is set, it will be used; otherwise, if `NODE_ENV` is `production`,\n * the level will be set to `error`.\n *\n * To manually change the level, assign the desired level to `logger.level`.\n *\n * See available levels [here](https://getpino.io/#/docs/api?id=level-string).\n *\n * @example\n * ```typescript\n * import { logger } from '@kikiutils/shared/pino';\n *\n * logger.info('test'); // [2024-07-11 12:12:30.085] INFO: test\n *\n * // Manually change the level\n * logger.level = 'info';\n * ```\n */\nexport const pinoLogger = pino({}, stream);\nexport const logger = pinoLogger;\n// eslint-disable-next-line style/max-len\npinoLogger.level = process.env.PINO_LOGGER_LEVEL || (process.env.NODE_ENV === 'production' ? 'error' : pinoLogger.level);\n"],"names":[],"mappings":";;;AAGA;;AAEG;AACH,MAAM,MAAM,GAAG,UAAU,CAAC;IACtB,QAAQ,EAAE,IAAI;IACd,MAAM,EAAE,cAAc;IACtB,aAAa,EAAE,2BAA2B;AAC7C,CAAA,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;AAoBG;AACI,MAAM,UAAU,GAAG,IAAI,CAAC,EAAE,EAAE,MAAM;AAClC,MAAM,MAAM,GAAG;AACtB;AACA,UAAU,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,KAAK,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,GAAG,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","sources":["../../../../src/storage/enhanced/local/core.ts"],"sourcesContent":["import {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Json = '0',\n String = '1',\n}\n\nconst customValueHeader = '';\nconst customValueHeaderLength = customValueHeader.length + 1;\nconst toCustomValue = (type: StorageValueEncodingType, payload: string) => `${customValueHeader}${type}${payload}`;\n\n/**\n * An enhanced localStorage wrapper that supports storing\n * complex data types (e.g. Dates, Maps, Sets) using SuperJSON encoding.\n *\n * This utility preserves type structure when saving and retrieving values.\n *\n * @example\n * ```typescript\n * import { enhancedLocalStorage } from '@kikiutils/shared/storage/enhanced/local';\n *\n * enhancedLocalStorage.setItem('user', { name: 'user', createdAt: new Date() });\n * const user = enhancedLocalStorage.getItem<{ name: string, createdAt: Date }>('user');\n * ```\n */\nexport const enhancedLocalStorage = Object.freeze({\n /**\n * Removes all items from localStorage.\n */\n clear: () => window.localStorage.clear(),\n /**\n * Retrieves a value by key and decodes it using SuperJSON or raw string.\n *\n * @template T - The expected type of the value.\n *\n * @param {string} key - The key of the value to retrieve.\n *\n * @returns {null | T} The decoded value or null if not found.\n */\n getItem<T = unknown>(key: string) {\n const rawValue = window.localStorage.getItem(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Checks whether a key exists in localStorage.\n *\n * @param {string} key - The key to check.\n *\n * @returns {boolean} True if the key exists, false otherwise.\n */\n hasItem: (key: string) => window.localStorage.getItem(key) !== null,\n /**\n * Returns the number of items stored in localStorage.\n *\n * @returns {number} The number of items stored in localStorage.\n */\n get length() {\n return window.localStorage.length;\n },\n /**\n * Removes a specific key from localStorage.\n *\n * @param {string} key - The key to remove.\n */\n removeItem: (key: string) => window.localStorage.removeItem(key),\n /**\n * Stores a value in localStorage with automatic serialization.\n *\n * @param {string} key - The key to store the value under.\n * @param {any} value - The value to store.\n */\n setItem: (key: string, value: any) => window.localStorage.setItem(key, encodeToStorageValue(value)),\n});\n\nfunction decodeStorageValue(data: string) {\n if (!isCustomFormat(data)) return data;\n const payload = data.substring(customValueHeaderLength);\n const type = data.charAt(customValueHeader.length);\n switch (type) {\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload));\n } catch {\n throw new Error('[EnhancedLocalStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload;\n default:\n throw new Error(`[EnhancedLocalStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, value);\n return toCustomValue(StorageValueEncodingType.Json, JSON.stringify(serialize(value)));\n}\n\nfunction isCustomFormat(data: string) {\n return (\n data.length >= customValueHeaderLength\n && data[0] === customValueHeader[0]\n && data[1] === customValueHeader[1]\n );\n}\n"],"names":["deserialize","serialize"],"mappings":";;;;AAKA,IAAK,wBAGJ;AAHD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,GAAU;AACV,IAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,GAAY;AAChB,CAAC,EAHI,wBAAwB,KAAxB,wBAAwB,
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../../../../src/storage/enhanced/local/core.ts"],"sourcesContent":["import {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Json = '0',\n String = '1',\n}\n\nconst customValueHeader = '';\nconst customValueHeaderLength = customValueHeader.length + 1;\nconst toCustomValue = (type: StorageValueEncodingType, payload: string) => `${customValueHeader}${type}${payload}`;\n\n/**\n * An enhanced localStorage wrapper that supports storing\n * complex data types (e.g. Dates, Maps, Sets) using SuperJSON encoding.\n *\n * This utility preserves type structure when saving and retrieving values.\n *\n * @example\n * ```typescript\n * import { enhancedLocalStorage } from '@kikiutils/shared/storage/enhanced/local';\n *\n * enhancedLocalStorage.setItem('user', { name: 'user', createdAt: new Date() });\n * const user = enhancedLocalStorage.getItem<{ name: string, createdAt: Date }>('user');\n * ```\n */\nexport const enhancedLocalStorage = Object.freeze({\n /**\n * Removes all items from localStorage.\n */\n clear: () => window.localStorage.clear(),\n /**\n * Retrieves a value by key and decodes it using SuperJSON or raw string.\n *\n * @template T - The expected type of the value.\n *\n * @param {string} key - The key of the value to retrieve.\n *\n * @returns {null | T} The decoded value or null if not found.\n */\n getItem<T = unknown>(key: string) {\n const rawValue = window.localStorage.getItem(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Checks whether a key exists in localStorage.\n *\n * @param {string} key - The key to check.\n *\n * @returns {boolean} True if the key exists, false otherwise.\n */\n hasItem: (key: string) => window.localStorage.getItem(key) !== null,\n /**\n * Returns the number of items stored in localStorage.\n *\n * @returns {number} The number of items stored in localStorage.\n */\n get length() {\n return window.localStorage.length;\n },\n /**\n * Removes a specific key from localStorage.\n *\n * @param {string} key - The key to remove.\n */\n removeItem: (key: string) => window.localStorage.removeItem(key),\n /**\n * Stores a value in localStorage with automatic serialization.\n *\n * @param {string} key - The key to store the value under.\n * @param {any} value - The value to store.\n */\n setItem: (key: string, value: any) => window.localStorage.setItem(key, encodeToStorageValue(value)),\n});\n\nfunction decodeStorageValue(data: string) {\n if (!isCustomFormat(data)) return data;\n const payload = data.substring(customValueHeaderLength);\n const type = data.charAt(customValueHeader.length);\n switch (type) {\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload));\n } catch {\n throw new Error('[EnhancedLocalStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload;\n default:\n throw new Error(`[EnhancedLocalStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, value);\n return toCustomValue(StorageValueEncodingType.Json, JSON.stringify(serialize(value)));\n}\n\nfunction isCustomFormat(data: string) {\n return (\n data.length >= customValueHeaderLength\n && data[0] === customValueHeader[0]\n && data[1] === customValueHeader[1]\n );\n}\n"],"names":["deserialize","serialize"],"mappings":";;;;AAKA,IAAK,wBAGJ;AAHD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,GAAU;AACV,IAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,GAAY;AAChB,CAAC,EAHI,wBAAwB,KAAxB,wBAAwB,GAAA,EAAA,CAAA,CAAA;AAK7B,MAAM,iBAAiB,GAAG,IAAI;AAC9B,MAAM,uBAAuB,GAAG,iBAAiB,CAAC,MAAM,GAAG,CAAC;AAC5D,MAAM,aAAa,GAAG,CAAC,IAA8B,EAAE,OAAe,KAAK,CAAA,EAAG,iBAAiB,CAAA,EAAG,I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O,CAAC,CAAC;;AACzC,YAAA,MAAM;AACJ,gBAAA,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC;;AAE/E,QAAA,KAAK,wBAAwB,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD,QAAA;AACI,YAAA,MAAM,IAAI,KAAK,CAAC,iDAAiD,IAAI,CAAA,CAAA,CAAG,CAAC;;AAErF;AAEA,SAAS,oBAAoB,CAAC,KAAU,EAAA;IACpC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,KAAK,CAAC;AAC3F,IAAA,OAAO,aAAa,CAAC,wBAAwB,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAACC,mBAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACzF;AAEA,SAAS,cAAc,CAAC,IAAY,EAAA;AAChC,IAAA,QACI,IAAI,CAAC,MAAM,IAAI;AACZ,WAAA,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC;WAC/B,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAC;AAE3C;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.mjs","sources":["../../../../src/storage/enhanced/local/core.ts"],"sourcesContent":["import {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Json = '0',\n String = '1',\n}\n\nconst customValueHeader = '';\nconst customValueHeaderLength = customValueHeader.length + 1;\nconst toCustomValue = (type: StorageValueEncodingType, payload: string) => `${customValueHeader}${type}${payload}`;\n\n/**\n * An enhanced localStorage wrapper that supports storing\n * complex data types (e.g. Dates, Maps, Sets) using SuperJSON encoding.\n *\n * This utility preserves type structure when saving and retrieving values.\n *\n * @example\n * ```typescript\n * import { enhancedLocalStorage } from '@kikiutils/shared/storage/enhanced/local';\n *\n * enhancedLocalStorage.setItem('user', { name: 'user', createdAt: new Date() });\n * const user = enhancedLocalStorage.getItem<{ name: string, createdAt: Date }>('user');\n * ```\n */\nexport const enhancedLocalStorage = Object.freeze({\n /**\n * Removes all items from localStorage.\n */\n clear: () => window.localStorage.clear(),\n /**\n * Retrieves a value by key and decodes it using SuperJSON or raw string.\n *\n * @template T - The expected type of the value.\n *\n * @param {string} key - The key of the value to retrieve.\n *\n * @returns {null | T} The decoded value or null if not found.\n */\n getItem<T = unknown>(key: string) {\n const rawValue = window.localStorage.getItem(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Checks whether a key exists in localStorage.\n *\n * @param {string} key - The key to check.\n *\n * @returns {boolean} True if the key exists, false otherwise.\n */\n hasItem: (key: string) => window.localStorage.getItem(key) !== null,\n /**\n * Returns the number of items stored in localStorage.\n *\n * @returns {number} The number of items stored in localStorage.\n */\n get length() {\n return window.localStorage.length;\n },\n /**\n * Removes a specific key from localStorage.\n *\n * @param {string} key - The key to remove.\n */\n removeItem: (key: string) => window.localStorage.removeItem(key),\n /**\n * Stores a value in localStorage with automatic serialization.\n *\n * @param {string} key - The key to store the value under.\n * @param {any} value - The value to store.\n */\n setItem: (key: string, value: any) => window.localStorage.setItem(key, encodeToStorageValue(value)),\n});\n\nfunction decodeStorageValue(data: string) {\n if (!isCustomFormat(data)) return data;\n const payload = data.substring(customValueHeaderLength);\n const type = data.charAt(customValueHeader.length);\n switch (type) {\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload));\n } catch {\n throw new Error('[EnhancedLocalStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload;\n default:\n throw new Error(`[EnhancedLocalStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, value);\n return toCustomValue(StorageValueEncodingType.Json, JSON.stringify(serialize(value)));\n}\n\nfunction isCustomFormat(data: string) {\n return (\n data.length >= customValueHeaderLength\n && data[0] === customValueHeader[0]\n && data[1] === customValueHeader[1]\n );\n}\n"],"names":[],"mappings":";;AAKA,IAAK,wBAGJ;AAHD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,GAAU;AACV,IAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,GAAY;AAChB,CAAC,EAHI,wBAAwB,KAAxB,wBAAwB,
|
|
1
|
+
{"version":3,"file":"core.mjs","sources":["../../../../src/storage/enhanced/local/core.ts"],"sourcesContent":["import {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Json = '0',\n String = '1',\n}\n\nconst customValueHeader = '';\nconst customValueHeaderLength = customValueHeader.length + 1;\nconst toCustomValue = (type: StorageValueEncodingType, payload: string) => `${customValueHeader}${type}${payload}`;\n\n/**\n * An enhanced localStorage wrapper that supports storing\n * complex data types (e.g. Dates, Maps, Sets) using SuperJSON encoding.\n *\n * This utility preserves type structure when saving and retrieving values.\n *\n * @example\n * ```typescript\n * import { enhancedLocalStorage } from '@kikiutils/shared/storage/enhanced/local';\n *\n * enhancedLocalStorage.setItem('user', { name: 'user', createdAt: new Date() });\n * const user = enhancedLocalStorage.getItem<{ name: string, createdAt: Date }>('user');\n * ```\n */\nexport const enhancedLocalStorage = Object.freeze({\n /**\n * Removes all items from localStorage.\n */\n clear: () => window.localStorage.clear(),\n /**\n * Retrieves a value by key and decodes it using SuperJSON or raw string.\n *\n * @template T - The expected type of the value.\n *\n * @param {string} key - The key of the value to retrieve.\n *\n * @returns {null | T} The decoded value or null if not found.\n */\n getItem<T = unknown>(key: string) {\n const rawValue = window.localStorage.getItem(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Checks whether a key exists in localStorage.\n *\n * @param {string} key - The key to check.\n *\n * @returns {boolean} True if the key exists, false otherwise.\n */\n hasItem: (key: string) => window.localStorage.getItem(key) !== null,\n /**\n * Returns the number of items stored in localStorage.\n *\n * @returns {number} The number of items stored in localStorage.\n */\n get length() {\n return window.localStorage.length;\n },\n /**\n * Removes a specific key from localStorage.\n *\n * @param {string} key - The key to remove.\n */\n removeItem: (key: string) => window.localStorage.removeItem(key),\n /**\n * Stores a value in localStorage with automatic serialization.\n *\n * @param {string} key - The key to store the value under.\n * @param {any} value - The value to store.\n */\n setItem: (key: string, value: any) => window.localStorage.setItem(key, encodeToStorageValue(value)),\n});\n\nfunction decodeStorageValue(data: string) {\n if (!isCustomFormat(data)) return data;\n const payload = data.substring(customValueHeaderLength);\n const type = data.charAt(customValueHeader.length);\n switch (type) {\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload));\n } catch {\n throw new Error('[EnhancedLocalStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload;\n default:\n throw new Error(`[EnhancedLocalStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, value);\n return toCustomValue(StorageValueEncodingType.Json, JSON.stringify(serialize(value)));\n}\n\nfunction isCustomFormat(data: string) {\n return (\n data.length >= customValueHeaderLength\n && data[0] === customValueHeader[0]\n && data[1] === customValueHeader[1]\n );\n}\n"],"names":[],"mappings":";;AAKA,IAAK,wBAGJ;AAHD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,GAAU;AACV,IAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,GAAY;AAChB,CAAC,EAHI,wBAAwB,KAAxB,wBAAwB,GAAA,EAAA,CAAA,CAAA;AAK7B,MAAM,iBAAiB,GAAG,IAAI;AAC9B,MAAM,uBAAuB,GAAG,iBAAiB,CAAC,MAAM,GAAG,CAAC;AAC5D,MAAM,aAAa,GAAG,CAAC,IAA8B,EAAE,OAAe,KAAK,CAAA,EAAG,iBAAiB,CAAA,EAAG,IAAI,CAAA,EAAG,OAAO,EAAE;AAElH;;;;;;;;;;;;;AAaG;AACI,MAAM,oBAAoB,GAAG,MAAM,C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/E,QAAA,KAAK,wBAAwB,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD,QAAA;AACI,YAAA,MAAM,IAAI,KAAK,CAAC,iDAAiD,IAAI,CAAA,CAAA,CAAG,CAAC;;AAErF;AAEA,SAAS,oBAAoB,CAAC,KAAU,EAAA;IACpC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,KAAK,CAAC;AAC3F,IAAA,OAAO,aAAa,CAAC,wBAAwB,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACzF;AAEA,SAAS,cAAc,CAAC,IAAY,EAAA;AAChC,IAAA,QACI,IAAI,CAAC,MAAM,IAAI;AACZ,WAAA,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC;WAC/B,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAC;AAE3C;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","sources":["../../../../src/storage/enhanced/redis/core.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\n\nimport { Redis } from 'ioredis';\nimport {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Buffer = 0,\n Json = 1,\n String = 2,\n}\n\nconst customValueHeader = Buffer.of(\n 0xE2,\n 0x81,\n 0xA0,\n);\n\nconst customValueHeaderLength = customValueHeader.byteLength + 1;\n\n/**\n * Creates an enhanced Redis-based storage interface using SuperJSON encoding.\n *\n * This utility provides a typed, serializable key-value store backed by Redis,\n * supporting TTL operations and safe deserialization of complex types (e.g. Date, Map).\n *\n * @param {Redis | string} ioRedisInstanceOrUrl - Either an existing `ioredis` instance or a Redis connection string.\n *\n * @returns A frozen object that wraps Redis commands with typed get/set logic and encoding.\n *\n * @example\n * ```typescript\n * import { createEnhancedRedisStorage } from '@kikiutils/shared/storage/enhanced/redis';\n *\n * const redisStorage = createEnhancedRedisStorage('redis://localhost');\n * await redisStorage.setItem('user:1', { name: 'user' });\n * const user = await redisStorage.getItem<{ name: string }>('user:1');\n * ```\n */\nexport function createEnhancedRedisStorage(ioRedisInstanceOrUrl: Redis | string) {\n const instance = ioRedisInstanceOrUrl instanceof Redis ? ioRedisInstanceOrUrl : new Redis(ioRedisInstanceOrUrl);\n return Object.freeze({\n /**\n * Retrieves a value from Redis and decodes it.\n *\n * @template T - The expected return type.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<null | T>} The decoded value or null if not found.\n */\n async getItem<T = unknown>(key: string) {\n const rawValue = await instance.getBuffer(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Gets the remaining TTL (in seconds) for a given key.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<number>} The number of seconds until the key expires, or -1 if no expiration is set.\n */\n getItemTtl: (key: string) => instance.ttl(key),\n /**\n * Checks whether a key exists in Redis.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<boolean>} True if the key exists, false otherwise.\n */\n hasItem: async (key: string) => await instance.exists(key) === 1,\n /**\n * The underlying Redis instance, exposed for advanced operations.\n * Use with caution; most use cases should rely on the wrapper methods.\n *\n * @returns {Redis} The underlying Redis instance.\n */\n get instance() {\n return instance;\n },\n /**\n * Removes a key from Redis.\n *\n * @param {string} key - The Redis key to delete.\n *\n * @returns {Promise<boolean>} A Promise that resolves to `true` if the key was removed,\n * or `false` if it did not exist.\n */\n removeItem: async (key: string) => await instance.del(key) === 1,\n /**\n * Stores a value in Redis without expiration.\n *\n * @param {string} key - The Redis key.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItem: (key: string, value: any) => instance.set(key, encodeToStorageValue(value)),\n /**\n * Stores a value in Redis with a time-to-live (TTL).\n *\n * @param {string} key - The Redis key.\n * @param {number} seconds - Expiration time in seconds.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItemWithTtl(key: string, seconds: number, value: any) {\n return instance.setex(key, seconds, encodeToStorageValue(value));\n },\n });\n}\n\nfunction decodeStorageValue(data: Buffer) {\n if (!isCustomFormat(data)) return data;\n const payload = data.subarray(customValueHeaderLength);\n const type = data[customValueHeader.byteLength];\n switch (type) {\n case StorageValueEncodingType.Buffer: return payload;\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload.toString()));\n } catch {\n throw new Error('[RedisStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload.toString();\n default:\n throw new Error(`[RedisStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (Buffer.isBuffer(value)) return toCustomValue(StorageValueEncodingType.Buffer, value);\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, Buffer.from(value));\n return toCustomValue(StorageValueEncodingType.Json, Buffer.from(JSON.stringify(serialize(value))));\n}\n\nfunction isCustomFormat(buffer: Buffer) {\n return (\n buffer.length >= customValueHeaderLength\n && buffer[0] === customValueHeader[0]\n && buffer[1] === customValueHeader[1]\n && buffer[2] === customValueHeader[2]\n );\n}\n\nfunction toCustomValue(type: StorageValueEncodingType, payload: Buffer) {\n return Buffer.concat([\n customValueHeader,\n Buffer.of(type),\n payload,\n ]);\n}\n"],"names":["Buffer","Redis","deserialize","serialize"],"mappings":";;;;;;AAQA,IAAK,wBAIJ;AAJD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,wBAAA,CAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAQ;AACR,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACd,CAAC,EAJI,wBAAwB,KAAxB,wBAAwB,
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../../../../src/storage/enhanced/redis/core.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\n\nimport { Redis } from 'ioredis';\nimport {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Buffer = 0,\n Json = 1,\n String = 2,\n}\n\nconst customValueHeader = Buffer.of(\n 0xE2,\n 0x81,\n 0xA0,\n);\n\nconst customValueHeaderLength = customValueHeader.byteLength + 1;\n\n/**\n * Creates an enhanced Redis-based storage interface using SuperJSON encoding.\n *\n * This utility provides a typed, serializable key-value store backed by Redis,\n * supporting TTL operations and safe deserialization of complex types (e.g. Date, Map).\n *\n * @param {Redis | string} ioRedisInstanceOrUrl - Either an existing `ioredis` instance or a Redis connection string.\n *\n * @returns A frozen object that wraps Redis commands with typed get/set logic and encoding.\n *\n * @example\n * ```typescript\n * import { createEnhancedRedisStorage } from '@kikiutils/shared/storage/enhanced/redis';\n *\n * const redisStorage = createEnhancedRedisStorage('redis://localhost');\n * await redisStorage.setItem('user:1', { name: 'user' });\n * const user = await redisStorage.getItem<{ name: string }>('user:1');\n * ```\n */\nexport function createEnhancedRedisStorage(ioRedisInstanceOrUrl: Redis | string) {\n const instance = ioRedisInstanceOrUrl instanceof Redis ? ioRedisInstanceOrUrl : new Redis(ioRedisInstanceOrUrl);\n return Object.freeze({\n /**\n * Retrieves a value from Redis and decodes it.\n *\n * @template T - The expected return type.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<null | T>} The decoded value or null if not found.\n */\n async getItem<T = unknown>(key: string) {\n const rawValue = await instance.getBuffer(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Gets the remaining TTL (in seconds) for a given key.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<number>} The number of seconds until the key expires, or -1 if no expiration is set.\n */\n getItemTtl: (key: string) => instance.ttl(key),\n /**\n * Checks whether a key exists in Redis.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<boolean>} True if the key exists, false otherwise.\n */\n hasItem: async (key: string) => await instance.exists(key) === 1,\n /**\n * The underlying Redis instance, exposed for advanced operations.\n * Use with caution; most use cases should rely on the wrapper methods.\n *\n * @returns {Redis} The underlying Redis instance.\n */\n get instance() {\n return instance;\n },\n /**\n * Removes a key from Redis.\n *\n * @param {string} key - The Redis key to delete.\n *\n * @returns {Promise<boolean>} A Promise that resolves to `true` if the key was removed,\n * or `false` if it did not exist.\n */\n removeItem: async (key: string) => await instance.del(key) === 1,\n /**\n * Stores a value in Redis without expiration.\n *\n * @param {string} key - The Redis key.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItem: (key: string, value: any) => instance.set(key, encodeToStorageValue(value)),\n /**\n * Stores a value in Redis with a time-to-live (TTL).\n *\n * @param {string} key - The Redis key.\n * @param {number} seconds - Expiration time in seconds.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItemWithTtl(key: string, seconds: number, value: any) {\n return instance.setex(key, seconds, encodeToStorageValue(value));\n },\n });\n}\n\nfunction decodeStorageValue(data: Buffer) {\n if (!isCustomFormat(data)) return data;\n const payload = data.subarray(customValueHeaderLength);\n const type = data[customValueHeader.byteLength];\n switch (type) {\n case StorageValueEncodingType.Buffer: return payload;\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload.toString()));\n } catch {\n throw new Error('[RedisStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload.toString();\n default:\n throw new Error(`[RedisStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (Buffer.isBuffer(value)) return toCustomValue(StorageValueEncodingType.Buffer, value);\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, Buffer.from(value));\n return toCustomValue(StorageValueEncodingType.Json, Buffer.from(JSON.stringify(serialize(value))));\n}\n\nfunction isCustomFormat(buffer: Buffer) {\n return (\n buffer.length >= customValueHeaderLength\n && buffer[0] === customValueHeader[0]\n && buffer[1] === customValueHeader[1]\n && buffer[2] === customValueHeader[2]\n );\n}\n\nfunction toCustomValue(type: StorageVal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,CAAG,CAAC;;AAE7E;AAEA,SAAS,oBAAoB,CAAC,KAAU,EAAA;AACpC,IAAA,IAAIF,kBAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAE,KAAK,CAAC;IACxF,IAAI,OAAO,KAAK,KAAK,QAAQ;AAAE,QAAA,OAAO,aAAa,CAAC,wBAAwB,CAAC,MAAM,EAAEA,kBAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxG,OAAO,aAAa,CAAC,wBAAwB,CAAC,IAAI,EAAEA,kBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAACG,mBAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACtG;AAEA,SAAS,cAAc,CAAC,MAAc,EAAA;AAClC,IAAA,QACI,MAAM,CAAC,MAAM,IAAI;AACd,WAAA,MAAM,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC;AACjC,WAAA,MAAM,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC;WACjC,MAAM,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAC;AAE7C;AAEA,SAAS,aAAa,CAAC,IAA8B,EAAE,OAAe,EAAA;IAClE,OAAOH,kBAAM,CAAC,MAAM,CAAC;QACjB,iBAAiB;AACjB,QAAAA,kBAAM,CAAC,EAAE,CAAC,IAAI,CAAC;QACf,OAAO;AACV,KAAA,CAAC;AACN;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.mjs","sources":["../../../../src/storage/enhanced/redis/core.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\n\nimport { Redis } from 'ioredis';\nimport {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Buffer = 0,\n Json = 1,\n String = 2,\n}\n\nconst customValueHeader = Buffer.of(\n 0xE2,\n 0x81,\n 0xA0,\n);\n\nconst customValueHeaderLength = customValueHeader.byteLength + 1;\n\n/**\n * Creates an enhanced Redis-based storage interface using SuperJSON encoding.\n *\n * This utility provides a typed, serializable key-value store backed by Redis,\n * supporting TTL operations and safe deserialization of complex types (e.g. Date, Map).\n *\n * @param {Redis | string} ioRedisInstanceOrUrl - Either an existing `ioredis` instance or a Redis connection string.\n *\n * @returns A frozen object that wraps Redis commands with typed get/set logic and encoding.\n *\n * @example\n * ```typescript\n * import { createEnhancedRedisStorage } from '@kikiutils/shared/storage/enhanced/redis';\n *\n * const redisStorage = createEnhancedRedisStorage('redis://localhost');\n * await redisStorage.setItem('user:1', { name: 'user' });\n * const user = await redisStorage.getItem<{ name: string }>('user:1');\n * ```\n */\nexport function createEnhancedRedisStorage(ioRedisInstanceOrUrl: Redis | string) {\n const instance = ioRedisInstanceOrUrl instanceof Redis ? ioRedisInstanceOrUrl : new Redis(ioRedisInstanceOrUrl);\n return Object.freeze({\n /**\n * Retrieves a value from Redis and decodes it.\n *\n * @template T - The expected return type.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<null | T>} The decoded value or null if not found.\n */\n async getItem<T = unknown>(key: string) {\n const rawValue = await instance.getBuffer(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Gets the remaining TTL (in seconds) for a given key.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<number>} The number of seconds until the key expires, or -1 if no expiration is set.\n */\n getItemTtl: (key: string) => instance.ttl(key),\n /**\n * Checks whether a key exists in Redis.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<boolean>} True if the key exists, false otherwise.\n */\n hasItem: async (key: string) => await instance.exists(key) === 1,\n /**\n * The underlying Redis instance, exposed for advanced operations.\n * Use with caution; most use cases should rely on the wrapper methods.\n *\n * @returns {Redis} The underlying Redis instance.\n */\n get instance() {\n return instance;\n },\n /**\n * Removes a key from Redis.\n *\n * @param {string} key - The Redis key to delete.\n *\n * @returns {Promise<boolean>} A Promise that resolves to `true` if the key was removed,\n * or `false` if it did not exist.\n */\n removeItem: async (key: string) => await instance.del(key) === 1,\n /**\n * Stores a value in Redis without expiration.\n *\n * @param {string} key - The Redis key.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItem: (key: string, value: any) => instance.set(key, encodeToStorageValue(value)),\n /**\n * Stores a value in Redis with a time-to-live (TTL).\n *\n * @param {string} key - The Redis key.\n * @param {number} seconds - Expiration time in seconds.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItemWithTtl(key: string, seconds: number, value: any) {\n return instance.setex(key, seconds, encodeToStorageValue(value));\n },\n });\n}\n\nfunction decodeStorageValue(data: Buffer) {\n if (!isCustomFormat(data)) return data;\n const payload = data.subarray(customValueHeaderLength);\n const type = data[customValueHeader.byteLength];\n switch (type) {\n case StorageValueEncodingType.Buffer: return payload;\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload.toString()));\n } catch {\n throw new Error('[RedisStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload.toString();\n default:\n throw new Error(`[RedisStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (Buffer.isBuffer(value)) return toCustomValue(StorageValueEncodingType.Buffer, value);\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, Buffer.from(value));\n return toCustomValue(StorageValueEncodingType.Json, Buffer.from(JSON.stringify(serialize(value))));\n}\n\nfunction isCustomFormat(buffer: Buffer) {\n return (\n buffer.length >= customValueHeaderLength\n && buffer[0] === customValueHeader[0]\n && buffer[1] === customValueHeader[1]\n && buffer[2] === customValueHeader[2]\n );\n}\n\nfunction toCustomValue(type: StorageValueEncodingType, payload: Buffer) {\n return Buffer.concat([\n customValueHeader,\n Buffer.of(type),\n payload,\n ]);\n}\n"],"names":[],"mappings":";;;;AAQA,IAAK,wBAIJ;AAJD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,wBAAA,CAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAQ;AACR,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACd,CAAC,EAJI,wBAAwB,KAAxB,wBAAwB,
|
|
1
|
+
{"version":3,"file":"core.mjs","sources":["../../../../src/storage/enhanced/redis/core.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\n\nimport { Redis } from 'ioredis';\nimport {\n deserialize,\n serialize,\n} from 'superjson';\n\nenum StorageValueEncodingType {\n Buffer = 0,\n Json = 1,\n String = 2,\n}\n\nconst customValueHeader = Buffer.of(\n 0xE2,\n 0x81,\n 0xA0,\n);\n\nconst customValueHeaderLength = customValueHeader.byteLength + 1;\n\n/**\n * Creates an enhanced Redis-based storage interface using SuperJSON encoding.\n *\n * This utility provides a typed, serializable key-value store backed by Redis,\n * supporting TTL operations and safe deserialization of complex types (e.g. Date, Map).\n *\n * @param {Redis | string} ioRedisInstanceOrUrl - Either an existing `ioredis` instance or a Redis connection string.\n *\n * @returns A frozen object that wraps Redis commands with typed get/set logic and encoding.\n *\n * @example\n * ```typescript\n * import { createEnhancedRedisStorage } from '@kikiutils/shared/storage/enhanced/redis';\n *\n * const redisStorage = createEnhancedRedisStorage('redis://localhost');\n * await redisStorage.setItem('user:1', { name: 'user' });\n * const user = await redisStorage.getItem<{ name: string }>('user:1');\n * ```\n */\nexport function createEnhancedRedisStorage(ioRedisInstanceOrUrl: Redis | string) {\n const instance = ioRedisInstanceOrUrl instanceof Redis ? ioRedisInstanceOrUrl : new Redis(ioRedisInstanceOrUrl);\n return Object.freeze({\n /**\n * Retrieves a value from Redis and decodes it.\n *\n * @template T - The expected return type.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<null | T>} The decoded value or null if not found.\n */\n async getItem<T = unknown>(key: string) {\n const rawValue = await instance.getBuffer(key);\n return rawValue ? decodeStorageValue(rawValue) as T : null;\n },\n /**\n * Gets the remaining TTL (in seconds) for a given key.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<number>} The number of seconds until the key expires, or -1 if no expiration is set.\n */\n getItemTtl: (key: string) => instance.ttl(key),\n /**\n * Checks whether a key exists in Redis.\n *\n * @param {string} key - The Redis key.\n *\n * @returns {Promise<boolean>} True if the key exists, false otherwise.\n */\n hasItem: async (key: string) => await instance.exists(key) === 1,\n /**\n * The underlying Redis instance, exposed for advanced operations.\n * Use with caution; most use cases should rely on the wrapper methods.\n *\n * @returns {Redis} The underlying Redis instance.\n */\n get instance() {\n return instance;\n },\n /**\n * Removes a key from Redis.\n *\n * @param {string} key - The Redis key to delete.\n *\n * @returns {Promise<boolean>} A Promise that resolves to `true` if the key was removed,\n * or `false` if it did not exist.\n */\n removeItem: async (key: string) => await instance.del(key) === 1,\n /**\n * Stores a value in Redis without expiration.\n *\n * @param {string} key - The Redis key.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItem: (key: string, value: any) => instance.set(key, encodeToStorageValue(value)),\n /**\n * Stores a value in Redis with a time-to-live (TTL).\n *\n * @param {string} key - The Redis key.\n * @param {number} seconds - Expiration time in seconds.\n * @param {any} value - The value to store. Will be serialized.\n */\n setItemWithTtl(key: string, seconds: number, value: any) {\n return instance.setex(key, seconds, encodeToStorageValue(value));\n },\n });\n}\n\nfunction decodeStorageValue(data: Buffer) {\n if (!isCustomFormat(data)) return data;\n const payload = data.subarray(customValueHeaderLength);\n const type = data[customValueHeader.byteLength];\n switch (type) {\n case StorageValueEncodingType.Buffer: return payload;\n case StorageValueEncodingType.Json:\n try {\n return deserialize(JSON.parse(payload.toString()));\n } catch {\n throw new Error('[RedisStorage] Failed to parse JSON payload.');\n }\n case StorageValueEncodingType.String: return payload.toString();\n default:\n throw new Error(`[RedisStorage] Unknown encoding type: ${type}.`);\n }\n}\n\nfunction encodeToStorageValue(value: any) {\n if (Buffer.isBuffer(value)) return toCustomValue(StorageValueEncodingType.Buffer, value);\n if (typeof value === 'string') return toCustomValue(StorageValueEncodingType.String, Buffer.from(value));\n return toCustomValue(StorageValueEncodingType.Json, Buffer.from(JSON.stringify(serialize(value))));\n}\n\nfunction isCustomFormat(buffer: Buffer) {\n return (\n buffer.length >= customValueHeaderLength\n && buffer[0] === customValueHeader[0]\n && buffer[1] === customValueHeader[1]\n && buffer[2] === customValueHeader[2]\n );\n}\n\nfunction toCustomValue(type: StorageValueEncodingType, payload: Buffer) {\n return Buffer.concat([\n customValueHeader,\n Buffer.of(type),\n payload,\n ]);\n}\n"],"names":[],"mappings":";;;;AAQA,IAAK,wBAIJ;AAJD,CAAA,UAAK,wBAAwB,EAAA;AACzB,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,wBAAA,CAAA,wBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAQ;AACR,IAAA,wBAAA,CAAA,wBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACd,CAAC,EAJI,wBAAwB,KAAxB,wBAAwB,GAAA,EAAA,CAAA,CAAA;AAM7B,MAAM,iBAAiB,GAAG,MAAM,CAAC,EAAE,CAC/B,IAAI,EACJ,IAAI,EACJ,IAAI,CACP;AAED,MAAM,uBAAuB,GAAG,iBAAiB,CAAC,UAAU,GAAG,CAAC;AAEhE;;;;;;;;;;;;;;;;;;AAkBG;AACG,SAAU,0BAA0B,CAAC,oBAAoC,EAAA;AAC3E,IAAA,MAAM,QAAQ,GAAG,oBAAoB,YAAY,KAAK,GAAG,oBAAoB,GAAG,IAAI,KAAK,CAAC,oBAAoB,CAAC;IAC/G,OAAO,MAAM,CAAC,MAAM,CAAC;AACjB;;;;;;;;AAQG;QACH,MAAM,OAAO,CAAc,GAAW,EAAA;YAClC,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC;AAC9C,YAA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,"file":"url.cjs","sources":["../src/url.ts"],"sourcesContent":["/**\n * Appends or updates the `redirect` query parameter on a given URL.\n *\n * Typically used to preserve the user's current path for post-login navigation.\n *\n * @param {string} url - The target URL to modify.\n * @param {string} redirectPath - The path to use as the redirect destination.\n *\n * @returns {string} A new URL string with the `redirect` query parameter.\n */\nexport function appendRedirectParamToUrl(url: string, redirectPath: string) {\n const [base, rawQuery = ''] = url.split('?');\n const searchParams = new URLSearchParams(rawQuery);\n searchParams.set('redirect', redirectPath);\n return `${base}?${searchParams.toString()}`;\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;AASG;
|
|
1
|
+
{"version":3,"file":"url.cjs","sources":["../src/url.ts"],"sourcesContent":["/**\n * Appends or updates the `redirect` query parameter on a given URL.\n *\n * Typically used to preserve the user's current path for post-login navigation.\n *\n * @param {string} url - The target URL to modify.\n * @param {string} redirectPath - The path to use as the redirect destination.\n *\n * @returns {string} A new URL string with the `redirect` query parameter.\n */\nexport function appendRedirectParamToUrl(url: string, redirectPath: string) {\n const [base, rawQuery = ''] = url.split('?');\n const searchParams = new URLSearchParams(rawQuery);\n searchParams.set('redirect', redirectPath);\n return `${base}?${searchParams.toString()}`;\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,GAAW,EAAE,YAAoB,EAAA;AACtE,IAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;AAC5C,IAAA,MAAM,YAAY,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC;AAClD,IAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,CAAC;IAC1C,OAAO,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,YAAY,CAAC,QAAQ,EAAE,EAAE;AAC/C;;;;"}
|
package/dist/url.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url.mjs","sources":["../src/url.ts"],"sourcesContent":["/**\n * Appends or updates the `redirect` query parameter on a given URL.\n *\n * Typically used to preserve the user's current path for post-login navigation.\n *\n * @param {string} url - The target URL to modify.\n * @param {string} redirectPath - The path to use as the redirect destination.\n *\n * @returns {string} A new URL string with the `redirect` query parameter.\n */\nexport function appendRedirectParamToUrl(url: string, redirectPath: string) {\n const [base, rawQuery = ''] = url.split('?');\n const searchParams = new URLSearchParams(rawQuery);\n searchParams.set('redirect', redirectPath);\n return `${base}?${searchParams.toString()}`;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;AASG;
|
|
1
|
+
{"version":3,"file":"url.mjs","sources":["../src/url.ts"],"sourcesContent":["/**\n * Appends or updates the `redirect` query parameter on a given URL.\n *\n * Typically used to preserve the user's current path for post-login navigation.\n *\n * @param {string} url - The target URL to modify.\n * @param {string} redirectPath - The path to use as the redirect destination.\n *\n * @returns {string} A new URL string with the `redirect` query parameter.\n */\nexport function appendRedirectParamToUrl(url: string, redirectPath: string) {\n const [base, rawQuery = ''] = url.split('?');\n const searchParams = new URLSearchParams(rawQuery);\n searchParams.set('redirect', redirectPath);\n return `${base}?${searchParams.toString()}`;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;AASG;AACG,SAAU,wBAAwB,CAAC,GAAW,EAAE,YAAoB,EAAA;AACtE,IAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;AAC5C,IAAA,MAAM,YAAY,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC;AAClD,IAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,CAAC;IAC1C,OAAO,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,YAAY,CAAC,QAAQ,EAAE,EAAE;AAC/C;;;;"}
|
package/dist/web.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.cjs","sources":["../src/web.ts"],"sourcesContent":["import { appendRedirectParamToUrl } from './url';\n\n/**\n * Appends the current browser URL (including path, query, and hash) as the `redirect` query parameter to the given URL.\n *\n * @param {string} url - The base URL to modify.\n *\n * @returns {string} A new URL with the current location as the `redirect` parameter.\n */\nexport function appendRedirectParamFromCurrentLocationToUrl(url: string) {\n const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n return appendRedirectParamToUrl(url, currentPath);\n}\n\n/**\n * Navigates to the given URL, appending the current browser location\n * (path, query, and hash) as the `redirect` query parameter.\n *\n * Useful for redirecting to login or other gateways while preserving\n * the current location for post-auth navigation.\n *\n * @param {string} url - The destination URL to navigate to.\n * @param {number} [delayMs] - Optional delay in milliseconds before navigation.\n */\nexport function assignUrlWithRedirectParamFromCurrentLocation(url: string, delayMs?: number) {\n if (delayMs === undefined) window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url));\n else return setTimeout(() => window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url)), delayMs);\n}\n"],"names":["url","appendRedirectParamToUrl"],"mappings":";;;;AAEA;;;;;;AAMG;AACG,SAAU,2CAA2C,CAACA,KAAW,EAAA;IACnE,MAAM,WAAW,GAAG,
|
|
1
|
+
{"version":3,"file":"web.cjs","sources":["../src/web.ts"],"sourcesContent":["import { appendRedirectParamToUrl } from './url';\n\n/**\n * Appends the current browser URL (including path, query, and hash) as the `redirect` query parameter to the given URL.\n *\n * @param {string} url - The base URL to modify.\n *\n * @returns {string} A new URL with the current location as the `redirect` parameter.\n */\nexport function appendRedirectParamFromCurrentLocationToUrl(url: string) {\n const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n return appendRedirectParamToUrl(url, currentPath);\n}\n\n/**\n * Navigates to the given URL, appending the current browser location\n * (path, query, and hash) as the `redirect` query parameter.\n *\n * Useful for redirecting to login or other gateways while preserving\n * the current location for post-auth navigation.\n *\n * @param {string} url - The destination URL to navigate to.\n * @param {number} [delayMs] - Optional delay in milliseconds before navigation.\n */\nexport function assignUrlWithRedirectParamFromCurrentLocation(url: string, delayMs?: number) {\n if (delayMs === undefined) window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url));\n else return setTimeout(() => window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url)), delayMs);\n}\n"],"names":["url","appendRedirectParamToUrl"],"mappings":";;;;AAEA;;;;;;AAMG;AACG,SAAU,2CAA2C,CAACA,KAAW,EAAA;IACnE,MAAM,WAAW,GAAG,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAA,CAAE;AACjG,IAAA,OAAOC,4BAAwB,CAACD,KAAG,EAAE,WAAW,CAAC;AACrD;AAEA;;;;;;;;;AASG;AACG,SAAU,6CAA6C,CAAC,GAAW,EAAE,OAAgB,EAAA;IACvF,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,2CAA2C,CAAC,GAAG,CAAC,CAAC;;AAC9F,QAAA,OAAO,UAAU,CAAC,MAAM,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,2CAA2C,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC;AACnH;;;;;"}
|
package/dist/web.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.mjs","sources":["../src/web.ts"],"sourcesContent":["import { appendRedirectParamToUrl } from './url';\n\n/**\n * Appends the current browser URL (including path, query, and hash) as the `redirect` query parameter to the given URL.\n *\n * @param {string} url - The base URL to modify.\n *\n * @returns {string} A new URL with the current location as the `redirect` parameter.\n */\nexport function appendRedirectParamFromCurrentLocationToUrl(url: string) {\n const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n return appendRedirectParamToUrl(url, currentPath);\n}\n\n/**\n * Navigates to the given URL, appending the current browser location\n * (path, query, and hash) as the `redirect` query parameter.\n *\n * Useful for redirecting to login or other gateways while preserving\n * the current location for post-auth navigation.\n *\n * @param {string} url - The destination URL to navigate to.\n * @param {number} [delayMs] - Optional delay in milliseconds before navigation.\n */\nexport function assignUrlWithRedirectParamFromCurrentLocation(url: string, delayMs?: number) {\n if (delayMs === undefined) window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url));\n else return setTimeout(() => window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url)), delayMs);\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACG,SAAU,2CAA2C,CAAC,GAAW,EAAA;IACnE,MAAM,WAAW,GAAG,
|
|
1
|
+
{"version":3,"file":"web.mjs","sources":["../src/web.ts"],"sourcesContent":["import { appendRedirectParamToUrl } from './url';\n\n/**\n * Appends the current browser URL (including path, query, and hash) as the `redirect` query parameter to the given URL.\n *\n * @param {string} url - The base URL to modify.\n *\n * @returns {string} A new URL with the current location as the `redirect` parameter.\n */\nexport function appendRedirectParamFromCurrentLocationToUrl(url: string) {\n const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n return appendRedirectParamToUrl(url, currentPath);\n}\n\n/**\n * Navigates to the given URL, appending the current browser location\n * (path, query, and hash) as the `redirect` query parameter.\n *\n * Useful for redirecting to login or other gateways while preserving\n * the current location for post-auth navigation.\n *\n * @param {string} url - The destination URL to navigate to.\n * @param {number} [delayMs] - Optional delay in milliseconds before navigation.\n */\nexport function assignUrlWithRedirectParamFromCurrentLocation(url: string, delayMs?: number) {\n if (delayMs === undefined) window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url));\n else return setTimeout(() => window.location.assign(appendRedirectParamFromCurrentLocationToUrl(url)), delayMs);\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACG,SAAU,2CAA2C,CAAC,GAAW,EAAA;IACnE,MAAM,WAAW,GAAG,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAA,EAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAA,CAAE;AACjG,IAAA,OAAO,wBAAwB,CAAC,GAAG,EAAE,WAAW,CAAC;AACrD;AAEA;;;;;;;;;AASG;AACG,SAAU,6CAA6C,CAAC,GAAW,EAAE,OAAgB,EAAA;IACvF,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,2CAA2C,CAAC,GAAG,CAAC,CAAC;;AAC9F,QAAA,OAAO,UAAU,CAAC,MAAM,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,2CAA2C,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC;AACnH;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kikiutils/shared",
|
|
3
|
-
"version": "10.1
|
|
3
|
+
"version": "10.2.1",
|
|
4
4
|
"description": "A lightweight and modular utility library for modern JavaScript and TypeScript — includes secure hashing, flexible logging, datetime tools, Vue/web helpers, storage abstraction, and more.",
|
|
5
5
|
"author": "kiki-kanri",
|
|
6
6
|
"license": "MIT",
|
|
@@ -68,17 +68,17 @@
|
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@kikiutils/changelogen": "^0.8.0",
|
|
71
|
-
"@kikiutils/eslint-config": "^1.
|
|
72
|
-
"@kikiutils/tsconfigs": "^5.0.
|
|
71
|
+
"@kikiutils/eslint-config": "^1.2.7",
|
|
72
|
+
"@kikiutils/tsconfigs": "^5.0.4",
|
|
73
73
|
"@noble/hashes": "^1.8.0",
|
|
74
|
-
"@types/node": "^
|
|
75
|
-
"@vitest/coverage-v8": "^3.
|
|
74
|
+
"@types/node": "^24.0.10",
|
|
75
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
76
76
|
"async-validator": "^4.2.5",
|
|
77
77
|
"consola": "^3.4.2",
|
|
78
78
|
"cross-env": "^7.0.3",
|
|
79
79
|
"date-fns": "^4.1.0",
|
|
80
80
|
"decimal.js": "^10.5.0",
|
|
81
|
-
"element-plus": "^2.
|
|
81
|
+
"element-plus": "^2.10.2",
|
|
82
82
|
"ioredis": "^5.6.1",
|
|
83
83
|
"jsdom": "^26.1.0",
|
|
84
84
|
"lru-cache": "^11.1.0",
|
|
@@ -86,10 +86,10 @@
|
|
|
86
86
|
"pino": "^9.7.0",
|
|
87
87
|
"pino-pretty": "^13.0.0",
|
|
88
88
|
"superjson": "^2.2.2",
|
|
89
|
-
"ts-project-builder": "^5.0.
|
|
89
|
+
"ts-project-builder": "^5.0.2",
|
|
90
90
|
"typescript": "^5.8.3",
|
|
91
|
-
"vitest": "^3.
|
|
92
|
-
"vue": "^3.5.
|
|
91
|
+
"vitest": "^3.2.4",
|
|
92
|
+
"vue": "^3.5.17",
|
|
93
93
|
"vue-router": "^4.5.1"
|
|
94
94
|
},
|
|
95
95
|
"pnpm": {
|
package/src/object.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes a nested object into a deterministic, flat string format.
|
|
3
|
+
*
|
|
4
|
+
* This function recursively traverses the input object (including nested objects and arrays),
|
|
5
|
+
* flattens it into key paths using dot notation (e.g. "a.b.0.c"), sorts all keys,
|
|
6
|
+
* and joins each key-value pair into a string with customizable separators.
|
|
7
|
+
*
|
|
8
|
+
* It is designed for use cases such as signature generation, cache key construction,
|
|
9
|
+
* or any context requiring consistent and predictable object serialization.
|
|
10
|
+
*
|
|
11
|
+
* @param {Record<string, any>} input - The object to serialize. Can contain nested objects and arrays.
|
|
12
|
+
* @param {string} kvSeparator - The string used to separate each key from its value (default: '=').
|
|
13
|
+
* @param {string} pairSeparator - The string used to separate each key-value pair (default: '&').
|
|
14
|
+
* @returns {string} A deterministic string representation of the input object.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { stringifyObjectDeterministically } from '@kikiutils/shared/object';
|
|
19
|
+
*
|
|
20
|
+
* console.log(stringifyObjectDeterministically({ b: 2, a: { x: 1, y: [3, 4] } })); // a.x=1&a.y.0=3&a.y.1=4&b=2
|
|
21
|
+
* console.log(stringifyObjectDeterministically({ foo: 'bar' }, ':', '|')); // foo:bar
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export function stringifyObjectDeterministically(
|
|
25
|
+
input: Record<string, any>,
|
|
26
|
+
kvSeparator: string = '=',
|
|
27
|
+
pairSeparator: string = '&',
|
|
28
|
+
) {
|
|
29
|
+
const entries: string[] = [];
|
|
30
|
+
|
|
31
|
+
function walk(object: any, path: string[] = []) {
|
|
32
|
+
if (Array.isArray(object)) {
|
|
33
|
+
object.forEach((value, index) => {
|
|
34
|
+
walk(
|
|
35
|
+
value,
|
|
36
|
+
[
|
|
37
|
+
...path,
|
|
38
|
+
index.toString(),
|
|
39
|
+
],
|
|
40
|
+
);
|
|
41
|
+
});
|
|
42
|
+
} else if (
|
|
43
|
+
object !== null
|
|
44
|
+
&& typeof object === 'object'
|
|
45
|
+
&& Object.prototype.toString.call(object) === '[object Object]'
|
|
46
|
+
) {
|
|
47
|
+
Object.keys(object).sort().forEach((key) => {
|
|
48
|
+
walk(
|
|
49
|
+
object[key],
|
|
50
|
+
[
|
|
51
|
+
...path,
|
|
52
|
+
key,
|
|
53
|
+
],
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
} else entries.push(`${path.join('.')}${kvSeparator}${String(object)}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
walk(input);
|
|
60
|
+
return entries.sort().join(pairSeparator);
|
|
61
|
+
}
|