@trackunit/shared-utils 1.22.5-alpha-07efa4379b2.0 → 1.22.8
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/index.cjs.js +204 -0
- package/index.esm.js +199 -1
- package/package.json +1 -1
- package/src/index.d.ts +2 -0
- package/src/urlPersistence/hashFragment.d.ts +70 -0
- package/src/urlPersistence/urlIdentity.d.ts +64 -0
package/index.cjs.js
CHANGED
|
@@ -1890,6 +1890,204 @@ const isSorted = (sortInput) => {
|
|
|
1890
1890
|
return originalKeys.every((key, index) => key === sortedKeys[index]);
|
|
1891
1891
|
};
|
|
1892
1892
|
|
|
1893
|
+
/**
|
|
1894
|
+
* Pure utilities for reading and writing single named entries inside a URL
|
|
1895
|
+
* fragment (the part after `#`).
|
|
1896
|
+
*
|
|
1897
|
+
* # Format contract
|
|
1898
|
+
*
|
|
1899
|
+
* The fragment body (after the leading `#`) is treated as a sequence of
|
|
1900
|
+
* `&`-separated tokens. A token may be:
|
|
1901
|
+
* - **A named entry** — `<key>=<value>` (the first `=` separates key from
|
|
1902
|
+
* value; later `=` chars are part of the value).
|
|
1903
|
+
* - **Foreign content** — anything else (bare scroll anchors like
|
|
1904
|
+
* `section`, hash routes, third-party data, malformed tokens). Foreign
|
|
1905
|
+
* tokens are preserved byte-for-byte, in their original positions.
|
|
1906
|
+
*
|
|
1907
|
+
* # Single-key ownership
|
|
1908
|
+
*
|
|
1909
|
+
* Callers operate on **one** named key per invocation. Every token whose
|
|
1910
|
+
* key does not match the supplied key is foreign — the utility never
|
|
1911
|
+
* categorises or rewrites it. This mirrors how `useSearchParamSync`
|
|
1912
|
+
* treats a single named search param.
|
|
1913
|
+
*
|
|
1914
|
+
* # Value-encoding invariant
|
|
1915
|
+
*
|
|
1916
|
+
* Values passed to {@link writeHashKey} must not contain `&`, `=`, or `#`.
|
|
1917
|
+
* The standard producer for this codebase is `useCustomEncoding`, whose
|
|
1918
|
+
* base64url alphabet (`[A-Za-z0-9_-]`) satisfies the invariant by
|
|
1919
|
+
* construction. Keys are restricted by the existing persistence-key
|
|
1920
|
+
* schema (camelCase, ≤15 chars), so they are likewise safe.
|
|
1921
|
+
*
|
|
1922
|
+
* # Anchor-scroll caveat
|
|
1923
|
+
*
|
|
1924
|
+
* Browsers locate scroll targets by matching the entire fragment string
|
|
1925
|
+
* against element IDs. Appending a named entry to a fragment containing
|
|
1926
|
+
* a bare anchor (e.g. `#section` becoming `#section&userTableTp=...`)
|
|
1927
|
+
* therefore breaks anchor scrolling on that page. This is unavoidable
|
|
1928
|
+
* for any hash-backed shared state. Consumers that rely on scroll
|
|
1929
|
+
* anchors should not also persist state to the hash on the same route.
|
|
1930
|
+
*/
|
|
1931
|
+
const TOKEN_SEPARATOR = "&";
|
|
1932
|
+
const KEY_VALUE_SEPARATOR = "=";
|
|
1933
|
+
const stripLeadingHash = (hash) => (hash.startsWith("#") ? hash.slice(1) : hash);
|
|
1934
|
+
const formatHash = (body) => (body.length === 0 ? "" : `#${body}`);
|
|
1935
|
+
/**
|
|
1936
|
+
* Reads the value of a single named entry from a URL fragment.
|
|
1937
|
+
*
|
|
1938
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
1939
|
+
* @param key - The entry key to look up.
|
|
1940
|
+
* @returns {string | undefined} The raw value (everything after the first
|
|
1941
|
+
* `=` in the matching token), or `undefined` when the key is absent. An
|
|
1942
|
+
* entry whose token has no `=` is treated as foreign content and ignored.
|
|
1943
|
+
*/
|
|
1944
|
+
const readHashKey = (hash, key) => {
|
|
1945
|
+
const body = stripLeadingHash(hash);
|
|
1946
|
+
if (body.length === 0) {
|
|
1947
|
+
return undefined;
|
|
1948
|
+
}
|
|
1949
|
+
for (const token of body.split(TOKEN_SEPARATOR)) {
|
|
1950
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
1951
|
+
if (eqIndex > 0 && token.slice(0, eqIndex) === key) {
|
|
1952
|
+
return token.slice(eqIndex + 1);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
return undefined;
|
|
1956
|
+
};
|
|
1957
|
+
/**
|
|
1958
|
+
* Lists the key of every named entry in a URL fragment, in order of first
|
|
1959
|
+
* appearance. Foreign tokens (no `=`) are skipped and duplicates collapse.
|
|
1960
|
+
*
|
|
1961
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
1962
|
+
* @returns {Array<string>} The distinct entry keys.
|
|
1963
|
+
*/
|
|
1964
|
+
const listHashKeys = (hash) => {
|
|
1965
|
+
const body = stripLeadingHash(hash);
|
|
1966
|
+
if (body.length === 0) {
|
|
1967
|
+
return [];
|
|
1968
|
+
}
|
|
1969
|
+
const keys = [];
|
|
1970
|
+
for (const token of body.split(TOKEN_SEPARATOR)) {
|
|
1971
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
1972
|
+
if (eqIndex > 0) {
|
|
1973
|
+
const key = token.slice(0, eqIndex);
|
|
1974
|
+
if (!keys.includes(key)) {
|
|
1975
|
+
keys.push(key);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
return keys;
|
|
1980
|
+
};
|
|
1981
|
+
/**
|
|
1982
|
+
* Returns a new fragment string with the named entry written, replaced,
|
|
1983
|
+
* or removed. Foreign tokens are preserved in their original order; the
|
|
1984
|
+
* named entry retains its position if it already exists, and is appended
|
|
1985
|
+
* to the end when newly inserted. Empty tokens (e.g. produced by
|
|
1986
|
+
* consecutive `&`) are dropped on the way out.
|
|
1987
|
+
*
|
|
1988
|
+
* @param hash - The current fragment string, with or without the leading `#`.
|
|
1989
|
+
* @param key - The entry key to write.
|
|
1990
|
+
* @param value - The value to set, or `undefined` to remove the entry.
|
|
1991
|
+
* @returns {string} The new fragment string, including a leading `#` when
|
|
1992
|
+
* non-empty, or an empty string when the result has no tokens left.
|
|
1993
|
+
*/
|
|
1994
|
+
const writeHashKey = (hash, key, value) => {
|
|
1995
|
+
const body = stripLeadingHash(hash);
|
|
1996
|
+
const tokens = body.length === 0 ? [] : body.split(TOKEN_SEPARATOR);
|
|
1997
|
+
const next = [];
|
|
1998
|
+
let replaced = false;
|
|
1999
|
+
for (const token of tokens) {
|
|
2000
|
+
if (token.length === 0) {
|
|
2001
|
+
continue;
|
|
2002
|
+
}
|
|
2003
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
2004
|
+
if (eqIndex > 0 && token.slice(0, eqIndex) === key) {
|
|
2005
|
+
if (value !== undefined && !replaced) {
|
|
2006
|
+
next.push(`${key}${KEY_VALUE_SEPARATOR}${value}`);
|
|
2007
|
+
replaced = true;
|
|
2008
|
+
}
|
|
2009
|
+
// Else: drop the token (either removing the key or dropping a
|
|
2010
|
+
// duplicate occurrence after we already wrote the replacement).
|
|
2011
|
+
continue;
|
|
2012
|
+
}
|
|
2013
|
+
next.push(token);
|
|
2014
|
+
}
|
|
2015
|
+
if (value !== undefined && !replaced) {
|
|
2016
|
+
next.push(`${key}${KEY_VALUE_SEPARATOR}${value}`);
|
|
2017
|
+
}
|
|
2018
|
+
return formatHash(next.join(TOKEN_SEPARATOR));
|
|
2019
|
+
};
|
|
2020
|
+
|
|
2021
|
+
/**
|
|
2022
|
+
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
2023
|
+
* wrote it.
|
|
2024
|
+
*
|
|
2025
|
+
* A URL (hash or search param) is shared by every account that uses the same
|
|
2026
|
+
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
2027
|
+
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
2028
|
+
* there is no way to tell "a colleague shared this link" from "the previous
|
|
2029
|
+
* account on this PC left its layout in the address bar" — and the second
|
|
2030
|
+
* case silently replaces the current user's saved state (GLU-2396).
|
|
2031
|
+
*
|
|
2032
|
+
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
2033
|
+
* It is not a secret and not a security boundary; it only lets a reader
|
|
2034
|
+
* recognise a value written by a *different* identity on the same device.
|
|
2035
|
+
*/
|
|
2036
|
+
/**
|
|
2037
|
+
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
2038
|
+
* Values written before stamping existed are bare payloads and decode as
|
|
2039
|
+
* unowned (see {@link unwrapUrlOwner}).
|
|
2040
|
+
*/
|
|
2041
|
+
const stampedUrlValueSchema = zod.z.object({
|
|
2042
|
+
o: zod.z.string(),
|
|
2043
|
+
v: zod.z.unknown(),
|
|
2044
|
+
});
|
|
2045
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
2046
|
+
const FNV_PRIME = 0x01000193;
|
|
2047
|
+
/**
|
|
2048
|
+
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
2049
|
+
*
|
|
2050
|
+
* Synchronous and dependency-free so it can run inside a `useState`
|
|
2051
|
+
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
2052
|
+
* collision can only make a foreign value look like the reader's own, which
|
|
2053
|
+
* is today's behaviour for every value.
|
|
2054
|
+
*
|
|
2055
|
+
* @param identity - The client-side user id to fingerprint.
|
|
2056
|
+
* @returns {string} A short stable fingerprint of `identity`.
|
|
2057
|
+
*/
|
|
2058
|
+
const identityFingerprint = (identity) => {
|
|
2059
|
+
let hash = FNV_OFFSET_BASIS;
|
|
2060
|
+
for (let index = 0; index < identity.length; index++) {
|
|
2061
|
+
hash ^= identity.charCodeAt(index);
|
|
2062
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
2063
|
+
}
|
|
2064
|
+
return hash.toString(36);
|
|
2065
|
+
};
|
|
2066
|
+
/**
|
|
2067
|
+
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
2068
|
+
*
|
|
2069
|
+
* @param value - The payload that would otherwise be encoded into the URL.
|
|
2070
|
+
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
2071
|
+
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
2072
|
+
*/
|
|
2073
|
+
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
2074
|
+
/**
|
|
2075
|
+
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
2076
|
+
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
2077
|
+
*
|
|
2078
|
+
* @param decoded - The decoded URL value, stamped or bare.
|
|
2079
|
+
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
2080
|
+
*/
|
|
2081
|
+
const unwrapUrlOwner = (decoded) => {
|
|
2082
|
+
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
2083
|
+
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
2084
|
+
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
2085
|
+
// is what keeps it unowned. Do not remove it as redundant.
|
|
2086
|
+
return stamped.success && "v" in stamped.data
|
|
2087
|
+
? { owner: stamped.data.o, value: stamped.data.v }
|
|
2088
|
+
: { owner: undefined, value: decoded };
|
|
2089
|
+
};
|
|
2090
|
+
|
|
1893
2091
|
/**
|
|
1894
2092
|
* Generates a version 3 UUID (namespace with MD5).
|
|
1895
2093
|
*
|
|
@@ -2107,6 +2305,7 @@ exports.getStartOfDay = getStartOfDay;
|
|
|
2107
2305
|
exports.groupBy = groupBy;
|
|
2108
2306
|
exports.groupTinyDataToOthers = groupTinyDataToOthers;
|
|
2109
2307
|
exports.hourIntervals = hourIntervals;
|
|
2308
|
+
exports.identityFingerprint = identityFingerprint;
|
|
2110
2309
|
exports.intersection = intersection;
|
|
2111
2310
|
exports.isArrayEqual = isArrayEqual;
|
|
2112
2311
|
exports.isNavigatingAway = isNavigatingAway;
|
|
@@ -2114,6 +2313,7 @@ exports.isSortByProperty = isSortByProperty;
|
|
|
2114
2313
|
exports.isSorted = isSorted;
|
|
2115
2314
|
exports.isUUID = isUUID;
|
|
2116
2315
|
exports.isValidImage = isValidImage;
|
|
2316
|
+
exports.listHashKeys = listHashKeys;
|
|
2117
2317
|
exports.loadSVGDimensions = loadSVGDimensions;
|
|
2118
2318
|
exports.markNavigatingAway = markNavigatingAway;
|
|
2119
2319
|
exports.nonNullable = nonNullable;
|
|
@@ -2128,6 +2328,7 @@ exports.parseTailwindArbitraryValue = parseTailwindArbitraryValue;
|
|
|
2128
2328
|
exports.pick = pick;
|
|
2129
2329
|
exports.preload = preload;
|
|
2130
2330
|
exports.readFromStorage = readFromStorage;
|
|
2331
|
+
exports.readHashKey = readHashKey;
|
|
2131
2332
|
exports.readLocalStorageValue = readLocalStorageValue;
|
|
2132
2333
|
exports.removeLeftPadding = removeLeftPadding;
|
|
2133
2334
|
exports.removeLocalStorageValue = removeLocalStorageValue;
|
|
@@ -2154,9 +2355,12 @@ exports.trimIds = trimIds;
|
|
|
2154
2355
|
exports.trimPath = trimPath;
|
|
2155
2356
|
exports.truthy = truthy;
|
|
2156
2357
|
exports.unionArraysByKey = unionArraysByKey;
|
|
2358
|
+
exports.unwrapUrlOwner = unwrapUrlOwner;
|
|
2157
2359
|
exports.uuidv3 = uuidv3;
|
|
2158
2360
|
exports.uuidv4 = uuidv4;
|
|
2159
2361
|
exports.uuidv5 = uuidv5;
|
|
2160
2362
|
exports.validateState = validateState;
|
|
2363
|
+
exports.wrapUrlOwner = wrapUrlOwner;
|
|
2364
|
+
exports.writeHashKey = writeHashKey;
|
|
2161
2365
|
exports.writeLocalStorageValue = writeLocalStorageValue;
|
|
2162
2366
|
exports.writeToStorage = writeToStorage;
|
package/index.esm.js
CHANGED
|
@@ -1888,6 +1888,204 @@ const isSorted = (sortInput) => {
|
|
|
1888
1888
|
return originalKeys.every((key, index) => key === sortedKeys[index]);
|
|
1889
1889
|
};
|
|
1890
1890
|
|
|
1891
|
+
/**
|
|
1892
|
+
* Pure utilities for reading and writing single named entries inside a URL
|
|
1893
|
+
* fragment (the part after `#`).
|
|
1894
|
+
*
|
|
1895
|
+
* # Format contract
|
|
1896
|
+
*
|
|
1897
|
+
* The fragment body (after the leading `#`) is treated as a sequence of
|
|
1898
|
+
* `&`-separated tokens. A token may be:
|
|
1899
|
+
* - **A named entry** — `<key>=<value>` (the first `=` separates key from
|
|
1900
|
+
* value; later `=` chars are part of the value).
|
|
1901
|
+
* - **Foreign content** — anything else (bare scroll anchors like
|
|
1902
|
+
* `section`, hash routes, third-party data, malformed tokens). Foreign
|
|
1903
|
+
* tokens are preserved byte-for-byte, in their original positions.
|
|
1904
|
+
*
|
|
1905
|
+
* # Single-key ownership
|
|
1906
|
+
*
|
|
1907
|
+
* Callers operate on **one** named key per invocation. Every token whose
|
|
1908
|
+
* key does not match the supplied key is foreign — the utility never
|
|
1909
|
+
* categorises or rewrites it. This mirrors how `useSearchParamSync`
|
|
1910
|
+
* treats a single named search param.
|
|
1911
|
+
*
|
|
1912
|
+
* # Value-encoding invariant
|
|
1913
|
+
*
|
|
1914
|
+
* Values passed to {@link writeHashKey} must not contain `&`, `=`, or `#`.
|
|
1915
|
+
* The standard producer for this codebase is `useCustomEncoding`, whose
|
|
1916
|
+
* base64url alphabet (`[A-Za-z0-9_-]`) satisfies the invariant by
|
|
1917
|
+
* construction. Keys are restricted by the existing persistence-key
|
|
1918
|
+
* schema (camelCase, ≤15 chars), so they are likewise safe.
|
|
1919
|
+
*
|
|
1920
|
+
* # Anchor-scroll caveat
|
|
1921
|
+
*
|
|
1922
|
+
* Browsers locate scroll targets by matching the entire fragment string
|
|
1923
|
+
* against element IDs. Appending a named entry to a fragment containing
|
|
1924
|
+
* a bare anchor (e.g. `#section` becoming `#section&userTableTp=...`)
|
|
1925
|
+
* therefore breaks anchor scrolling on that page. This is unavoidable
|
|
1926
|
+
* for any hash-backed shared state. Consumers that rely on scroll
|
|
1927
|
+
* anchors should not also persist state to the hash on the same route.
|
|
1928
|
+
*/
|
|
1929
|
+
const TOKEN_SEPARATOR = "&";
|
|
1930
|
+
const KEY_VALUE_SEPARATOR = "=";
|
|
1931
|
+
const stripLeadingHash = (hash) => (hash.startsWith("#") ? hash.slice(1) : hash);
|
|
1932
|
+
const formatHash = (body) => (body.length === 0 ? "" : `#${body}`);
|
|
1933
|
+
/**
|
|
1934
|
+
* Reads the value of a single named entry from a URL fragment.
|
|
1935
|
+
*
|
|
1936
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
1937
|
+
* @param key - The entry key to look up.
|
|
1938
|
+
* @returns {string | undefined} The raw value (everything after the first
|
|
1939
|
+
* `=` in the matching token), or `undefined` when the key is absent. An
|
|
1940
|
+
* entry whose token has no `=` is treated as foreign content and ignored.
|
|
1941
|
+
*/
|
|
1942
|
+
const readHashKey = (hash, key) => {
|
|
1943
|
+
const body = stripLeadingHash(hash);
|
|
1944
|
+
if (body.length === 0) {
|
|
1945
|
+
return undefined;
|
|
1946
|
+
}
|
|
1947
|
+
for (const token of body.split(TOKEN_SEPARATOR)) {
|
|
1948
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
1949
|
+
if (eqIndex > 0 && token.slice(0, eqIndex) === key) {
|
|
1950
|
+
return token.slice(eqIndex + 1);
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
return undefined;
|
|
1954
|
+
};
|
|
1955
|
+
/**
|
|
1956
|
+
* Lists the key of every named entry in a URL fragment, in order of first
|
|
1957
|
+
* appearance. Foreign tokens (no `=`) are skipped and duplicates collapse.
|
|
1958
|
+
*
|
|
1959
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
1960
|
+
* @returns {Array<string>} The distinct entry keys.
|
|
1961
|
+
*/
|
|
1962
|
+
const listHashKeys = (hash) => {
|
|
1963
|
+
const body = stripLeadingHash(hash);
|
|
1964
|
+
if (body.length === 0) {
|
|
1965
|
+
return [];
|
|
1966
|
+
}
|
|
1967
|
+
const keys = [];
|
|
1968
|
+
for (const token of body.split(TOKEN_SEPARATOR)) {
|
|
1969
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
1970
|
+
if (eqIndex > 0) {
|
|
1971
|
+
const key = token.slice(0, eqIndex);
|
|
1972
|
+
if (!keys.includes(key)) {
|
|
1973
|
+
keys.push(key);
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
return keys;
|
|
1978
|
+
};
|
|
1979
|
+
/**
|
|
1980
|
+
* Returns a new fragment string with the named entry written, replaced,
|
|
1981
|
+
* or removed. Foreign tokens are preserved in their original order; the
|
|
1982
|
+
* named entry retains its position if it already exists, and is appended
|
|
1983
|
+
* to the end when newly inserted. Empty tokens (e.g. produced by
|
|
1984
|
+
* consecutive `&`) are dropped on the way out.
|
|
1985
|
+
*
|
|
1986
|
+
* @param hash - The current fragment string, with or without the leading `#`.
|
|
1987
|
+
* @param key - The entry key to write.
|
|
1988
|
+
* @param value - The value to set, or `undefined` to remove the entry.
|
|
1989
|
+
* @returns {string} The new fragment string, including a leading `#` when
|
|
1990
|
+
* non-empty, or an empty string when the result has no tokens left.
|
|
1991
|
+
*/
|
|
1992
|
+
const writeHashKey = (hash, key, value) => {
|
|
1993
|
+
const body = stripLeadingHash(hash);
|
|
1994
|
+
const tokens = body.length === 0 ? [] : body.split(TOKEN_SEPARATOR);
|
|
1995
|
+
const next = [];
|
|
1996
|
+
let replaced = false;
|
|
1997
|
+
for (const token of tokens) {
|
|
1998
|
+
if (token.length === 0) {
|
|
1999
|
+
continue;
|
|
2000
|
+
}
|
|
2001
|
+
const eqIndex = token.indexOf(KEY_VALUE_SEPARATOR);
|
|
2002
|
+
if (eqIndex > 0 && token.slice(0, eqIndex) === key) {
|
|
2003
|
+
if (value !== undefined && !replaced) {
|
|
2004
|
+
next.push(`${key}${KEY_VALUE_SEPARATOR}${value}`);
|
|
2005
|
+
replaced = true;
|
|
2006
|
+
}
|
|
2007
|
+
// Else: drop the token (either removing the key or dropping a
|
|
2008
|
+
// duplicate occurrence after we already wrote the replacement).
|
|
2009
|
+
continue;
|
|
2010
|
+
}
|
|
2011
|
+
next.push(token);
|
|
2012
|
+
}
|
|
2013
|
+
if (value !== undefined && !replaced) {
|
|
2014
|
+
next.push(`${key}${KEY_VALUE_SEPARATOR}${value}`);
|
|
2015
|
+
}
|
|
2016
|
+
return formatHash(next.join(TOKEN_SEPARATOR));
|
|
2017
|
+
};
|
|
2018
|
+
|
|
2019
|
+
/**
|
|
2020
|
+
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
2021
|
+
* wrote it.
|
|
2022
|
+
*
|
|
2023
|
+
* A URL (hash or search param) is shared by every account that uses the same
|
|
2024
|
+
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
2025
|
+
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
2026
|
+
* there is no way to tell "a colleague shared this link" from "the previous
|
|
2027
|
+
* account on this PC left its layout in the address bar" — and the second
|
|
2028
|
+
* case silently replaces the current user's saved state (GLU-2396).
|
|
2029
|
+
*
|
|
2030
|
+
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
2031
|
+
* It is not a secret and not a security boundary; it only lets a reader
|
|
2032
|
+
* recognise a value written by a *different* identity on the same device.
|
|
2033
|
+
*/
|
|
2034
|
+
/**
|
|
2035
|
+
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
2036
|
+
* Values written before stamping existed are bare payloads and decode as
|
|
2037
|
+
* unowned (see {@link unwrapUrlOwner}).
|
|
2038
|
+
*/
|
|
2039
|
+
const stampedUrlValueSchema = z.object({
|
|
2040
|
+
o: z.string(),
|
|
2041
|
+
v: z.unknown(),
|
|
2042
|
+
});
|
|
2043
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
2044
|
+
const FNV_PRIME = 0x01000193;
|
|
2045
|
+
/**
|
|
2046
|
+
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
2047
|
+
*
|
|
2048
|
+
* Synchronous and dependency-free so it can run inside a `useState`
|
|
2049
|
+
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
2050
|
+
* collision can only make a foreign value look like the reader's own, which
|
|
2051
|
+
* is today's behaviour for every value.
|
|
2052
|
+
*
|
|
2053
|
+
* @param identity - The client-side user id to fingerprint.
|
|
2054
|
+
* @returns {string} A short stable fingerprint of `identity`.
|
|
2055
|
+
*/
|
|
2056
|
+
const identityFingerprint = (identity) => {
|
|
2057
|
+
let hash = FNV_OFFSET_BASIS;
|
|
2058
|
+
for (let index = 0; index < identity.length; index++) {
|
|
2059
|
+
hash ^= identity.charCodeAt(index);
|
|
2060
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
2061
|
+
}
|
|
2062
|
+
return hash.toString(36);
|
|
2063
|
+
};
|
|
2064
|
+
/**
|
|
2065
|
+
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
2066
|
+
*
|
|
2067
|
+
* @param value - The payload that would otherwise be encoded into the URL.
|
|
2068
|
+
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
2069
|
+
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
2070
|
+
*/
|
|
2071
|
+
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
2072
|
+
/**
|
|
2073
|
+
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
2074
|
+
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
2075
|
+
*
|
|
2076
|
+
* @param decoded - The decoded URL value, stamped or bare.
|
|
2077
|
+
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
2078
|
+
*/
|
|
2079
|
+
const unwrapUrlOwner = (decoded) => {
|
|
2080
|
+
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
2081
|
+
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
2082
|
+
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
2083
|
+
// is what keeps it unowned. Do not remove it as redundant.
|
|
2084
|
+
return stamped.success && "v" in stamped.data
|
|
2085
|
+
? { owner: stamped.data.o, value: stamped.data.v }
|
|
2086
|
+
: { owner: undefined, value: decoded };
|
|
2087
|
+
};
|
|
2088
|
+
|
|
1891
2089
|
/**
|
|
1892
2090
|
* Generates a version 3 UUID (namespace with MD5).
|
|
1893
2091
|
*
|
|
@@ -2058,4 +2256,4 @@ const formatUsCustomaryDistance = (value) => {
|
|
|
2058
2256
|
}
|
|
2059
2257
|
};
|
|
2060
2258
|
|
|
2061
|
-
export { DateTimeFormat, HoursAndMinutesFormat, UnitsOfMeasurementSI, UnitsOfMeasurementUSCustomary, VISIBLE_ONLY_COLUMN_VISIBILITY_KEY, align, alphabeticallySort, arrayLengthCompare, arrayNotEmpty, booleanCompare, calculateImageScaleRatio, capitalize, clearNavigatingAway, colorsFromStyleDeclaration, convertBlobToBase64, convertMetersToKilometers, convertMetersToYards, convertYardsToMeters, convertYardsToMiles, dateCompare, deleteUndefinedKeys, difference, doNothing, enumFromValue, enumFromValueTypesafe, enumOrUndefinedFromValue, exhaustiveCheck, fetchImageAsBase64, filterByMultiple, formatAddress, formatCoordinates, formatSiDistance, formatUsCustomaryDistance, fuzzySearch, getAllColors, getCountryName, getDifferenceBetweenDates, getEndOfDay, getFirstLevelObjectPropertyDifferences, getISOStringFromDate, getLoremIpsum, getMimeTypeFromDataURL, getResizedDimensions, getStartOfDay, groupBy, groupTinyDataToOthers, hourIntervals, intersection, isArrayEqual, isNavigatingAway, isSortByProperty, isSorted, isUUID, isValidImage, loadSVGDimensions, markNavigatingAway, nonNullable, numberCompare, numberCompareUnknownAfterHighest, objNotEmpty, objectEntries, objectFromEntries, objectKeys, objectValues, parseTailwindArbitraryValue, pick, preload, readFromStorage, readLocalStorageValue, removeLeftPadding, removeLocalStorageValue, removeProperties, removeProperty, replaceNullableNumbersWithZero, resetNavigatingAwayForTests, resizeBlob, resizeImage, rgb2hex, size, storageSerializer, stringCompare, stringCompareFromKey, stringNaturalCompare, stripHiddenCharacters, svgToPNG, titleCase, toID, toIDs, toPNG, toUUID, trimIds, trimPath, truthy, unionArraysByKey, uuidv3, uuidv4, uuidv5, validateState, writeLocalStorageValue, writeToStorage };
|
|
2259
|
+
export { DateTimeFormat, HoursAndMinutesFormat, UnitsOfMeasurementSI, UnitsOfMeasurementUSCustomary, VISIBLE_ONLY_COLUMN_VISIBILITY_KEY, align, alphabeticallySort, arrayLengthCompare, arrayNotEmpty, booleanCompare, calculateImageScaleRatio, capitalize, clearNavigatingAway, colorsFromStyleDeclaration, convertBlobToBase64, convertMetersToKilometers, convertMetersToYards, convertYardsToMeters, convertYardsToMiles, dateCompare, deleteUndefinedKeys, difference, doNothing, enumFromValue, enumFromValueTypesafe, enumOrUndefinedFromValue, exhaustiveCheck, fetchImageAsBase64, filterByMultiple, formatAddress, formatCoordinates, formatSiDistance, formatUsCustomaryDistance, fuzzySearch, getAllColors, getCountryName, getDifferenceBetweenDates, getEndOfDay, getFirstLevelObjectPropertyDifferences, getISOStringFromDate, getLoremIpsum, getMimeTypeFromDataURL, getResizedDimensions, getStartOfDay, groupBy, groupTinyDataToOthers, hourIntervals, identityFingerprint, intersection, isArrayEqual, isNavigatingAway, isSortByProperty, isSorted, isUUID, isValidImage, listHashKeys, loadSVGDimensions, markNavigatingAway, nonNullable, numberCompare, numberCompareUnknownAfterHighest, objNotEmpty, objectEntries, objectFromEntries, objectKeys, objectValues, parseTailwindArbitraryValue, pick, preload, readFromStorage, readHashKey, readLocalStorageValue, removeLeftPadding, removeLocalStorageValue, removeProperties, removeProperty, replaceNullableNumbersWithZero, resetNavigatingAwayForTests, resizeBlob, resizeImage, rgb2hex, size, storageSerializer, stringCompare, stringCompareFromKey, stringNaturalCompare, stripHiddenCharacters, svgToPNG, titleCase, toID, toIDs, toPNG, toUUID, trimIds, trimPath, truthy, unionArraysByKey, unwrapUrlOwner, uuidv3, uuidv4, uuidv5, validateState, wrapUrlOwner, writeHashKey, writeLocalStorageValue, writeToStorage };
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -34,6 +34,8 @@ export * from "./stringUtils";
|
|
|
34
34
|
export * from "./svgTools";
|
|
35
35
|
export * from "./translationUtils";
|
|
36
36
|
export * from "./typeUtils";
|
|
37
|
+
export * from "./urlPersistence/hashFragment";
|
|
38
|
+
export * from "./urlPersistence/urlIdentity";
|
|
37
39
|
export * from "./UUID";
|
|
38
40
|
export * from "./tailwindUtils";
|
|
39
41
|
export * from "./UnitOfMeasurementConverter";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure utilities for reading and writing single named entries inside a URL
|
|
3
|
+
* fragment (the part after `#`).
|
|
4
|
+
*
|
|
5
|
+
* # Format contract
|
|
6
|
+
*
|
|
7
|
+
* The fragment body (after the leading `#`) is treated as a sequence of
|
|
8
|
+
* `&`-separated tokens. A token may be:
|
|
9
|
+
* - **A named entry** — `<key>=<value>` (the first `=` separates key from
|
|
10
|
+
* value; later `=` chars are part of the value).
|
|
11
|
+
* - **Foreign content** — anything else (bare scroll anchors like
|
|
12
|
+
* `section`, hash routes, third-party data, malformed tokens). Foreign
|
|
13
|
+
* tokens are preserved byte-for-byte, in their original positions.
|
|
14
|
+
*
|
|
15
|
+
* # Single-key ownership
|
|
16
|
+
*
|
|
17
|
+
* Callers operate on **one** named key per invocation. Every token whose
|
|
18
|
+
* key does not match the supplied key is foreign — the utility never
|
|
19
|
+
* categorises or rewrites it. This mirrors how `useSearchParamSync`
|
|
20
|
+
* treats a single named search param.
|
|
21
|
+
*
|
|
22
|
+
* # Value-encoding invariant
|
|
23
|
+
*
|
|
24
|
+
* Values passed to {@link writeHashKey} must not contain `&`, `=`, or `#`.
|
|
25
|
+
* The standard producer for this codebase is `useCustomEncoding`, whose
|
|
26
|
+
* base64url alphabet (`[A-Za-z0-9_-]`) satisfies the invariant by
|
|
27
|
+
* construction. Keys are restricted by the existing persistence-key
|
|
28
|
+
* schema (camelCase, ≤15 chars), so they are likewise safe.
|
|
29
|
+
*
|
|
30
|
+
* # Anchor-scroll caveat
|
|
31
|
+
*
|
|
32
|
+
* Browsers locate scroll targets by matching the entire fragment string
|
|
33
|
+
* against element IDs. Appending a named entry to a fragment containing
|
|
34
|
+
* a bare anchor (e.g. `#section` becoming `#section&userTableTp=...`)
|
|
35
|
+
* therefore breaks anchor scrolling on that page. This is unavoidable
|
|
36
|
+
* for any hash-backed shared state. Consumers that rely on scroll
|
|
37
|
+
* anchors should not also persist state to the hash on the same route.
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* Reads the value of a single named entry from a URL fragment.
|
|
41
|
+
*
|
|
42
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
43
|
+
* @param key - The entry key to look up.
|
|
44
|
+
* @returns {string | undefined} The raw value (everything after the first
|
|
45
|
+
* `=` in the matching token), or `undefined` when the key is absent. An
|
|
46
|
+
* entry whose token has no `=` is treated as foreign content and ignored.
|
|
47
|
+
*/
|
|
48
|
+
export declare const readHashKey: (hash: string, key: string) => string | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Lists the key of every named entry in a URL fragment, in order of first
|
|
51
|
+
* appearance. Foreign tokens (no `=`) are skipped and duplicates collapse.
|
|
52
|
+
*
|
|
53
|
+
* @param hash - The fragment string, with or without the leading `#`.
|
|
54
|
+
* @returns {Array<string>} The distinct entry keys.
|
|
55
|
+
*/
|
|
56
|
+
export declare const listHashKeys: (hash: string) => Array<string>;
|
|
57
|
+
/**
|
|
58
|
+
* Returns a new fragment string with the named entry written, replaced,
|
|
59
|
+
* or removed. Foreign tokens are preserved in their original order; the
|
|
60
|
+
* named entry retains its position if it already exists, and is appended
|
|
61
|
+
* to the end when newly inserted. Empty tokens (e.g. produced by
|
|
62
|
+
* consecutive `&`) are dropped on the way out.
|
|
63
|
+
*
|
|
64
|
+
* @param hash - The current fragment string, with or without the leading `#`.
|
|
65
|
+
* @param key - The entry key to write.
|
|
66
|
+
* @param value - The value to set, or `undefined` to remove the entry.
|
|
67
|
+
* @returns {string} The new fragment string, including a leading `#` when
|
|
68
|
+
* non-empty, or an empty string when the result has no tokens left.
|
|
69
|
+
*/
|
|
70
|
+
export declare const writeHashKey: (hash: string, key: string, value: string | undefined) => string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
3
|
+
* wrote it.
|
|
4
|
+
*
|
|
5
|
+
* A URL (hash or search param) is shared by every account that uses the same
|
|
6
|
+
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
7
|
+
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
8
|
+
* there is no way to tell "a colleague shared this link" from "the previous
|
|
9
|
+
* account on this PC left its layout in the address bar" — and the second
|
|
10
|
+
* case silently replaces the current user's saved state (GLU-2396).
|
|
11
|
+
*
|
|
12
|
+
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
13
|
+
* It is not a secret and not a security boundary; it only lets a reader
|
|
14
|
+
* recognise a value written by a *different* identity on the same device.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
/**
|
|
18
|
+
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
19
|
+
* Values written before stamping existed are bare payloads and decode as
|
|
20
|
+
* unowned (see {@link unwrapUrlOwner}).
|
|
21
|
+
*/
|
|
22
|
+
declare const stampedUrlValueSchema: z.ZodObject<{
|
|
23
|
+
o: z.ZodString;
|
|
24
|
+
v: z.ZodUnknown;
|
|
25
|
+
}, "strip", z.ZodTypeAny, {
|
|
26
|
+
o: string;
|
|
27
|
+
v?: unknown;
|
|
28
|
+
}, {
|
|
29
|
+
o: string;
|
|
30
|
+
v?: unknown;
|
|
31
|
+
}>;
|
|
32
|
+
export type StampedUrlValue = z.infer<typeof stampedUrlValueSchema>;
|
|
33
|
+
/**
|
|
34
|
+
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
35
|
+
*
|
|
36
|
+
* Synchronous and dependency-free so it can run inside a `useState`
|
|
37
|
+
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
38
|
+
* collision can only make a foreign value look like the reader's own, which
|
|
39
|
+
* is today's behaviour for every value.
|
|
40
|
+
*
|
|
41
|
+
* @param identity - The client-side user id to fingerprint.
|
|
42
|
+
* @returns {string} A short stable fingerprint of `identity`.
|
|
43
|
+
*/
|
|
44
|
+
export declare const identityFingerprint: (identity: string) => string;
|
|
45
|
+
/**
|
|
46
|
+
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
47
|
+
*
|
|
48
|
+
* @param value - The payload that would otherwise be encoded into the URL.
|
|
49
|
+
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
50
|
+
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
51
|
+
*/
|
|
52
|
+
export declare const wrapUrlOwner: (value: unknown, owner: string) => StampedUrlValue;
|
|
53
|
+
/**
|
|
54
|
+
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
55
|
+
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
56
|
+
*
|
|
57
|
+
* @param decoded - The decoded URL value, stamped or bare.
|
|
58
|
+
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
59
|
+
*/
|
|
60
|
+
export declare const unwrapUrlOwner: (decoded: unknown) => {
|
|
61
|
+
readonly owner: string | undefined;
|
|
62
|
+
readonly value: unknown;
|
|
63
|
+
};
|
|
64
|
+
export {};
|