@ptx-showcase/utils 0.2.3 → 0.3.0

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/README.md CHANGED
@@ -4,7 +4,7 @@ Shared utilities for PTX Showcase projects.
4
4
 
5
5
  ---
6
6
 
7
- ## 📦 Installation
7
+ ## Installation
8
8
 
9
9
  ```bash
10
10
  npm install @ptx-showcase/utils
@@ -18,42 +18,128 @@ bun add @ptx-showcase/utils
18
18
 
19
19
  ---
20
20
 
21
- ## 🚀 Usage
21
+ ## Usage
22
22
 
23
- ### Cookie utilities
23
+ All utilities can be imported from the root package or from a specific subpath.
24
+
25
+ ---
26
+
27
+ ### buildQueryParams
28
+
29
+ Builds a URL query string from an object. Skips `null`, `undefined`, empty strings, and empty arrays.
30
+
31
+ ```ts
32
+ // from root
33
+ import { buildQueryParams } from '@ptx-showcase/utils'
34
+
35
+ // from subpath
36
+ import { buildQueryParams } from '@ptx-showcase/utils/build-query-params'
37
+
38
+ buildQueryParams({ page: 1, search: 'test', empty: '' })
39
+ // → '?page=1&search=test'
40
+
41
+ buildQueryParams({ ids: [], status: 'active' })
42
+ // → '?status=active'
43
+
44
+ buildQueryParams({})
45
+ // → ''
46
+ ```
47
+
48
+ ---
49
+
50
+ ### buildSortParam
51
+
52
+ Builds a comma-separated sort string with toggle logic: first call adds the field, second toggles to descending (`-field`), third removes it.
53
+
54
+ ```ts
55
+ // from root
56
+ import { buildSortParam } from '@ptx-showcase/utils'
57
+
58
+ // from subpath
59
+ import { buildSortParam } from '@ptx-showcase/utils/build-sort-param'
60
+
61
+ buildSortParam('name') // → 'name'
62
+ buildSortParam('name', 'name') // → '-name'
63
+ buildSortParam('name', '-name') // → ''
64
+
65
+ // combining with existing sort
66
+ buildSortParam('age', 'name') // → 'age,name'
67
+ buildSortParam('age', 'age,name') // → '-age,name'
68
+ ```
69
+
70
+ ---
71
+
72
+ ### Cookies
73
+
74
+ Cookie helpers with secure defaults (`expires: 1h`, `secure: true`, `sameSite: Strict`).
24
75
 
25
76
  ```ts
77
+ // from root
78
+ import { setCookie, getCookie, deleteCookie } from '@ptx-showcase/utils'
79
+
80
+ // from subpath
26
81
  import { setCookie, getCookie, deleteCookie } from '@ptx-showcase/utils/cookies'
27
82
 
28
- // set cookie
29
- setCookie('token', '123')
83
+ // set (uses default options)
84
+ setCookie('token', 'abc123')
85
+
86
+ // set with custom options
87
+ setCookie('session', 'xyz', { expires: 7, sameSite: 'Lax' })
30
88
 
31
- // get cookie
32
- const token = getCookie('token')
89
+ // get
90
+ const token = getCookie('token') // → 'abc123' | undefined
33
91
 
34
- // delete cookie
92
+ // delete
35
93
  deleteCookie('token')
36
94
  ```
37
95
 
96
+ Default options:
97
+
98
+ | Option | Value |
99
+ |------------|------------|
100
+ | `expires` | 1 hour |
101
+ | `secure` | `true` |
102
+ | `sameSite` | `'Strict'` |
103
+
38
104
  ---
39
105
 
40
- ## 📁 Available modules
106
+ ### downloadBlob
107
+
108
+ Downloads a `Blob` as a file in the browser. Accepts either an explicit filename or a hash value (auto-generates a SHA-1 filename).
109
+
110
+ ```ts
111
+ // from root
112
+ import { downloadBlob } from '@ptx-showcase/utils'
41
113
 
42
- - `@ptx-showcase/utils` — base utilities
43
- - `@ptx-showcase/utils/cookie` — cookie helpers
114
+ // from subpath
115
+ import { downloadBlob } from '@ptx-showcase/utils/download-file'
116
+
117
+ const blob = new Blob(['Hello, World!'], { type: 'text/plain' })
118
+
119
+ // with explicit filename
120
+ await downloadBlob(blob, { filename: 'report.txt' })
121
+
122
+ // with auto-generated SHA-1 filename
123
+ await downloadBlob(blob, { hash: 12345 })
124
+ // → saves as e.g. '17b840d9...'
125
+ ```
44
126
 
45
127
  ---
46
128
 
47
- ## 🧠 Features
129
+ ## Available modules
48
130
 
49
- - TypeScript support out of the box
50
- - ESM + CommonJS compatibility
51
- - Modular architecture (subpath imports)
52
- - Lightweight and reusable across projects
131
+ | Subpath | Exports |
132
+ |---------------------------------------------|------------------------------------------------------|
133
+ | `@ptx-showcase/utils` | all utilities |
134
+ | `@ptx-showcase/utils/build-query-params` | `buildQueryParams` |
135
+ | `@ptx-showcase/utils/build-sort-param` | `buildSortParam` |
136
+ | `@ptx-showcase/utils/cookies` | `setCookie`, `getCookie`, `deleteCookie`, `defaultCookieOptions` |
137
+ | `@ptx-showcase/utils/download-file` | `downloadBlob` |
138
+ | `@ptx-showcase/utils/types` | `TableColumnConfig` |
53
139
 
54
140
  ---
55
141
 
56
- ## 🔄 Versioning
142
+ ## Versioning
57
143
 
58
144
  This package follows [Semantic Versioning](https://semver.org/):
59
145
 
@@ -63,12 +149,12 @@ This package follows [Semantic Versioning](https://semver.org/):
63
149
 
64
150
  ---
65
151
 
66
- ## 📜 Changelog
152
+ ## Changelog
67
153
 
68
154
  See [CHANGELOG.md](./CHANGELOG.md) for all changes.
69
155
 
70
156
  ---
71
157
 
72
- ## 📄 License
158
+ ## License
73
159
 
74
160
  MIT
@@ -1 +1,22 @@
1
+ /**
2
+ * Builds a URL query string from an object, ready to be appended to a URL.
3
+ *
4
+ * - `undefined`, `null`, `''` (empty string) and empty arrays are skipped
5
+ * - Other values (including `0`, `false`, non-empty arrays) are stringified
6
+ * via `String(value)` and appended as-is — arrays become comma-separated
7
+ * (e.g. `[1, 2, 3]` → `h=1%2C2%2C3`), not repeated `key=value` pairs
8
+ * - Returns `''` (not `'?'`) when there are no params left after filtering
9
+ *
10
+ * @param params - Object whose entries become query string params
11
+ * @returns The query string including a leading `?`, or `''` if empty
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * buildQueryParams({ a: 1, b: '', c: null, d: [1, 2] })
16
+ * // => '?a=1&d=1%2C2'
17
+ *
18
+ * buildQueryParams({ a: undefined, b: '' })
19
+ * // => ''
20
+ * ```
21
+ */
1
22
  export declare const buildQueryParams: <T extends object>(params: T) => string;
@@ -1 +1,21 @@
1
+ /**
2
+ * Builds the next value of a comma-separated sort param string by cycling a
3
+ * field through ascending → descending → removed, e.g. for toggling sort on
4
+ * table column clicks: `"" → "name" → "-name" → ""`.
5
+ *
6
+ * Other fields already present in `prev` are left untouched and keep their
7
+ * relative order; a newly added field is placed at the front of the list.
8
+ *
9
+ * @param field - The field name to toggle (without the `-` prefix)
10
+ * @param prev - The current comma-separated sort string (e.g. `"id,-name"`), if any
11
+ * @returns The updated comma-separated sort string
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * buildSortParam('name') // => 'name'
16
+ * buildSortParam('name', 'name') // => '-name'
17
+ * buildSortParam('name', '-name') // => ''
18
+ * buildSortParam('name', 'id,-surname') // => 'name,id,-surname'
19
+ * ```
20
+ */
1
21
  export declare const buildSortParam: (field: string, prev?: string) => string;
@@ -1,6 +1,26 @@
1
1
  type EmptyValue = undefined | null | '';
2
+ /**
3
+ * Result type of {@link cleanObject} — same shape as `T`, but every property
4
+ * becomes optional and `undefined`/`null`/`''` are excluded from its value type,
5
+ * reflecting that empty values are stripped from the resulting object.
6
+ */
2
7
  export type CleanObjectResult<T extends Record<string, unknown>> = Partial<{
3
8
  [K in keyof T]: Exclude<T[K], EmptyValue>;
4
9
  }>;
10
+ /**
11
+ * Returns a shallow copy of `obj` with all `undefined`, `null` and `''` (empty string)
12
+ * properties removed. Other falsy values (`0`, `false`, empty arrays, etc.) are kept.
13
+ *
14
+ * Useful for trimming objects before sending them as query params or request payloads,
15
+ * where empty fields shouldn't be included.
16
+ *
17
+ * @param obj - The object to clean
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * cleanObject({ a: 1, b: '', c: null, d: false, e: undefined })
22
+ * // => { a: 1, d: false }
23
+ * ```
24
+ */
5
25
  export declare const cleanObject: <T extends Record<string, unknown>>(obj: T) => CleanObjectResult<T>;
6
26
  export {};
@@ -1,5 +1,35 @@
1
1
  export type CookieOptions = Cookies.CookieAttributes;
2
+ /**
3
+ * Default options applied to every {@link setCookie} call: expires in 1 hour,
4
+ * `secure` and `sameSite: 'Strict'`. Can be overridden per-call via `options`.
5
+ */
2
6
  export declare const defaultCookieOptions: CookieOptions;
7
+ /**
8
+ * Sets a cookie, merging the given `options` over {@link defaultCookieOptions}.
9
+ *
10
+ * @param name - Cookie name
11
+ * @param value - Cookie value
12
+ * @param options - Overrides for the default cookie attributes (e.g. `expires`, `secure`, `sameSite`, `path`)
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * setCookie('token', '123')
17
+ * setCookie('token', '123', { expires: 7, secure: false })
18
+ * ```
19
+ */
3
20
  export declare const setCookie: (name: string, value: string, options?: CookieOptions) => void;
21
+ /**
22
+ * Returns the value of the cookie with the given name, or `undefined` if it doesn't exist.
23
+ *
24
+ * @param name - Cookie name
25
+ */
4
26
  export declare const getCookie: (name: string) => string | undefined;
27
+ /**
28
+ * Removes the cookie with the given name.
29
+ *
30
+ * @param name - Cookie name
31
+ * @param options - Attributes the cookie was set with (e.g. `path`, `domain`) —
32
+ * required if the cookie was set with non-default attributes, since removal
33
+ * must match them for the browser to find and delete the cookie
34
+ */
5
35
  export declare const deleteCookie: (name: string, options?: CookieOptions) => void;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("file-saver");var t=async e=>{let t=new TextEncoder().encode(String(e)),n=await crypto.subtle.digest(`SHA-1`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)},n=async(n,r)=>{if(!(n instanceof Blob))throw Error(`downloadBlob: expected Blob, got ${typeof n}`);(0,e.saveAs)(n,`filename`in r?r.filename:await t(r.hash))};exports.downloadBlob=n;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Options for {@link downloadBlob} that determine the resulting filename.
3
+ *
4
+ * - `filename` — uses the given name as-is
5
+ * - `hash` — derives the filename from the hex-encoded SHA-1 hash of the given
6
+ * value, useful when the original filename is unknown or shouldn't be exposed
7
+ */
8
+ type DownloadBlobOptions = {
9
+ filename: string;
10
+ } | {
11
+ hash: string | number;
12
+ };
13
+ /**
14
+ * Triggers a browser download of the given `Blob`, saving it under either an
15
+ * explicit filename or a name derived from the SHA-1 hash of a given value.
16
+ *
17
+ * @param blob - The `Blob` to download
18
+ * @param options - Either `{ filename }` to use an explicit name, or `{ hash }`
19
+ * to derive the filename from the SHA-1 hash of the given string/number
20
+ * @throws {Error} If `blob` is not a `Blob` instance
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * await downloadBlob(blob, { filename: 'report.pdf' })
25
+ * await downloadBlob(blob, { hash: userId })
26
+ * ```
27
+ */
28
+ export declare const downloadBlob: (blob: Blob, options: DownloadBlobOptions) => Promise<void>;
29
+ export {};
@@ -0,0 +1,11 @@
1
+ import { saveAs as e } from "file-saver";
2
+ //#region src/download-file/index.ts
3
+ var t = async (e) => {
4
+ let t = new TextEncoder().encode(String(e)), n = await crypto.subtle.digest("SHA-1", t);
5
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
6
+ }, n = async (n, r) => {
7
+ if (!(n instanceof Blob)) throw Error(`downloadBlob: expected Blob, got ${typeof n}`);
8
+ e(n, "filename" in r ? r.filename : await t(r.hash));
9
+ };
10
+ //#endregion
11
+ export { n as downloadBlob };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./chunks/cookies-BayERMbH.cjs"),t=require("./build-query-params/index.cjs"),n=require("./clean-object/index.cjs"),r=require("./build-sort-param/index.cjs");exports.buildQueryParams=t.buildQueryParams,exports.buildSortParam=r.buildSortParam,exports.cleanObject=n.cleanObject,exports.defaultCookieOptions=e.t,exports.deleteCookie=e.n,exports.getCookie=e.r,exports.setCookie=e.i;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./chunks/cookies-BayERMbH.cjs"),t=require("./build-query-params/index.cjs"),n=require("./clean-object/index.cjs"),r=require("./build-sort-param/index.cjs"),i=require("./download-file/index.cjs"),a=require("./normalize-input/index.cjs");exports.buildQueryParams=t.buildQueryParams,exports.buildSortParam=r.buildSortParam,exports.cleanObject=n.cleanObject,exports.defaultCookieOptions=e.t,exports.deleteCookie=e.n,exports.downloadBlob=i.downloadBlob,exports.getCookie=e.r,exports.normalizeDecimalInput=a.normalizeDecimalInput,exports.normalizePhoneNumberInput=a.normalizePhoneNumberInput,exports.setCookie=e.i;
package/dist/index.d.ts CHANGED
@@ -3,3 +3,5 @@ export * from './clean-object';
3
3
  export * from './cookies';
4
4
  export type * from './types';
5
5
  export * from './build-sort-param';
6
+ export * from './download-file';
7
+ export * from './normalize-input';
package/dist/index.js CHANGED
@@ -2,4 +2,6 @@ import { buildQueryParams as e } from "./build-query-params/index.js";
2
2
  import { cleanObject as t } from "./clean-object/index.js";
3
3
  import { defaultCookieOptions as n, deleteCookie as r, getCookie as i, setCookie as a } from "./cookies/index.js";
4
4
  import { buildSortParam as o } from "./build-sort-param/index.js";
5
- export { e as buildQueryParams, o as buildSortParam, t as cleanObject, n as defaultCookieOptions, r as deleteCookie, i as getCookie, a as setCookie };
5
+ import { downloadBlob as s } from "./download-file/index.js";
6
+ import { normalizeDecimalInput as c, normalizePhoneNumberInput as l } from "./normalize-input/index.js";
7
+ export { e as buildQueryParams, o as buildSortParam, t as cleanObject, n as defaultCookieOptions, r as deleteCookie, s as downloadBlob, i as getCookie, c as normalizeDecimalInput, l as normalizePhoneNumberInput, a as setCookie };
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=(e,t=2)=>{let n=e.target,r=n.value;r=r.replace(`,`,`.`),r=r.replace(/[^0-9.]/g,``);let i=r.indexOf(`.`);i!==-1&&(r=r.slice(0,i+1)+r.slice(i+1).replace(/\./g,``)),r.startsWith(`.`)&&(r=`0`+r);let[a,o]=r.split(`.`);o!==void 0&&(r=t>0?`${a}.${o.slice(0,t)}`:a),n.value=r},t=(e,t=15)=>{let n=e.target,r=n.value.replace(/\D/g,``).slice(0,t);n.value=r?`+`+r:``};exports.normalizeDecimalInput=e,exports.normalizePhoneNumberInput=t;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Sanitizes an input's value into a valid decimal number string in place,
3
+ * intended to be used as an `input`/`change` event handler.
4
+ *
5
+ * - Converts a comma decimal separator into a dot (`1,5` → `1.5`)
6
+ * - Strips any character that isn't a digit or a dot
7
+ * - Keeps only the first dot, removing subsequent ones (`1.2.3` → `1.23`)
8
+ * - Prefixes a leading dot with `0` (`.5` → `0.5`)
9
+ * - Truncates the decimal part to `decimals` digits (`1.2345` → `1.23`)
10
+ *
11
+ * @param e - The native `input`/`change` event from a text input
12
+ * @param decimals - Maximum number of digits allowed after the decimal point.
13
+ * Pass `0` to disallow decimals entirely (the dot is removed). Defaults to `2`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // Vue
18
+ * <input type="text" inputmode="decimal" @input="normalizeDecimalInput" />
19
+ *
20
+ * // React (wrap to access the native event)
21
+ * <input type="text" inputMode="decimal" onChange={(e) => normalizeDecimalInput(e.nativeEvent, 4)} />
22
+ * ```
23
+ */
24
+ export declare const normalizeDecimalInput: (e: Event, decimals?: number) => void;
25
+ /**
26
+ * Sanitizes an input's value into a valid phone number string in place,
27
+ * intended to be used as an `input`/`change` event handler.
28
+ *
29
+ * - Strips any character that isn't a digit
30
+ * - Truncates to `maxDigits` digits (`898812345678` → `89881234567`)
31
+ * - Prefixes the result with a `+` (`89991234567` → `+89991234567`)
32
+ * - Leaves the value empty when there are no digits left, so the field can be cleared
33
+ *
34
+ * @param e - The native `input`/`change` event from a text input
35
+ * @param maxDigits - Maximum number of digits allowed. Defaults to `15` (E.164 limit).
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * // Vue
40
+ * <input type="text" inputmode="tel" @input="normalizePhoneNumberInput" />
41
+ *
42
+ * // React (wrap to access the native event)
43
+ * <input type="text" inputMode="tel" onChange={(e) => normalizePhoneNumberInput(e.nativeEvent, 11)} />
44
+ * ```
45
+ */
46
+ export declare const normalizePhoneNumberInput: (e: Event, maxDigits?: number) => void;
@@ -0,0 +1,14 @@
1
+ //#region src/normalize-input/index.ts
2
+ var e = (e, t = 2) => {
3
+ let n = e.target, r = n.value;
4
+ r = r.replace(",", "."), r = r.replace(/[^0-9.]/g, "");
5
+ let i = r.indexOf(".");
6
+ i !== -1 && (r = r.slice(0, i + 1) + r.slice(i + 1).replace(/\./g, "")), r.startsWith(".") && (r = "0" + r);
7
+ let [a, o] = r.split(".");
8
+ o !== void 0 && (r = t > 0 ? `${a}.${o.slice(0, t)}` : a), n.value = r;
9
+ }, t = (e, t = 15) => {
10
+ let n = e.target, r = n.value.replace(/\D/g, "").slice(0, t);
11
+ n.value = r ? "+" + r : "";
12
+ };
13
+ //#endregion
14
+ export { e as normalizeDecimalInput, t as normalizePhoneNumberInput };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@ptx-showcase/utils",
3
3
  "author": "ptx-showcase",
4
4
  "description": "Shared utilities for PTX Showcase projects",
5
- "version": "0.2.3",
5
+ "version": "0.3.0",
6
6
  "private": false,
7
7
  "type": "module",
8
8
  "license": "MIT",
@@ -51,6 +51,16 @@
51
51
  "require": "./dist/clean-object/index.cjs",
52
52
  "types": "./dist/clean-object/index.d.ts"
53
53
  },
54
+ "./download-file": {
55
+ "import": "./dist/download-file/index.js",
56
+ "require": "./dist/download-file/index.cjs",
57
+ "types": "./dist/download-file/index.d.ts"
58
+ },
59
+ "./normalize-input": {
60
+ "import": "./dist/normalize-input/index.js",
61
+ "require": "./dist/normalize-input/index.cjs",
62
+ "types": "./dist/normalize-input/index.d.ts"
63
+ },
54
64
  "./types": {
55
65
  "import": "./dist/types/index.js",
56
66
  "require": "./dist/types/index.cjs",
@@ -67,16 +77,18 @@
67
77
  "access": "public"
68
78
  },
69
79
  "devDependencies": {
70
- "@types/node": "^25.9.1",
80
+ "@types/node": "^25.9.2",
71
81
  "bumpp": "^11.1.0",
72
- "oxlint": "^1.67.0",
82
+ "oxlint": "^1.68.0",
73
83
  "typescript": "~6.0.3",
74
- "vite": "^8.0.14",
75
- "vite-plugin-dts": "^5.0.1",
76
- "vitest": "^4.1.7"
84
+ "vite": "^8.0.16",
85
+ "vite-plugin-dts": "^5.0.2",
86
+ "vitest": "^4.1.8"
77
87
  },
78
88
  "dependencies": {
89
+ "@types/file-saver": "^2.0.7",
79
90
  "@types/js-cookie": "^3.0.6",
80
- "js-cookie": "^3.0.7"
91
+ "file-saver": "^2.0.5",
92
+ "js-cookie": "^3.0.8"
81
93
  }
82
94
  }