@rebasepro/utils 0.13.0 → 0.13.1-canary.g18cfeb7

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/dates.d.ts CHANGED
@@ -1 +1,32 @@
1
1
  export declare const defaultDateFormat = "MMMM dd, yyyy, HH:mm:ss";
2
+ export type FormatRelativeTimeOptions = {
3
+ /**
4
+ * The instant the distance is measured from. Defaults to the current time.
5
+ * Pass it explicitly to make a caller testable without faking the clock.
6
+ */
7
+ now?: Date | number;
8
+ /**
9
+ * How far a value may sit from {@link now} and still be described
10
+ * relatively. Beyond it the function returns `null` and the caller renders
11
+ * an absolute date instead. Defaults to seven days.
12
+ */
13
+ maxMs?: number;
14
+ };
15
+ /**
16
+ * Describes an instant relative to another one — "5m ago", "in 3h".
17
+ *
18
+ * The direction is part of the answer. Every hand-rolled version of this in the
19
+ * codebase computed `now - then` and then tested only the positive side, so a
20
+ * timestamp in the future fell through to whichever branch happened to be
21
+ * first: a date scheduled for next month read "Just now", and one a couple of
22
+ * hours out read "-1d ago". Both are dates a CMS holds all the time — a publish
23
+ * date, a due date, an expiry — and neither shape can occur here, because the
24
+ * distance is measured with {@link Math.abs} and the tense is chosen from the
25
+ * sign rather than assumed.
26
+ *
27
+ * Returns `null` when the value is unreadable, or when it is further than
28
+ * {@link FormatRelativeTimeOptions.maxMs} away in either direction. `null` is
29
+ * "say it another way", not an error: the caller owns the absolute format, and
30
+ * the locale and precision that go with it.
31
+ */
32
+ export declare function formatRelativeTime(value: Date | string | number | null | undefined, options?: FormatRelativeTimeOptions): string | null;
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./strings";
2
2
  export * from "./objects";
3
3
  export * from "./arrays";
4
4
  export * from "./dates";
5
+ export * from "./storage";
5
6
  export * from "./hash";
6
7
  export * from "./sha1";
7
8
  export * from "./policy-names";
package/dist/index.es.js CHANGED
@@ -74,15 +74,50 @@ var isInteger = (obj) => String(Math.floor(Number(obj))) === String(obj);
74
74
  /** @private is the given object a NaN? */
75
75
  var isNaN = (obj) => obj !== obj;
76
76
  /**
77
+ * Segments that reach the prototype chain rather than a property of the object.
78
+ *
79
+ * The twin of this function in `@rebasepro/forms` could be made to write onto
80
+ * `Object.prototype` through a path of `__proto__.x`. This copy survives the
81
+ * write by accident — its `clone` always spreads into a fresh object, while the
82
+ * form engine's has a "preserve class instances" branch that hands back
83
+ * `Object.prototype` itself — but `getIn` still *reads* through the chain, and
84
+ * handing back `Object.prototype` is how a polluted value is read out again.
85
+ *
86
+ * Closed on both sides here, so the two implementations agree.
87
+ */
88
+ var UNSAFE_PATH_SEGMENTS = /* @__PURE__ */ new Set([
89
+ "__proto__",
90
+ "constructor",
91
+ "prototype"
92
+ ]);
93
+ /** Whether any segment of this path would traverse the prototype chain. */
94
+ function pathTraversesPrototype(path) {
95
+ return toPath(path).some((segment) => UNSAFE_PATH_SEGMENTS.has(segment));
96
+ }
97
+ /**
98
+ * Whether writing this single key with `obj[key] = …` would reach the prototype
99
+ * chain instead of creating a property.
100
+ *
101
+ * The single-key counterpart of {@link pathTraversesPrototype}, for the many
102
+ * places that copy an object one key at a time. `JSON.parse` creates
103
+ * `__proto__` as an *own* property, so it survives `hasOwnProperty` — and then
104
+ * `target[key] = value` invokes the setter and replaces the target's prototype.
105
+ */
106
+ function isPrototypePollutingKey(key) {
107
+ return UNSAFE_PATH_SEGMENTS.has(key);
108
+ }
109
+ /**
77
110
  * Deeply get a value from an object via its path.
78
111
  */
79
112
  function getIn(obj, key, def, p = 0) {
113
+ if (pathTraversesPrototype(key)) return def;
80
114
  const path = toPath(key);
81
115
  while (obj && p < path.length) obj = obj[path[p++]];
82
116
  if (p !== path.length && !obj) return def;
83
117
  return obj === void 0 ? def : obj;
84
118
  }
85
119
  function setIn(obj, path, value) {
120
+ if (pathTraversesPrototype(path)) return obj;
86
121
  const res = clone(obj);
87
122
  let resVal = res;
88
123
  let i = 0;
@@ -292,6 +327,129 @@ function toArray(input) {
292
327
  //#endregion
293
328
  //#region src/dates.ts
294
329
  var defaultDateFormat = "MMMM dd, yyyy, HH:mm:ss";
330
+ /** Seven days, the distance past which a relative phrase stops being useful. */
331
+ var DEFAULT_MAX_MS = 10080 * 60 * 1e3;
332
+ function toTime(value) {
333
+ if (value === null || value === void 0 || value === "") return null;
334
+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime();
335
+ return Number.isNaN(time) ? null : time;
336
+ }
337
+ /**
338
+ * Describes an instant relative to another one — "5m ago", "in 3h".
339
+ *
340
+ * The direction is part of the answer. Every hand-rolled version of this in the
341
+ * codebase computed `now - then` and then tested only the positive side, so a
342
+ * timestamp in the future fell through to whichever branch happened to be
343
+ * first: a date scheduled for next month read "Just now", and one a couple of
344
+ * hours out read "-1d ago". Both are dates a CMS holds all the time — a publish
345
+ * date, a due date, an expiry — and neither shape can occur here, because the
346
+ * distance is measured with {@link Math.abs} and the tense is chosen from the
347
+ * sign rather than assumed.
348
+ *
349
+ * Returns `null` when the value is unreadable, or when it is further than
350
+ * {@link FormatRelativeTimeOptions.maxMs} away in either direction. `null` is
351
+ * "say it another way", not an error: the caller owns the absolute format, and
352
+ * the locale and precision that go with it.
353
+ */
354
+ function formatRelativeTime(value, options = {}) {
355
+ const then = toTime(value);
356
+ if (then === null) return null;
357
+ const now = options.now instanceof Date ? options.now.getTime() : options.now ?? Date.now();
358
+ const maxMs = options.maxMs ?? DEFAULT_MAX_MS;
359
+ const delta = now - then;
360
+ const distance = Math.abs(delta);
361
+ if (distance > maxMs) return null;
362
+ const future = delta < 0;
363
+ const minutes = Math.floor(distance / 6e4);
364
+ if (minutes < 1) return future ? "in a moment" : "just now";
365
+ if (minutes < 60) return future ? `in ${minutes}m` : `${minutes}m ago`;
366
+ const hours = Math.floor(distance / 36e5);
367
+ if (hours < 24) return future ? `in ${hours}h` : `${hours}h ago`;
368
+ const days = Math.floor(distance / 864e5);
369
+ return future ? `in ${days}d` : `${days}d ago`;
370
+ }
371
+ //#endregion
372
+ //#region src/storage.ts
373
+ /**
374
+ * The ambient `localStorage`, or `null` where there is not one. Access itself
375
+ * is what throws when storage is disabled, so even reaching for it is guarded.
376
+ */
377
+ function getWebStorage() {
378
+ try {
379
+ return globalThis.localStorage ?? null;
380
+ } catch {
381
+ return null;
382
+ }
383
+ }
384
+ /**
385
+ * Reads and parses a JSON value a previous session stored, falling back rather
386
+ * than throwing. See the module comment for what it is falling back from.
387
+ *
388
+ * A rejected value is deliberately left in place rather than cleared: this
389
+ * version not understanding it is not evidence that nothing does.
390
+ */
391
+ function readStoredJson(key, options) {
392
+ const storage = options.storage === void 0 ? getWebStorage() : options.storage;
393
+ if (!storage) return options.fallback;
394
+ let raw;
395
+ try {
396
+ raw = storage.getItem(key);
397
+ } catch {
398
+ return options.fallback;
399
+ }
400
+ if (raw === null || raw === "") return options.fallback;
401
+ let parsed;
402
+ try {
403
+ parsed = JSON.parse(raw);
404
+ } catch {
405
+ return options.fallback;
406
+ }
407
+ if (options.accept && !options.accept(parsed)) return options.fallback;
408
+ return parsed;
409
+ }
410
+ /**
411
+ * Persists a value as JSON. Returns whether it was stored, so a caller that
412
+ * cares can say so — most do not, and for them the point is simply that a full
413
+ * quota does not throw out of the effect doing the writing.
414
+ */
415
+ function writeStoredJson(key, value, options = {}) {
416
+ const storage = options.storage === void 0 ? getWebStorage() : options.storage;
417
+ if (!storage) return false;
418
+ try {
419
+ storage.setItem(key, JSON.stringify(value));
420
+ return true;
421
+ } catch {
422
+ return false;
423
+ }
424
+ }
425
+ /**
426
+ * Persists an already-serialised string, for the values kept as plain text
427
+ * rather than JSON — a selected id, a pane size.
428
+ */
429
+ function writeStoredString(key, value, options = {}) {
430
+ const storage = options.storage === void 0 ? getWebStorage() : options.storage;
431
+ if (!storage) return false;
432
+ try {
433
+ storage.setItem(key, value);
434
+ return true;
435
+ } catch {
436
+ return false;
437
+ }
438
+ }
439
+ /** Reads a plain string, absent rather than throwing where there is no storage. */
440
+ function readStoredString(key, options = {}) {
441
+ const storage = options.storage === void 0 ? getWebStorage() : options.storage;
442
+ if (!storage) return null;
443
+ try {
444
+ return storage.getItem(key);
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
449
+ /** `accept` for a caller whose fallback is an array. */
450
+ var isArrayValue = (value) => Array.isArray(value);
451
+ /** `accept` for a caller whose fallback is a keyed object — and not an array. */
452
+ var isRecordValue = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
295
453
  //#endregion
296
454
  //#region src/hash.ts
297
455
  function hashString(str) {
@@ -764,6 +922,6 @@ function isDefaultFieldConfigId(id) {
764
922
  ].includes(id);
765
923
  }
766
924
  //#endregion
767
- export { camelCase, clone, deepClone, defaultDateFormat, flattenObject, generateForeignKeyName, getArrayValuesCount, getHashValue, getIn, getPolicyNameHash, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations, getValueInPath, hashString, hydrateRegExp, isDefaultFieldConfigId, isEmptyArray, isEmptyObject, isFunction, isInteger, isNaN, isObject, isPlainObject, isValidRegExp, legacyForeignKeyName, mergeDeep, pick, plural, prettifyIdentifier, randomColor, randomString, removeFunctions, removeInPath, removeNulls, removePropsIfExisting, removeUndefined, serializeRegExp, setIn, sha1Hex, singular, slugify, toArray, toKebabCase, toSnakeCase, unslugify };
925
+ export { camelCase, clone, deepClone, defaultDateFormat, flattenObject, formatRelativeTime, generateForeignKeyName, getArrayValuesCount, getHashValue, getIn, getPolicyNameHash, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations, getValueInPath, getWebStorage, hashString, hydrateRegExp, isArrayValue, isDefaultFieldConfigId, isEmptyArray, isEmptyObject, isFunction, isInteger, isNaN, isObject, isPlainObject, isPrototypePollutingKey, isRecordValue, isValidRegExp, legacyForeignKeyName, mergeDeep, pathTraversesPrototype, pick, plural, prettifyIdentifier, randomColor, randomString, readStoredJson, readStoredString, removeFunctions, removeInPath, removeNulls, removePropsIfExisting, removeUndefined, serializeRegExp, setIn, sha1Hex, singular, slugify, toArray, toKebabCase, toSnakeCase, unslugify, writeStoredJson, writeStoredString };
768
926
 
769
927
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":[],"sources":["../src/strings.ts","../src/objects.ts","../src/arrays.ts","../src/dates.ts","../src/hash.ts","../src/sha1.ts","../src/policy-names.ts","../src/regexp.ts","../src/flatten_object.ts","../src/plurals.ts","../src/names.ts","../src/fields.ts"],"sourcesContent":["const tokenizeRegex = /[A-Z]{2,}(?=[A-Z][a-z]|\\b)|[A-Z]?[a-z]+|[0-9]+(?:[a-z](?![a-z]))?|[A-Z]/g;\n\nexport const toKebabCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(tokenizeRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"-\");\n};\n\nconst snakeCaseRegex = tokenizeRegex;\n\nexport const toSnakeCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(snakeCaseRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"_\");\n};\n\nexport function camelCase(str: string): string {\n if (!str) return \"\";\n if (str.length === 1) return str.toLowerCase();\n\n // Split by hyphens, underscores, or spaces and filter out empty strings\n const parts = str.split(/[-_ ]+/).filter(Boolean);\n\n if (parts.length === 0) return \"\";\n\n // Start with first part in lowercase\n return parts[0].toLowerCase() +\n // Transform remaining parts to have first letter uppercase\n parts.slice(1)\n .map(part => part.charAt(0).toUpperCase() + part.substring(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * A random base-36 string of exactly `strLength` characters.\n *\n * Not `Math.random().toString(36).slice(2, 2 + strLength)`: that has no\n * guaranteed length. Base-36 of a double drops trailing zeros, so the source\n * string is short about once in 36 calls and the slice quietly returns fewer\n * characters than asked for — `randomString(10)` returning 9. These values\n * prefix uploaded filenames to keep them apart, so a short one is a likelier\n * collision, and it fails at the rate that makes a test look flaky.\n */\nexport function randomString(strLength = 5) {\n const alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n let result = \"\";\n for (let i = 0; i < strLength; i++) {\n result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));\n }\n return result;\n}\n\nexport function randomColor() {\n return Math.floor(Math.random() * 16777215).toString(16);\n}\n\nexport function slugify(text?: string, separator = \"_\", lowercase = true) {\n if (!text) return \"\";\n const from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\"\n const to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\n for (let i = 0, l = from.length; i < l; i++) {\n text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n }\n\n text = text\n .toString() // Cast to string\n .trim() // Remove whitespace from both sides of a string\n .replace(/^\\s+|\\s+$/g, \"\")\n .replace(/\\s+/g, separator) // Replace spaces with separator\n .replace(/&/g, separator) // Replace & with separator\n .replace(/[^\\w\\\\-]+/g, \"\") // Remove all non-word chars\n .replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"),\n separator); // Replace multiple separators with single one\n\n return lowercase\n ? text.toLowerCase() // Convert the string to lowercase letters\n : text;\n}\n\nexport function unslugify(slug?: string): string {\n if (!slug) return \"\";\n if (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) {\n const result = slug.replace(/[-_]/g, \" \");\n return result.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substring(1);\n }).trim();\n } else {\n return slug.trim();\n }\n}\n\nexport function prettifyIdentifier(input: string) {\n if (!input) return \"\";\n\n let text = input;\n\n // 1. Handle camelCase and Acronyms\n // Group 1 ($1 $2): Lowercase followed by Uppercase (e.g., imageURL -> image URL)\n // Group 2 ($3 $4): Uppercase followed by Uppercase+lowercase (e.g., XMLParser -> XML Parser)\n text = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\n // 2. Replace hyphens/underscores with spaces\n text = text.replace(/[_-]+/g, \" \");\n\n // 3. Capitalize first letter of each word (Title Case)\n const s = text\n .trim()\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n return s;\n}\n","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n\n/** @private is the value an empty array? */\nexport const isEmptyArray = (value?: unknown) =>\n Array.isArray(value) && value.length === 0;\n\n/** @private is the given object a Function? */\nexport const isFunction = (obj: unknown): obj is (...args: unknown[]) => unknown =>\n typeof obj === \"function\";\n\n/** @private is the given object an integer? */\nexport const isInteger = (obj: unknown): boolean =>\n String(Math.floor(Number(obj))) === String(obj);\n\n/** @private is the given object a NaN? */\n\nexport const isNaN = (obj: unknown): boolean => obj !== obj;\n\n/**\n * Deeply get a value from an object via its path.\n */\nexport function getIn(\n obj: Record<string, unknown> | unknown[] | unknown,\n key: string | string[],\n def?: unknown,\n p = 0\n) {\n const path = toPath(key);\n while (obj && p < path.length) {\n obj = (obj as Record<string, unknown>)[path[p++]];\n }\n\n // check if path is not in the end\n if (p !== path.length && !obj) {\n return def;\n }\n\n return obj === undefined ? def : obj;\n}\n\nexport function setIn<T>(obj: T, path: string, value: unknown): T {\n const res = clone(obj) as Record<string, unknown>;\n let resVal: Record<string, unknown> = res;\n let i = 0;\n const pathArray = toPath(path);\n\n for (; i < pathArray.length - 1; i++) {\n const currentPath: string = pathArray[i];\n const currentObj = getIn(obj as Record<string, unknown>, pathArray.slice(0, i + 1));\n\n if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {\n resVal = resVal[currentPath] = clone(currentObj) as Record<string, unknown>;\n } else {\n const nextPath: string = pathArray[i + 1];\n resVal = resVal[currentPath] =\n (isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}) as Record<string, unknown>;\n }\n }\n\n // Return original object if new value is the same as current\n if ((i === 0 ? obj as Record<string, unknown> : resVal)[pathArray[i]] === value) {\n return obj;\n }\n\n if (value === undefined) {\n delete resVal[pathArray[i]];\n } else {\n resVal[pathArray[i]] = value;\n }\n\n // If the path array has a single element, the loop did not run.\n // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.\n if (i === 0 && value === undefined) {\n delete res[pathArray[i]];\n }\n\n return res as T;\n}\n\nexport function clone<T>(value: T): T {\n if (Array.isArray(value)) {\n return [...value] as T;\n } else if (typeof value === \"object\" && value !== null) {\n return { ...value } as T;\n } else {\n return value; // This is for primitive types which do not need cloning.\n }\n}\n\n/**\n * Deep clone a value, preserving function references and class instances.\n * Unlike structuredClone, this handles objects that contain functions\n * (e.g. CollectionConfig with target(), childCollections(), callbacks).\n */\nexport function deepClone<T>(value: T): T {\n if (value === null || value === undefined) return value;\n if (typeof value === \"function\") return value;\n if (typeof value !== \"object\") return value;\n\n if (Array.isArray(value)) {\n return value.map(item => deepClone(item)) as T;\n }\n\n // Preserve class instances (Date, GeoPoint, etc.) — don't recurse\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = deepClone((value as Record<string, unknown>)[key]);\n }\n return result as T;\n}\n\nfunction toPath(value: string | string[]) {\n if (Array.isArray(value)) return value; // Already in path array form.\n // Replace brackets with dots, remove leading/trailing dots, then split by dot.\n return value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\n\n\nexport const pick: <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => Partial<T> = <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => ({\n ...args.reduce<Record<string, unknown>>((res, key) => ({\n ...res,\n [key as string]: obj[key as string]\n }), {})\n}) as Partial<T>;\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === \"object\" && !Array.isArray(item);\n}\n\nexport function isPlainObject(obj: unknown): obj is Record<string, unknown> {\n // 1. Rule out non-objects, null, and arrays\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n return false;\n }\n\n // 2. Get the object's direct prototype\n const proto = Object.getPrototypeOf(obj);\n\n // 3. A plain object's direct prototype is Object.prototype\n return proto === Object.prototype;\n}\n\nexport function mergeDeep<T extends object, U extends object>(\n target: T,\n source: U,\n ignoreUndefined = false\n): T & U {\n // If target is not a true object (e.g., null, array, primitive), return target itself.\n if (!isObject(target)) {\n return target as T & U;\n }\n\n // Create a shallow copy of the target to avoid modifying the original object.\n const output = { ...target };\n\n // If source is not a true object, there's nothing to merge from it.\n // Return the shallow copy of target.\n if (!isObject(source)) {\n return output as T & U;\n }\n\n // Iterate over keys in the source object.\n for (const key in source) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n continue;\n }\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const outputValue = (output as Record<string, unknown>)[key]; // Current value in our merged object (originating from target)\n\n // Skip if source value is undefined and ignoreUndefined is true.\n // This handles both not adding new undefined properties and not overwriting existing properties with undefined.\n if (ignoreUndefined && sourceValue === undefined) {\n continue;\n }\n\n if (sourceValue instanceof Date) {\n // If source value is a Date, create a new Date instance.\n (output as Record<string, unknown>)[key] = new Date(sourceValue.getTime());\n } else if (Array.isArray(sourceValue)) {\n if (Array.isArray(outputValue)) {\n // If the array contains primitives or class instances (non-plain objects),\n // overwrite the array entirely instead of doing element-wise merging.\n const hasPlainObjects = sourceValue.some(isPlainObject) || outputValue.some(isPlainObject);\n if (!hasPlainObjects) {\n (output as Record<string, unknown>)[key] = [...sourceValue];\n } else {\n const newArray = [];\n const maxLength = Math.max(outputValue.length, sourceValue.length);\n for (let i = 0; i < maxLength; i++) {\n const sourceItem = sourceValue[i];\n const targetItem = outputValue[i];\n\n if (i >= sourceValue.length) { // source is shorter\n newArray[i] = targetItem;\n } else if (i >= outputValue.length) { // target is shorter\n newArray[i] = sourceItem;\n } else if (sourceItem === null) {\n newArray[i] = targetItem;\n } else if (isPlainObject(sourceItem) && isPlainObject(targetItem)) {\n // Only recursively merge plain objects, preserve class instances\n newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n } else {\n // For class instances and primitives, use source directly\n newArray[i] = sourceItem;\n }\n }\n (output as Record<string, unknown>)[key] = newArray;\n }\n } else {\n // If output's value (from target) is not an array,\n // overwrite with a shallow copy of the source array.\n (output as Record<string, unknown>)[key] = [...sourceValue];\n }\n } else if (isPlainObject(sourceValue)) {\n // If source value is a plain object (not a class instance like EntityReference, GeoPoint, etc.):\n if (isPlainObject(outputValue)) {\n // If the corresponding value in output (from target) is also a plain object, recurse.\n // Ensure the ignoreUndefined flag is passed down.\n (output as Record<string, unknown>)[key] = mergeDeep(outputValue as Record<string, unknown>, sourceValue, ignoreUndefined);\n } else {\n // If output's value (from target) is not a plain object (e.g., null, primitive, class instance, or key didn't exist in original target),\n // overwrite with the source object.\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isObject(sourceValue)) {\n // If source value is a class instance (not a plain object), use it directly to preserve prototype\n (output as Record<string, unknown>)[key] = sourceValue;\n } else {\n // If source value is a primitive, null, or undefined (and not ignored).\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n }\n }\n\n return output as T & U;\n}\n\nexport function getValueInPath(o: object | undefined, path: string): unknown {\n if (!o) return undefined;\n if (typeof o === \"object\") {\n if (path in o) {\n return (o as Record<string, unknown>)[path];\n }\n if (path.includes(\".\") || path.includes(\"[\")) {\n let pathSegments = path.split(/[.[]/);\n if (path.includes(\"[\")) {\n pathSegments = pathSegments.map(segment => segment.replace(\"]\", \"\"));\n }\n const firstSegment = pathSegments[0];\n const isArrayAndIndexExists = Array.isArray((o as Record<string, unknown>)[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n const nextObject = isArrayAndIndexExists\n ? ((o as Record<string, unknown>)[firstSegment] as unknown[])[parseInt(pathSegments[1])]\n : (o as Record<string, unknown>)[firstSegment];\n\n const nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n if (nextPath === \"\")\n return nextObject;\n return getValueInPath(nextObject as object | undefined, nextPath);\n }\n }\n return undefined;\n}\n\nexport function removeInPath(o: object, path: string): object | undefined {\n const res = clone(o) as Record<string, unknown>;\n let current = res;\n const parts = path.split(\".\");\n const last = parts.pop();\n for (const part of parts) {\n if (part in current && current[part] !== null && typeof current[part] === \"object\") {\n current[part] = clone(current[part]) as Record<string, unknown>;\n current = current[part] as Record<string, unknown>;\n } else {\n return res;\n }\n }\n if (last && current && typeof current === \"object\") {\n delete current[last];\n }\n return res;\n}\n\nexport function removeFunctions(o: unknown): unknown {\n if (o === undefined) return undefined;\n if (o === null) return null;\n if (typeof o === \"object\") {\n // Handle arrays first - drop function elements, then recurse.\n // Only object *properties* used to be filtered, so a function sitting\n // directly in an array survived — and the callers strip functions\n // precisely because a function survives no deep comparison.\n if (Array.isArray(o)) {\n return o\n .filter(v => typeof v !== \"function\")\n .map(v => removeFunctions(v));\n }\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(o)) {\n return o;\n }\n return Object.entries(o)\n .filter(([_, value]) => typeof value !== \"function\")\n .reduce<Record<string, unknown>>((acc, [key, value]) => {\n acc[key] = removeFunctions(value);\n return acc;\n }, {});\n }\n return o;\n}\n\nexport function getHashValue<T>(v: T): string | null {\n if (!v) return null;\n if (typeof v === \"object\" && v !== null) {\n if (\"id\" in v)\n return String((v as Record<string, unknown>).id);\n else if (v instanceof Date)\n return v.toLocaleString();\n else if (v instanceof GeoPoint)\n return hash(v as Record<string, unknown>);\n }\n return hash(v as object, { ignoreUnknown: true });\n}\n\nexport function removeUndefined(value: unknown, removeEmptyStrings?: boolean): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeUndefined(v, removeEmptyStrings));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n Object.keys(value).forEach((key) => {\n if (!isEmptyObject(value as object)) {\n const childRes = removeUndefined((value as Record<string, unknown>)[key], removeEmptyStrings);\n const isString = typeof childRes === \"string\";\n const shouldKeepIfString = !removeEmptyStrings || (removeEmptyStrings && !isString) || (removeEmptyStrings && isString && childRes !== \"\");\n if (childRes !== undefined && !isEmptyObject(childRes as object) && shouldKeepIfString)\n res[key] = childRes;\n }\n });\n return res;\n }\n return value;\n}\n\nexport function removeNulls(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeNulls(v));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n const obj = value as Record<string, unknown>;\n Object.keys(obj).forEach((key) => {\n if (obj[key] !== null)\n res[key] = removeNulls(obj[key]);\n });\n return res;\n }\n return value;\n}\n\nexport function isEmptyObject(obj: object) {\n return obj &&\n Object.getPrototypeOf(obj) === Object.prototype &&\n Object.keys(obj).length === 0\n}\n\nexport function removePropsIfExisting(source: Record<string, unknown> | unknown[], comparison: Record<string, unknown> | unknown[]) {\n const isObject = (val: unknown): val is Record<string, unknown> => typeof val === \"object\" && val !== null;\n const isArray = (val: unknown): val is unknown[] => Array.isArray(val);\n\n if (!isObject(source) || !isObject(comparison)) {\n return source;\n }\n\n const res = isArray(source) ? [...source] : { ...source };\n\n if (isArray(res)) {\n for (let i = res.length - 1; i >= 0; i--) {\n if (res[i] === comparison[i]) {\n res.splice(i, 1);\n } else if (isObject(res[i]) && isObject(comparison[i])) {\n res[i] = removePropsIfExisting(res[i] as unknown as Record<string, unknown>, (comparison as unknown as unknown[])[i] as Record<string, unknown>);\n }\n }\n } else {\n Object.keys(comparison).forEach(key => {\n if (key in res) {\n if (isObject(res[key]) && isObject(comparison[key])) {\n res[key] = removePropsIfExisting(res[key], comparison[key]);\n } else if (res[key] === comparison[key]) {\n delete res[key];\n }\n }\n });\n }\n\n return res;\n}\n","/**\n * Normalise a value that may be a single item or a list into a list.\n *\n * Only `null`/`undefined` mean \"nothing\". A truthiness check here silently\n * swallowed legitimate values — `toArray(0)`, `toArray(false)` and `toArray(\"\")`\n * all came back empty, so a caller normalising a single falsy item lost it.\n */\nexport function toArray<T>(input?: T | T[] | null): T[] {\n if (Array.isArray(input)) return input;\n if (input === undefined || input === null) return [];\n return [input];\n}\n","export const defaultDateFormat = \"MMMM dd, yyyy, HH:mm:ss\";\n","export function hashString(str: string): number {\n if (!str) return 0;\n let hash = 0;\n let i;\n let chr;\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return Math.abs(hash);\n}\n","/**\n * Minimal SHA-1 implementation that runs in both Node and the browser.\n *\n * This exists because generated Postgres policy names embed a SHA-1 digest of\n * the security rule. The DDL generator runs on the server (where `node:crypto`\n * is available) but the Studio has to derive the same names in the browser to\n * tell a policy it generated apart from one it did not. `node:crypto` cannot be\n * bundled for the browser, so the shared derivation needs a portable digest.\n *\n * SHA-1 is used purely to name things deterministically — never for security.\n * The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n * which `sha1.test.ts` pins against `node:crypto` directly.\n */\n\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value: number, n: number): number {\n return (value << n) | (value >>> (32 - n));\n}\n\n/**\n * SHA-1 digest of a string, hex-encoded.\n *\n * The input is encoded as UTF-8, matching Node's default handling of strings\n * passed to `hash.update(str)`.\n */\nexport function sha1Hex(input: string): string {\n const bytes: number[] = Array.from(new TextEncoder().encode(input));\n const bitLength = bytes.length * 8;\n\n // Padding: 0x80, then zeroes up to 56 bytes mod 64, then the length as a\n // 64-bit big-endian integer.\n bytes.push(0x80);\n while (bytes.length % 64 !== 56) bytes.push(0);\n\n const hi = Math.floor(bitLength / 0x100000000);\n const lo = bitLength >>> 0;\n bytes.push((hi >>> 24) & 0xff, (hi >>> 16) & 0xff, (hi >>> 8) & 0xff, hi & 0xff);\n bytes.push((lo >>> 24) & 0xff, (lo >>> 16) & 0xff, (lo >>> 8) & 0xff, lo & 0xff);\n\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Array<number>(80);\n\n for (let offset = 0; offset < bytes.length; offset += 64) {\n for (let i = 0; i < 16; i++) {\n const j = offset + i * 4;\n w[i] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) | 0;\n }\n for (let i = 16; i < 80; i++) {\n w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n for (let i = 0; i < 80; i++) {\n let f: number;\n let k: number;\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (rotl(a, 5) + f + e + k + w[i]) | 0;\n e = d;\n d = c;\n c = rotl(b, 30);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n return [h0, h1, h2, h3, h4]\n .map(word => (word >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n","import type { SecurityOperation, SecurityRule } from \"@rebasepro/types\";\nimport { sha1Hex } from \"./sha1\";\n\n/**\n * Naming of the Postgres policies generated from a collection's security rules.\n *\n * A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n * the hash covers the rule's semantics. The Studio needs the same names to tell\n * \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n * without them it treats generated policies as foreign and offers to import\n * them back into the codebase they came from.\n *\n * This is the single definition of that naming. The DDL and Drizzle generators\n * both derive names from here, so a change cannot silently rename every policy\n * in every deployed database while the UI keeps matching the old ones.\n */\n\n/** Stable digest of the parts of a rule that determine what the policy does. */\nexport function getPolicyNameHash(rule: SecurityRule): string {\n const data = JSON.stringify({\n a: rule.access,\n m: rule.mode,\n op: rule.operation,\n ops: rule.operations?.slice().sort(),\n own: rule.ownerField,\n rol: rule.roles?.slice().sort(),\n pg: rule.pgRoles?.slice().sort(),\n u: rule.using,\n w: rule.withCheck,\n c: rule.condition,\n ch: rule.check\n });\n return sha1Hex(data).substring(0, 7);\n}\n\n/** The operations a rule expands to — `operations` wins over `operation`. */\nexport function getPolicyOperations(rule: SecurityRule): readonly SecurityOperation[] {\n return rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n}\n\n/**\n * Every Postgres policy name a single rule compiles to — one per operation.\n *\n * @param rule The security rule as written in the collection config.\n * @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n */\nexport function getPolicyNamesForRule(rule: SecurityRule, tableName: string): string[] {\n const ops = getPolicyOperations(rule);\n const ruleHash = getPolicyNameHash(rule);\n\n return ops.map((op, opIdx) => rule.name\n ? (ops.length > 1 ? `${rule.name}_${op}` : rule.name)\n : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n\n/** Every policy name a set of rules compiles to, for membership checks. */\nexport function getPolicyNamesForRules(rules: SecurityRule[], tableName: string): Set<string> {\n const names = new Set<string>();\n for (const rule of rules) {\n for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n }\n return names;\n}\n","export function serializeRegExp(input: RegExp): string {\n if (!input) return \"\";\n // const fragments = input.toString().match(/\\/(.*?)\\/([a-z]*)?$/i);\n // if (fragments) {\n // if (fragments[2])\n // return input.toString();\n // return fragments[1];\n // }\n return input.toString();\n}\n\n/**\n * Get a RegExp out of a serialized string\n * @param input\n */\nexport function hydrateRegExp(input?: string): RegExp | undefined {\n if (!input) return undefined;\n const fragments = input.match(/\\/(.*?)\\/([a-z]*)?$/i);\n if (fragments) {\n return new RegExp(fragments[1], fragments[2] || \"\");\n } else {\n return new RegExp(input, \"\");\n }\n}\n\n/**\n * Is `input` something {@link hydrateRegExp} can turn into a working RegExp?\n *\n * This used to pattern-match the *shape* of a regex literal and, failing that,\n * fall back to \"does it contain any regex-ish character\" — which said yes to\n * malformed input like `/[a-z/g`. The only answer that matters to a caller is\n * whether hydration succeeds, so ask the engine instead of approximating it.\n */\nexport function isValidRegExp(input: string): boolean {\n if (!input) return false;\n try {\n return hydrateRegExp(input) !== undefined;\n } catch {\n return false;\n }\n}\n","export function flattenObject(obj: Record<string, unknown>, parentKey = \"\") {\n if (!obj) return obj;\n return Object.keys(obj).reduce((flatObj, key) => {\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (typeof obj[key] === \"object\" && obj[key] !== null) {\n if (Array.isArray(obj[key])) {\n obj[key].forEach((item: unknown, index: number) => {\n if (typeof item === \"object\" && item !== null) {\n Object.assign(flatObj, flattenObject(item as Record<string, unknown>, `${newKey}[${index}]`));\n } else {\n flatObj[`${newKey}[${index}]`] = item;\n }\n });\n } else {\n Object.assign(flatObj, flattenObject(obj[key] as Record<string, unknown>, newKey));\n }\n } else {\n flatObj[newKey] = obj[key];\n }\n\n return flatObj;\n }, {} as { [key: string]: unknown });\n}\n\n\n// map from nested property key like \"a.b.c\" to the maximum array count found in a list of objects for that array\nexport type ArrayValuesCount = Record<string, number>;\n\nexport function getArrayValuesCount(array: Record<string, unknown>[]): ArrayValuesCount {\n return array.reduce((acc: ArrayValuesCount, obj: Record<string, unknown>) => {\n Object.entries(obj).forEach(([key, value]) => {\n // proceed only if value is an array\n if (Array.isArray(value)) {\n acc[key] = Math.max(acc[key] || 0, value.length);\n }\n\n // handle nested object\n if (typeof value === \"object\" && value !== null) {\n const nested = getArrayValuesCount([value as Record<string, unknown>]);\n Object.entries(nested).forEach(([nestedKey, nestedCount]) => {\n const compoundKey = `${key}.${nestedKey}`;\n acc[compoundKey] = Math.max(acc[compoundKey] || 0, nestedCount);\n });\n }\n });\n return acc;\n }, {});\n}\n","/**\n * Returns the plural of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function plural(word: string, amount?: number): string {\n if (amount !== undefined && amount === 1) {\n return word\n }\n const plurals: { [key: string]: string } = {\n \"(quiz)$\": \"$1zes\",\n \"^(ox)$\": \"$1en\",\n \"([m|l])ouse$\": \"$1ice\",\n \"(matr|vert|ind)ix|ex$\": \"$1ices\",\n \"(x|ch|ss|sh)$\": \"$1es\",\n \"([^aeiouy]|qu)y$\": \"$1ies\",\n \"(hive)$\": \"$1s\",\n \"(?:([^f])fe|([lr])f)$\": \"$1$2ves\",\n \"(shea|lea|loa|thie)f$\": \"$1ves\",\n sis$: \"ses\",\n \"([ti])um$\": \"$1a\",\n \"(tomat|potat|ech|her|vet)o$\": \"$1oes\",\n \"(bu)s$\": \"$1ses\",\n \"(alias)$\": \"$1es\",\n \"(octop)us$\": \"$1i\",\n \"(ax|test)is$\": \"$1es\",\n \"(us)$\": \"$1es\",\n \"([^s]+)$\": \"$1s\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${w}$`, \"i\")\n const replace = irregular[w]\n if (pattern.test(word)) {\n return word.replace(pattern, replace);\n }\n }\n // check for matches using regular expressions\n for (const reg in plurals) {\n const pattern = new RegExp(reg, \"i\")\n if (pattern.test(word)) {\n return word.replace(pattern, plurals[reg])\n }\n }\n return word;\n}\n\n/**\n * Returns the singular of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function singular(word: string, amount?: number): string {\n if (amount !== undefined && amount !== 1) {\n return word;\n }\n const singulars: { [key: string]: string } = {\n \"(quiz)zes$\": \"$1\",\n \"(matr)ices$\": \"$1ix\",\n \"(vert|ind)ices$\": \"$1ex\",\n \"^(ox)en$\": \"$1\",\n \"(alias)es$\": \"$1\",\n \"(octop|vir)i$\": \"$1us\",\n \"(cris|ax|test)es$\": \"$1is\",\n \"(shoe)s$\": \"$1\",\n \"(o)es$\": \"$1\",\n \"(bus)es$\": \"$1\",\n \"([m|l])ice$\": \"$1ouse\",\n \"(x|ch|ss|sh)es$\": \"$1\",\n \"(m)ovies$\": \"$1ovie\",\n \"(s)eries$\": \"$1eries\",\n \"([^aeiouy]|qu)ies$\": \"$1y\",\n \"([lr])ves$\": \"$1f\",\n \"(tive)s$\": \"$1\",\n \"(hive)s$\": \"$1\",\n \"(li|wi|kni)ves$\": \"$1fe\",\n \"(shea|loa|lea|thie)ves$\": \"$1f\",\n \"(^analy)ses$\": \"$1sis\",\n \"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$\": \"$1$2sis\",\n \"([ti])a$\": \"$1um\",\n \"(n)ews$\": \"$1ews\",\n \"(h|bl)ouses$\": \"$1ouse\",\n \"(corpse)s$\": \"$1\",\n \"(us)es$\": \"$1\",\n s$: \"\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${irregular[w]}$`, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, w);\n }\n }\n // check for matches using regular expressions\n for (const reg in singulars) {\n const pattern = new RegExp(reg, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, singulars[reg]);\n }\n }\n return word;\n}\n","import { singular } from \"./plurals\";\nimport { toSnakeCase } from \"./strings\";\n\n/**\n * Generates a foreign key column name from a given string, typically a collection slug or name.\n * It singularizes the name, converts it to snake_case and appends '_id'.\n *\n * Singularization runs *before* snake-casing so that acronyms survive: `toSnakeCase`\n * splits on every capital, which turned \"URLs\" into \"ur_ls\" and then \"ur_l_id\".\n *\n * @param name The base name to convert to a foreign key.\n * @returns A foreign key name in the format 'singular_name_id'.\n *\n * @example\n * // returns \"user_id\"\n * generateForeignKeyName(\"users\")\n *\n * @example\n * // returns \"category_id\"\n * generateForeignKeyName(\"categories\")\n *\n * @example\n * // returns \"product_id\"\n * generateForeignKeyName(\"Product\")\n *\n */\nexport function generateForeignKeyName(name: string): string {\n return `${toSnakeCase(singularizeForKey(name))}_id`;\n}\n\n/**\n * `singular()` handles real English plurals, but its final catch-all rule strips\n * any trailing \"s\", which mangles words that only look plural. Guard the two\n * cases that produce a column name nobody would recognise:\n *\n * - a double \"s\" ending is never a plural marker (\"address\", \"class\", \"process\"),\n * so stripping it yields \"addres\";\n * - a name that singularizes to nothing (the literal \"s\") would yield \"_id\".\n */\nfunction singularizeForKey(name: string): string {\n if (/ss$/i.test(name)) return name;\n const result = singular(name);\n return result.length > 0 ? result : name;\n}\n\n/**\n * What `generateForeignKeyName` returned before it learned to singularize:\n * snake-case the name, then chop one trailing \"s\".\n *\n * This is here to be *detected*, never to be generated. A database provisioned\n * under the old rule carries `categorie_id`, `addresse_id`, `children_id` or\n * `ur_l_id` where the current rule expects `category_id`, `address_id`,\n * `child_id` and `url_id` — and the boot-time schema ensure is additive, so it\n * would create the new column empty beside the populated old one and leave the\n * relation reading nothing. No error, no missing table: the failure is silent,\n * which is the only reason this function still exists.\n *\n * `ensureCollectionSchema` calls it to recognise that shape and say so.\n * Returns the same string as `generateForeignKeyName` for every regular plural,\n * so a caller can compare the two and act only when they differ.\n */\nexport function legacyForeignKeyName(name: string): string {\n const snake = toSnakeCase(name);\n return `${snake.endsWith(\"s\") ? snake.slice(0, -1) : snake}_id`;\n}\n","\n\nexport function isDefaultFieldConfigId(id: string): boolean {\n return [\"text_field\",\n \"multiline\",\n \"markdown\",\n \"url\",\n \"email\",\n \"switch\",\n \"select\",\n \"multi_select\",\n \"number_input\",\n \"number_select\",\n \"multi_number_select\",\n \"file_upload\",\n \"multi_file_upload\",\n \"reference\",\n \"multi_references\",\n \"relation\",\n \"date_time\",\n \"group\",\n \"key_value\",\n \"repeat\",\n \"custom_array\",\n \"block\"\n ].includes(id);\n}\n"],"mappings":";;;AAAA,IAAM,gBAAgB;AAEtB,IAAa,eAAe,QAAiB;CACzC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,mBAAmB,IAAI,MAAM,aAAa;CAChD,IAAI,CAAC,kBAAkB,OAAO;CAC9B,OAAO,iBACF,KAAI,MAAK,EAAE,YAAY,CAAC,CAAC,CACzB,KAAK,GAAG;A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I,MAAM,MAAM,GAAG,EAAE,IAAI,MAAM;AAC/D;;;AC9DA,SAAgB,uBAAuB,IAAqB;CACxD,OAAO;EAAC;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,EAAE;AACjB"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/strings.ts","../src/objects.ts","../src/arrays.ts","../src/dates.ts","../src/storage.ts","../src/hash.ts","../src/sha1.ts","../src/policy-names.ts","../src/regexp.ts","../src/flatten_object.ts","../src/plurals.ts","../src/names.ts","../src/fields.ts"],"sourcesContent":["const tokenizeRegex = /[A-Z]{2,}(?=[A-Z][a-z]|\\b)|[A-Z]?[a-z]+|[0-9]+(?:[a-z](?![a-z]))?|[A-Z]/g;\n\nexport const toKebabCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(tokenizeRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"-\");\n};\n\nconst snakeCaseRegex = tokenizeRegex;\n\nexport const toSnakeCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(snakeCaseRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"_\");\n};\n\nexport function camelCase(str: string): string {\n if (!str) return \"\";\n if (str.length === 1) return str.toLowerCase();\n\n // Split by hyphens, underscores, or spaces and filter out empty strings\n const parts = str.split(/[-_ ]+/).filter(Boolean);\n\n if (parts.length === 0) return \"\";\n\n // Start with first part in lowercase\n return parts[0].toLowerCase() +\n // Transform remaining parts to have first letter uppercase\n parts.slice(1)\n .map(part => part.charAt(0).toUpperCase() + part.substring(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * A random base-36 string of exactly `strLength` characters.\n *\n * Not `Math.random().toString(36).slice(2, 2 + strLength)`: that has no\n * guaranteed length. Base-36 of a double drops trailing zeros, so the source\n * string is short about once in 36 calls and the slice quietly returns fewer\n * characters than asked for — `randomString(10)` returning 9. These values\n * prefix uploaded filenames to keep them apart, so a short one is a likelier\n * collision, and it fails at the rate that makes a test look flaky.\n */\nexport function randomString(strLength = 5) {\n const alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n let result = \"\";\n for (let i = 0; i < strLength; i++) {\n result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));\n }\n return result;\n}\n\nexport function randomColor() {\n return Math.floor(Math.random() * 16777215).toString(16);\n}\n\nexport function slugify(text?: string, separator = \"_\", lowercase = true) {\n if (!text) return \"\";\n const from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\"\n const to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\n for (let i = 0, l = from.length; i < l; i++) {\n text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n }\n\n text = text\n .toString() // Cast to string\n .trim() // Remove whitespace from both sides of a string\n .replace(/^\\s+|\\s+$/g, \"\")\n .replace(/\\s+/g, separator) // Replace spaces with separator\n .replace(/&/g, separator) // Replace & with separator\n .replace(/[^\\w\\\\-]+/g, \"\") // Remove all non-word chars\n .replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"),\n separator); // Replace multiple separators with single one\n\n return lowercase\n ? text.toLowerCase() // Convert the string to lowercase letters\n : text;\n}\n\nexport function unslugify(slug?: string): string {\n if (!slug) return \"\";\n if (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) {\n const result = slug.replace(/[-_]/g, \" \");\n return result.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substring(1);\n }).trim();\n } else {\n return slug.trim();\n }\n}\n\nexport function prettifyIdentifier(input: string) {\n if (!input) return \"\";\n\n let text = input;\n\n // 1. Handle camelCase and Acronyms\n // Group 1 ($1 $2): Lowercase followed by Uppercase (e.g., imageURL -> image URL)\n // Group 2 ($3 $4): Uppercase followed by Uppercase+lowercase (e.g., XMLParser -> XML Parser)\n text = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\n // 2. Replace hyphens/underscores with spaces\n text = text.replace(/[_-]+/g, \" \");\n\n // 3. Capitalize first letter of each word (Title Case)\n const s = text\n .trim()\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n return s;\n}\n","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n\n/** @private is the value an empty array? */\nexport const isEmptyArray = (value?: unknown) =>\n Array.isArray(value) && value.length === 0;\n\n/** @private is the given object a Function? */\nexport const isFunction = (obj: unknown): obj is (...args: unknown[]) => unknown =>\n typeof obj === \"function\";\n\n/** @private is the given object an integer? */\nexport const isInteger = (obj: unknown): boolean =>\n String(Math.floor(Number(obj))) === String(obj);\n\n/** @private is the given object a NaN? */\n\nexport const isNaN = (obj: unknown): boolean => obj !== obj;\n\n/**\n * Segments that reach the prototype chain rather than a property of the object.\n *\n * The twin of this function in `@rebasepro/forms` could be made to write onto\n * `Object.prototype` through a path of `__proto__.x`. This copy survives the\n * write by accident — its `clone` always spreads into a fresh object, while the\n * form engine's has a \"preserve class instances\" branch that hands back\n * `Object.prototype` itself — but `getIn` still *reads* through the chain, and\n * handing back `Object.prototype` is how a polluted value is read out again.\n *\n * Closed on both sides here, so the two implementations agree.\n */\nconst UNSAFE_PATH_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Whether any segment of this path would traverse the prototype chain. */\nexport function pathTraversesPrototype(path: string | string[]): boolean {\n return toPath(path).some(segment => UNSAFE_PATH_SEGMENTS.has(segment));\n}\n\n/**\n * Whether writing this single key with `obj[key] = …` would reach the prototype\n * chain instead of creating a property.\n *\n * The single-key counterpart of {@link pathTraversesPrototype}, for the many\n * places that copy an object one key at a time. `JSON.parse` creates\n * `__proto__` as an *own* property, so it survives `hasOwnProperty` — and then\n * `target[key] = value` invokes the setter and replaces the target's prototype.\n */\nexport function isPrototypePollutingKey(key: string): boolean {\n return UNSAFE_PATH_SEGMENTS.has(key);\n}\n\n/**\n * Deeply get a value from an object via its path.\n */\nexport function getIn(\n obj: Record<string, unknown> | unknown[] | unknown,\n key: string | string[],\n def?: unknown,\n p = 0\n) {\n if (pathTraversesPrototype(key)) return def;\n\n const path = toPath(key);\n while (obj && p < path.length) {\n obj = (obj as Record<string, unknown>)[path[p++]];\n }\n\n // check if path is not in the end\n if (p !== path.length && !obj) {\n return def;\n }\n\n return obj === undefined ? def : obj;\n}\n\nexport function setIn<T>(obj: T, path: string, value: unknown): T {\n // See `pathTraversesPrototype`. This copy's `clone` happens to contain the\n // write, but relying on that is relying on an implementation detail of a\n // different function.\n if (pathTraversesPrototype(path)) return obj;\n\n const res = clone(obj) as Record<string, unknown>;\n let resVal: Record<string, unknown> = res;\n let i = 0;\n const pathArray = toPath(path);\n\n for (; i < pathArray.length - 1; i++) {\n const currentPath: string = pathArray[i];\n const currentObj = getIn(obj as Record<string, unknown>, pathArray.slice(0, i + 1));\n\n if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {\n resVal = resVal[currentPath] = clone(currentObj) as Record<string, unknown>;\n } else {\n const nextPath: string = pathArray[i + 1];\n resVal = resVal[currentPath] =\n (isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}) as Record<string, unknown>;\n }\n }\n\n // Return original object if new value is the same as current\n if ((i === 0 ? obj as Record<string, unknown> : resVal)[pathArray[i]] === value) {\n return obj;\n }\n\n if (value === undefined) {\n delete resVal[pathArray[i]];\n } else {\n resVal[pathArray[i]] = value;\n }\n\n // If the path array has a single element, the loop did not run.\n // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.\n if (i === 0 && value === undefined) {\n delete res[pathArray[i]];\n }\n\n return res as T;\n}\n\nexport function clone<T>(value: T): T {\n if (Array.isArray(value)) {\n return [...value] as T;\n } else if (typeof value === \"object\" && value !== null) {\n return { ...value } as T;\n } else {\n return value; // This is for primitive types which do not need cloning.\n }\n}\n\n/**\n * Deep clone a value, preserving function references and class instances.\n * Unlike structuredClone, this handles objects that contain functions\n * (e.g. CollectionConfig with target(), childCollections(), callbacks).\n */\nexport function deepClone<T>(value: T): T {\n if (value === null || value === undefined) return value;\n if (typeof value === \"function\") return value;\n if (typeof value !== \"object\") return value;\n\n if (Array.isArray(value)) {\n return value.map(item => deepClone(item)) as T;\n }\n\n // Preserve class instances (Date, GeoPoint, etc.) — don't recurse\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = deepClone((value as Record<string, unknown>)[key]);\n }\n return result as T;\n}\n\nfunction toPath(value: string | string[]) {\n if (Array.isArray(value)) return value; // Already in path array form.\n // Replace brackets with dots, remove leading/trailing dots, then split by dot.\n return value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\n\n\nexport const pick: <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => Partial<T> = <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => ({\n ...args.reduce<Record<string, unknown>>((res, key) => ({\n ...res,\n [key as string]: obj[key as string]\n }), {})\n}) as Partial<T>;\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === \"object\" && !Array.isArray(item);\n}\n\nexport function isPlainObject(obj: unknown): obj is Record<string, unknown> {\n // 1. Rule out non-objects, null, and arrays\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n return false;\n }\n\n // 2. Get the object's direct prototype\n const proto = Object.getPrototypeOf(obj);\n\n // 3. A plain object's direct prototype is Object.prototype\n return proto === Object.prototype;\n}\n\nexport function mergeDeep<T extends object, U extends object>(\n target: T,\n source: U,\n ignoreUndefined = false\n): T & U {\n // If target is not a true object (e.g., null, array, primitive), return target itself.\n if (!isObject(target)) {\n return target as T & U;\n }\n\n // Create a shallow copy of the target to avoid modifying the original object.\n const output = { ...target };\n\n // If source is not a true object, there's nothing to merge from it.\n // Return the shallow copy of target.\n if (!isObject(source)) {\n return output as T & U;\n }\n\n // Iterate over keys in the source object.\n for (const key in source) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n continue;\n }\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const outputValue = (output as Record<string, unknown>)[key]; // Current value in our merged object (originating from target)\n\n // Skip if source value is undefined and ignoreUndefined is true.\n // This handles both not adding new undefined properties and not overwriting existing properties with undefined.\n if (ignoreUndefined && sourceValue === undefined) {\n continue;\n }\n\n if (sourceValue instanceof Date) {\n // If source value is a Date, create a new Date instance.\n (output as Record<string, unknown>)[key] = new Date(sourceValue.getTime());\n } else if (Array.isArray(sourceValue)) {\n if (Array.isArray(outputValue)) {\n // If the array contains primitives or class instances (non-plain objects),\n // overwrite the array entirely instead of doing element-wise merging.\n const hasPlainObjects = sourceValue.some(isPlainObject) || outputValue.some(isPlainObject);\n if (!hasPlainObjects) {\n (output as Record<string, unknown>)[key] = [...sourceValue];\n } else {\n const newArray = [];\n const maxLength = Math.max(outputValue.length, sourceValue.length);\n for (let i = 0; i < maxLength; i++) {\n const sourceItem = sourceValue[i];\n const targetItem = outputValue[i];\n\n if (i >= sourceValue.length) { // source is shorter\n newArray[i] = targetItem;\n } else if (i >= outputValue.length) { // target is shorter\n newArray[i] = sourceItem;\n } else if (sourceItem === null) {\n newArray[i] = targetItem;\n } else if (isPlainObject(sourceItem) && isPlainObject(targetItem)) {\n // Only recursively merge plain objects, preserve class instances\n newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n } else {\n // For class instances and primitives, use source directly\n newArray[i] = sourceItem;\n }\n }\n (output as Record<string, unknown>)[key] = newArray;\n }\n } else {\n // If output's value (from target) is not an array,\n // overwrite with a shallow copy of the source array.\n (output as Record<string, unknown>)[key] = [...sourceValue];\n }\n } else if (isPlainObject(sourceValue)) {\n // If source value is a plain object (not a class instance like EntityReference, GeoPoint, etc.):\n if (isPlainObject(outputValue)) {\n // If the corresponding value in output (from target) is also a plain object, recurse.\n // Ensure the ignoreUndefined flag is passed down.\n (output as Record<string, unknown>)[key] = mergeDeep(outputValue as Record<string, unknown>, sourceValue, ignoreUndefined);\n } else {\n // If output's value (from target) is not a plain object (e.g., null, primitive, class instance, or key didn't exist in original target),\n // overwrite with the source object.\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isObject(sourceValue)) {\n // If source value is a class instance (not a plain object), use it directly to preserve prototype\n (output as Record<string, unknown>)[key] = sourceValue;\n } else {\n // If source value is a primitive, null, or undefined (and not ignored).\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n }\n }\n\n return output as T & U;\n}\n\nexport function getValueInPath(o: object | undefined, path: string): unknown {\n if (!o) return undefined;\n if (typeof o === \"object\") {\n if (path in o) {\n return (o as Record<string, unknown>)[path];\n }\n if (path.includes(\".\") || path.includes(\"[\")) {\n let pathSegments = path.split(/[.[]/);\n if (path.includes(\"[\")) {\n pathSegments = pathSegments.map(segment => segment.replace(\"]\", \"\"));\n }\n const firstSegment = pathSegments[0];\n const isArrayAndIndexExists = Array.isArray((o as Record<string, unknown>)[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n const nextObject = isArrayAndIndexExists\n ? ((o as Record<string, unknown>)[firstSegment] as unknown[])[parseInt(pathSegments[1])]\n : (o as Record<string, unknown>)[firstSegment];\n\n const nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n if (nextPath === \"\")\n return nextObject;\n return getValueInPath(nextObject as object | undefined, nextPath);\n }\n }\n return undefined;\n}\n\nexport function removeInPath(o: object, path: string): object | undefined {\n const res = clone(o) as Record<string, unknown>;\n let current = res;\n const parts = path.split(\".\");\n const last = parts.pop();\n for (const part of parts) {\n if (part in current && current[part] !== null && typeof current[part] === \"object\") {\n current[part] = clone(current[part]) as Record<string, unknown>;\n current = current[part] as Record<string, unknown>;\n } else {\n return res;\n }\n }\n if (last && current && typeof current === \"object\") {\n delete current[last];\n }\n return res;\n}\n\nexport function removeFunctions(o: unknown): unknown {\n if (o === undefined) return undefined;\n if (o === null) return null;\n if (typeof o === \"object\") {\n // Handle arrays first - drop function elements, then recurse.\n // Only object *properties* used to be filtered, so a function sitting\n // directly in an array survived — and the callers strip functions\n // precisely because a function survives no deep comparison.\n if (Array.isArray(o)) {\n return o\n .filter(v => typeof v !== \"function\")\n .map(v => removeFunctions(v));\n }\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(o)) {\n return o;\n }\n return Object.entries(o)\n .filter(([_, value]) => typeof value !== \"function\")\n .reduce<Record<string, unknown>>((acc, [key, value]) => {\n acc[key] = removeFunctions(value);\n return acc;\n }, {});\n }\n return o;\n}\n\nexport function getHashValue<T>(v: T): string | null {\n if (!v) return null;\n if (typeof v === \"object\" && v !== null) {\n if (\"id\" in v)\n return String((v as Record<string, unknown>).id);\n else if (v instanceof Date)\n return v.toLocaleString();\n else if (v instanceof GeoPoint)\n return hash(v as Record<string, unknown>);\n }\n return hash(v as object, { ignoreUnknown: true });\n}\n\nexport function removeUndefined(value: unknown, removeEmptyStrings?: boolean): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeUndefined(v, removeEmptyStrings));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n Object.keys(value).forEach((key) => {\n if (!isEmptyObject(value as object)) {\n const childRes = removeUndefined((value as Record<string, unknown>)[key], removeEmptyStrings);\n const isString = typeof childRes === \"string\";\n const shouldKeepIfString = !removeEmptyStrings || (removeEmptyStrings && !isString) || (removeEmptyStrings && isString && childRes !== \"\");\n if (childRes !== undefined && !isEmptyObject(childRes as object) && shouldKeepIfString)\n res[key] = childRes;\n }\n });\n return res;\n }\n return value;\n}\n\nexport function removeNulls(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeNulls(v));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n const obj = value as Record<string, unknown>;\n Object.keys(obj).forEach((key) => {\n if (obj[key] !== null)\n res[key] = removeNulls(obj[key]);\n });\n return res;\n }\n return value;\n}\n\nexport function isEmptyObject(obj: object) {\n return obj &&\n Object.getPrototypeOf(obj) === Object.prototype &&\n Object.keys(obj).length === 0\n}\n\nexport function removePropsIfExisting(source: Record<string, unknown> | unknown[], comparison: Record<string, unknown> | unknown[]) {\n const isObject = (val: unknown): val is Record<string, unknown> => typeof val === \"object\" && val !== null;\n const isArray = (val: unknown): val is unknown[] => Array.isArray(val);\n\n if (!isObject(source) || !isObject(comparison)) {\n return source;\n }\n\n const res = isArray(source) ? [...source] : { ...source };\n\n if (isArray(res)) {\n for (let i = res.length - 1; i >= 0; i--) {\n if (res[i] === comparison[i]) {\n res.splice(i, 1);\n } else if (isObject(res[i]) && isObject(comparison[i])) {\n res[i] = removePropsIfExisting(res[i] as unknown as Record<string, unknown>, (comparison as unknown as unknown[])[i] as Record<string, unknown>);\n }\n }\n } else {\n Object.keys(comparison).forEach(key => {\n if (key in res) {\n if (isObject(res[key]) && isObject(comparison[key])) {\n res[key] = removePropsIfExisting(res[key], comparison[key]);\n } else if (res[key] === comparison[key]) {\n delete res[key];\n }\n }\n });\n }\n\n return res;\n}\n","/**\n * Normalise a value that may be a single item or a list into a list.\n *\n * Only `null`/`undefined` mean \"nothing\". A truthiness check here silently\n * swallowed legitimate values — `toArray(0)`, `toArray(false)` and `toArray(\"\")`\n * all came back empty, so a caller normalising a single falsy item lost it.\n */\nexport function toArray<T>(input?: T | T[] | null): T[] {\n if (Array.isArray(input)) return input;\n if (input === undefined || input === null) return [];\n return [input];\n}\n","export const defaultDateFormat = \"MMMM dd, yyyy, HH:mm:ss\";\n\n/** Seven days, the distance past which a relative phrase stops being useful. */\nconst DEFAULT_MAX_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type FormatRelativeTimeOptions = {\n /**\n * The instant the distance is measured from. Defaults to the current time.\n * Pass it explicitly to make a caller testable without faking the clock.\n */\n now?: Date | number;\n /**\n * How far a value may sit from {@link now} and still be described\n * relatively. Beyond it the function returns `null` and the caller renders\n * an absolute date instead. Defaults to seven days.\n */\n maxMs?: number;\n};\n\nfunction toTime(value: Date | string | number | null | undefined): number | null {\n if (value === null || value === undefined || value === \"\") return null;\n const time = value instanceof Date ? value.getTime() : new Date(value).getTime();\n return Number.isNaN(time) ? null : time;\n}\n\n/**\n * Describes an instant relative to another one — \"5m ago\", \"in 3h\".\n *\n * The direction is part of the answer. Every hand-rolled version of this in the\n * codebase computed `now - then` and then tested only the positive side, so a\n * timestamp in the future fell through to whichever branch happened to be\n * first: a date scheduled for next month read \"Just now\", and one a couple of\n * hours out read \"-1d ago\". Both are dates a CMS holds all the time — a publish\n * date, a due date, an expiry — and neither shape can occur here, because the\n * distance is measured with {@link Math.abs} and the tense is chosen from the\n * sign rather than assumed.\n *\n * Returns `null` when the value is unreadable, or when it is further than\n * {@link FormatRelativeTimeOptions.maxMs} away in either direction. `null` is\n * \"say it another way\", not an error: the caller owns the absolute format, and\n * the locale and precision that go with it.\n */\nexport function formatRelativeTime(\n value: Date | string | number | null | undefined,\n options: FormatRelativeTimeOptions = {}\n): string | null {\n const then = toTime(value);\n if (then === null) return null;\n\n const now = options.now instanceof Date ? options.now.getTime() : (options.now ?? Date.now());\n const maxMs = options.maxMs ?? DEFAULT_MAX_MS;\n\n // Positive is the past, which is the only case the callers used to handle.\n const delta = now - then;\n const distance = Math.abs(delta);\n if (distance > maxMs) return null;\n\n const future = delta < 0;\n\n const minutes = Math.floor(distance / 60_000);\n if (minutes < 1) return future ? \"in a moment\" : \"just now\";\n if (minutes < 60) return future ? `in ${minutes}m` : `${minutes}m ago`;\n\n const hours = Math.floor(distance / 3_600_000);\n if (hours < 24) return future ? `in ${hours}h` : `${hours}h ago`;\n\n const days = Math.floor(distance / 86_400_000);\n return future ? `in ${days}d` : `${days}d ago`;\n}\n","/**\n * Reading and writing the small amounts of JSON a UI keeps between sessions —\n * open tabs, column widths, collapsed groups, recent searches.\n *\n * Every one of those reads is a read of *aged* state: it was written by whatever\n * version of the app the user last ran, and it is parsed by this one. The same\n * class the database upgrade path is careful about, in a place nothing migrates.\n *\n * A hand-rolled `JSON.parse(localStorage.getItem(key)!)` has four ways to throw\n * and no way to recover from any of them:\n *\n * - `localStorage` itself throws on access when storage is disabled (Safari\n * private browsing, blocked third-party cookies) or absent (SSR, Node).\n * - the stored text is not JSON, because a write was interrupted or a user\n * edited it.\n * - the stored text is valid JSON of the *wrong shape*, because an older\n * release wrote an object where this one expects an array. `parsed.map` is\n * then not a function.\n * - `setItem` throws `QuotaExceededError` once the origin's few megabytes are\n * full, which a view that persists query text on every edit will reach.\n *\n * When any of those happens inside a `useState` initializer it throws during\n * render, and the bad value is still there on reload, so the view is bricked\n * until someone opens devtools. These helpers turn all four into the fallback.\n */\n\nexport interface WebStorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/**\n * The ambient `localStorage`, or `null` where there is not one. Access itself\n * is what throws when storage is disabled, so even reaching for it is guarded.\n */\nexport function getWebStorage(): WebStorageLike | null {\n try {\n const storage = (globalThis as { localStorage?: WebStorageLike }).localStorage;\n return storage ?? null;\n } catch {\n return null;\n }\n}\n\nexport type ReadStoredJsonOptions<T> = {\n /** Returned whenever the stored value is missing, unreadable or rejected. */\n fallback: T;\n /**\n * Whether the parsed value is the shape this caller expects. Pass it\n * whenever the fallback is an array or a keyed object: valid JSON of the\n * wrong shape is the failure an upgrade actually produces, and it survives\n * `JSON.parse` untouched to fail later at the first `.map` or `.find`.\n */\n accept?: (value: unknown) => boolean;\n /** Defaults to the ambient `localStorage`. */\n storage?: WebStorageLike | null;\n};\n\n/**\n * Reads and parses a JSON value a previous session stored, falling back rather\n * than throwing. See the module comment for what it is falling back from.\n *\n * A rejected value is deliberately left in place rather than cleared: this\n * version not understanding it is not evidence that nothing does.\n */\nexport function readStoredJson<T>(key: string, options: ReadStoredJsonOptions<T>): T {\n const storage = options.storage === undefined ? getWebStorage() : options.storage;\n if (!storage) return options.fallback;\n\n let raw: string | null;\n try {\n raw = storage.getItem(key);\n } catch {\n return options.fallback;\n }\n if (raw === null || raw === \"\") return options.fallback;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return options.fallback;\n }\n\n if (options.accept && !options.accept(parsed)) return options.fallback;\n return parsed as T;\n}\n\n/**\n * Persists a value as JSON. Returns whether it was stored, so a caller that\n * cares can say so — most do not, and for them the point is simply that a full\n * quota does not throw out of the effect doing the writing.\n */\nexport function writeStoredJson(\n key: string,\n value: unknown,\n options: { storage?: WebStorageLike | null } = {}\n): boolean {\n const storage = options.storage === undefined ? getWebStorage() : options.storage;\n if (!storage) return false;\n try {\n storage.setItem(key, JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Persists an already-serialised string, for the values kept as plain text\n * rather than JSON — a selected id, a pane size.\n */\nexport function writeStoredString(\n key: string,\n value: string,\n options: { storage?: WebStorageLike | null } = {}\n): boolean {\n const storage = options.storage === undefined ? getWebStorage() : options.storage;\n if (!storage) return false;\n try {\n storage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Reads a plain string, absent rather than throwing where there is no storage. */\nexport function readStoredString(\n key: string,\n options: { storage?: WebStorageLike | null } = {}\n): string | null {\n const storage = options.storage === undefined ? getWebStorage() : options.storage;\n if (!storage) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/** `accept` for a caller whose fallback is an array. */\nexport const isArrayValue = (value: unknown): boolean => Array.isArray(value);\n\n/** `accept` for a caller whose fallback is a keyed object — and not an array. */\nexport const isRecordValue = (value: unknown): boolean =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n","export function hashString(str: string): number {\n if (!str) return 0;\n let hash = 0;\n let i;\n let chr;\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return Math.abs(hash);\n}\n","/**\n * Minimal SHA-1 implementation that runs in both Node and the browser.\n *\n * This exists because generated Postgres policy names embed a SHA-1 digest of\n * the security rule. The DDL generator runs on the server (where `node:crypto`\n * is available) but the Studio has to derive the same names in the browser to\n * tell a policy it generated apart from one it did not. `node:crypto` cannot be\n * bundled for the browser, so the shared derivation needs a portable digest.\n *\n * SHA-1 is used purely to name things deterministically — never for security.\n * The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n * which `sha1.test.ts` pins against `node:crypto` directly.\n */\n\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value: number, n: number): number {\n return (value << n) | (value >>> (32 - n));\n}\n\n/**\n * SHA-1 digest of a string, hex-encoded.\n *\n * The input is encoded as UTF-8, matching Node's default handling of strings\n * passed to `hash.update(str)`.\n */\nexport function sha1Hex(input: string): string {\n const bytes: number[] = Array.from(new TextEncoder().encode(input));\n const bitLength = bytes.length * 8;\n\n // Padding: 0x80, then zeroes up to 56 bytes mod 64, then the length as a\n // 64-bit big-endian integer.\n bytes.push(0x80);\n while (bytes.length % 64 !== 56) bytes.push(0);\n\n const hi = Math.floor(bitLength / 0x100000000);\n const lo = bitLength >>> 0;\n bytes.push((hi >>> 24) & 0xff, (hi >>> 16) & 0xff, (hi >>> 8) & 0xff, hi & 0xff);\n bytes.push((lo >>> 24) & 0xff, (lo >>> 16) & 0xff, (lo >>> 8) & 0xff, lo & 0xff);\n\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Array<number>(80);\n\n for (let offset = 0; offset < bytes.length; offset += 64) {\n for (let i = 0; i < 16; i++) {\n const j = offset + i * 4;\n w[i] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) | 0;\n }\n for (let i = 16; i < 80; i++) {\n w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n for (let i = 0; i < 80; i++) {\n let f: number;\n let k: number;\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (rotl(a, 5) + f + e + k + w[i]) | 0;\n e = d;\n d = c;\n c = rotl(b, 30);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n return [h0, h1, h2, h3, h4]\n .map(word => (word >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n","import type { SecurityOperation, SecurityRule } from \"@rebasepro/types\";\nimport { sha1Hex } from \"./sha1\";\n\n/**\n * Naming of the Postgres policies generated from a collection's security rules.\n *\n * A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n * the hash covers the rule's semantics. The Studio needs the same names to tell\n * \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n * without them it treats generated policies as foreign and offers to import\n * them back into the codebase they came from.\n *\n * This is the single definition of that naming. The DDL and Drizzle generators\n * both derive names from here, so a change cannot silently rename every policy\n * in every deployed database while the UI keeps matching the old ones.\n */\n\n/** Stable digest of the parts of a rule that determine what the policy does. */\nexport function getPolicyNameHash(rule: SecurityRule): string {\n const data = JSON.stringify({\n a: rule.access,\n m: rule.mode,\n op: rule.operation,\n ops: rule.operations?.slice().sort(),\n own: rule.ownerField,\n rol: rule.roles?.slice().sort(),\n pg: rule.pgRoles?.slice().sort(),\n u: rule.using,\n w: rule.withCheck,\n c: rule.condition,\n ch: rule.check\n });\n return sha1Hex(data).substring(0, 7);\n}\n\n/** The operations a rule expands to — `operations` wins over `operation`. */\nexport function getPolicyOperations(rule: SecurityRule): readonly SecurityOperation[] {\n return rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n}\n\n/**\n * Every Postgres policy name a single rule compiles to — one per operation.\n *\n * @param rule The security rule as written in the collection config.\n * @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n */\nexport function getPolicyNamesForRule(rule: SecurityRule, tableName: string): string[] {\n const ops = getPolicyOperations(rule);\n const ruleHash = getPolicyNameHash(rule);\n\n return ops.map((op, opIdx) => rule.name\n ? (ops.length > 1 ? `${rule.name}_${op}` : rule.name)\n : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n\n/** Every policy name a set of rules compiles to, for membership checks. */\nexport function getPolicyNamesForRules(rules: SecurityRule[], tableName: string): Set<string> {\n const names = new Set<string>();\n for (const rule of rules) {\n for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n }\n return names;\n}\n","export function serializeRegExp(input: RegExp): string {\n if (!input) return \"\";\n // const fragments = input.toString().match(/\\/(.*?)\\/([a-z]*)?$/i);\n // if (fragments) {\n // if (fragments[2])\n // return input.toString();\n // return fragments[1];\n // }\n return input.toString();\n}\n\n/**\n * Get a RegExp out of a serialized string\n * @param input\n */\nexport function hydrateRegExp(input?: string): RegExp | undefined {\n if (!input) return undefined;\n const fragments = input.match(/\\/(.*?)\\/([a-z]*)?$/i);\n if (fragments) {\n return new RegExp(fragments[1], fragments[2] || \"\");\n } else {\n return new RegExp(input, \"\");\n }\n}\n\n/**\n * Is `input` something {@link hydrateRegExp} can turn into a working RegExp?\n *\n * This used to pattern-match the *shape* of a regex literal and, failing that,\n * fall back to \"does it contain any regex-ish character\" — which said yes to\n * malformed input like `/[a-z/g`. The only answer that matters to a caller is\n * whether hydration succeeds, so ask the engine instead of approximating it.\n */\nexport function isValidRegExp(input: string): boolean {\n if (!input) return false;\n try {\n return hydrateRegExp(input) !== undefined;\n } catch {\n return false;\n }\n}\n","export function flattenObject(obj: Record<string, unknown>, parentKey = \"\") {\n if (!obj) return obj;\n return Object.keys(obj).reduce((flatObj, key) => {\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (typeof obj[key] === \"object\" && obj[key] !== null) {\n if (Array.isArray(obj[key])) {\n obj[key].forEach((item: unknown, index: number) => {\n if (typeof item === \"object\" && item !== null) {\n Object.assign(flatObj, flattenObject(item as Record<string, unknown>, `${newKey}[${index}]`));\n } else {\n flatObj[`${newKey}[${index}]`] = item;\n }\n });\n } else {\n Object.assign(flatObj, flattenObject(obj[key] as Record<string, unknown>, newKey));\n }\n } else {\n flatObj[newKey] = obj[key];\n }\n\n return flatObj;\n }, {} as { [key: string]: unknown });\n}\n\n\n// map from nested property key like \"a.b.c\" to the maximum array count found in a list of objects for that array\nexport type ArrayValuesCount = Record<string, number>;\n\nexport function getArrayValuesCount(array: Record<string, unknown>[]): ArrayValuesCount {\n return array.reduce((acc: ArrayValuesCount, obj: Record<string, unknown>) => {\n Object.entries(obj).forEach(([key, value]) => {\n // proceed only if value is an array\n if (Array.isArray(value)) {\n acc[key] = Math.max(acc[key] || 0, value.length);\n }\n\n // handle nested object\n if (typeof value === \"object\" && value !== null) {\n const nested = getArrayValuesCount([value as Record<string, unknown>]);\n Object.entries(nested).forEach(([nestedKey, nestedCount]) => {\n const compoundKey = `${key}.${nestedKey}`;\n acc[compoundKey] = Math.max(acc[compoundKey] || 0, nestedCount);\n });\n }\n });\n return acc;\n }, {});\n}\n","/**\n * Returns the plural of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function plural(word: string, amount?: number): string {\n if (amount !== undefined && amount === 1) {\n return word\n }\n const plurals: { [key: string]: string } = {\n \"(quiz)$\": \"$1zes\",\n \"^(ox)$\": \"$1en\",\n \"([m|l])ouse$\": \"$1ice\",\n \"(matr|vert|ind)ix|ex$\": \"$1ices\",\n \"(x|ch|ss|sh)$\": \"$1es\",\n \"([^aeiouy]|qu)y$\": \"$1ies\",\n \"(hive)$\": \"$1s\",\n \"(?:([^f])fe|([lr])f)$\": \"$1$2ves\",\n \"(shea|lea|loa|thie)f$\": \"$1ves\",\n sis$: \"ses\",\n \"([ti])um$\": \"$1a\",\n \"(tomat|potat|ech|her|vet)o$\": \"$1oes\",\n \"(bu)s$\": \"$1ses\",\n \"(alias)$\": \"$1es\",\n \"(octop)us$\": \"$1i\",\n \"(ax|test)is$\": \"$1es\",\n \"(us)$\": \"$1es\",\n \"([^s]+)$\": \"$1s\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${w}$`, \"i\")\n const replace = irregular[w]\n if (pattern.test(word)) {\n return word.replace(pattern, replace);\n }\n }\n // check for matches using regular expressions\n for (const reg in plurals) {\n const pattern = new RegExp(reg, \"i\")\n if (pattern.test(word)) {\n return word.replace(pattern, plurals[reg])\n }\n }\n return word;\n}\n\n/**\n * Returns the singular of an English word.\n *\n * @param {string} word\n * @param {number} [amount]\n * @returns {string}\n */\nexport function singular(word: string, amount?: number): string {\n if (amount !== undefined && amount !== 1) {\n return word;\n }\n const singulars: { [key: string]: string } = {\n \"(quiz)zes$\": \"$1\",\n \"(matr)ices$\": \"$1ix\",\n \"(vert|ind)ices$\": \"$1ex\",\n \"^(ox)en$\": \"$1\",\n \"(alias)es$\": \"$1\",\n \"(octop|vir)i$\": \"$1us\",\n \"(cris|ax|test)es$\": \"$1is\",\n \"(shoe)s$\": \"$1\",\n \"(o)es$\": \"$1\",\n \"(bus)es$\": \"$1\",\n \"([m|l])ice$\": \"$1ouse\",\n \"(x|ch|ss|sh)es$\": \"$1\",\n \"(m)ovies$\": \"$1ovie\",\n \"(s)eries$\": \"$1eries\",\n \"([^aeiouy]|qu)ies$\": \"$1y\",\n \"([lr])ves$\": \"$1f\",\n \"(tive)s$\": \"$1\",\n \"(hive)s$\": \"$1\",\n \"(li|wi|kni)ves$\": \"$1fe\",\n \"(shea|loa|lea|thie)ves$\": \"$1f\",\n \"(^analy)ses$\": \"$1sis\",\n \"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$\": \"$1$2sis\",\n \"([ti])a$\": \"$1um\",\n \"(n)ews$\": \"$1ews\",\n \"(h|bl)ouses$\": \"$1ouse\",\n \"(corpse)s$\": \"$1\",\n \"(us)es$\": \"$1\",\n s$: \"\"\n }\n const irregular: { [key: string]: string } = {\n move: \"moves\",\n foot: \"feet\",\n goose: \"geese\",\n sex: \"sexes\",\n child: \"children\",\n man: \"men\",\n tooth: \"teeth\",\n person: \"people\"\n }\n const uncountable: string[] = [\n \"sheep\",\n \"fish\",\n \"deer\",\n \"moose\",\n \"series\",\n \"species\",\n \"money\",\n \"rice\",\n \"information\",\n \"equipment\",\n \"bison\",\n \"cod\",\n \"offspring\",\n \"pike\",\n \"salmon\",\n \"shrimp\",\n \"swine\",\n \"trout\",\n \"aircraft\",\n \"hovercraft\",\n \"spacecraft\",\n \"sugar\",\n \"tuna\",\n \"you\",\n \"wood\"\n ]\n // save some time in the case that singular and plural are the same\n if (uncountable.indexOf(word.toLowerCase()) >= 0) {\n return word;\n }\n // check for irregular forms\n for (const w in irregular) {\n const pattern = new RegExp(`${irregular[w]}$`, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, w);\n }\n }\n // check for matches using regular expressions\n for (const reg in singulars) {\n const pattern = new RegExp(reg, \"i\");\n if (pattern.test(word)) {\n return word.replace(pattern, singulars[reg]);\n }\n }\n return word;\n}\n","import { singular } from \"./plurals\";\nimport { toSnakeCase } from \"./strings\";\n\n/**\n * Generates a foreign key column name from a given string, typically a collection slug or name.\n * It singularizes the name, converts it to snake_case and appends '_id'.\n *\n * Singularization runs *before* snake-casing so that acronyms survive: `toSnakeCase`\n * splits on every capital, which turned \"URLs\" into \"ur_ls\" and then \"ur_l_id\".\n *\n * @param name The base name to convert to a foreign key.\n * @returns A foreign key name in the format 'singular_name_id'.\n *\n * @example\n * // returns \"user_id\"\n * generateForeignKeyName(\"users\")\n *\n * @example\n * // returns \"category_id\"\n * generateForeignKeyName(\"categories\")\n *\n * @example\n * // returns \"product_id\"\n * generateForeignKeyName(\"Product\")\n *\n */\nexport function generateForeignKeyName(name: string): string {\n return `${toSnakeCase(singularizeForKey(name))}_id`;\n}\n\n/**\n * `singular()` handles real English plurals, but its final catch-all rule strips\n * any trailing \"s\", which mangles words that only look plural. Guard the two\n * cases that produce a column name nobody would recognise:\n *\n * - a double \"s\" ending is never a plural marker (\"address\", \"class\", \"process\"),\n * so stripping it yields \"addres\";\n * - a name that singularizes to nothing (the literal \"s\") would yield \"_id\".\n */\nfunction singularizeForKey(name: string): string {\n if (/ss$/i.test(name)) return name;\n const result = singular(name);\n return result.length > 0 ? result : name;\n}\n\n/**\n * What `generateForeignKeyName` returned before it learned to singularize:\n * snake-case the name, then chop one trailing \"s\".\n *\n * This is here to be *detected*, never to be generated. A database provisioned\n * under the old rule carries `categorie_id`, `addresse_id`, `children_id` or\n * `ur_l_id` where the current rule expects `category_id`, `address_id`,\n * `child_id` and `url_id` — and the boot-time schema ensure is additive, so it\n * would create the new column empty beside the populated old one and leave the\n * relation reading nothing. No error, no missing table: the failure is silent,\n * which is the only reason this function still exists.\n *\n * `ensureCollectionSchema` calls it to recognise that shape and say so.\n * Returns the same string as `generateForeignKeyName` for every regular plural,\n * so a caller can compare the two and act only when they differ.\n */\nexport function legacyForeignKeyName(name: string): string {\n const snake = toSnakeCase(name);\n return `${snake.endsWith(\"s\") ? snake.slice(0, -1) : snake}_id`;\n}\n","\n\nexport function isDefaultFieldConfigId(id: string): boolean {\n return [\"text_field\",\n \"multiline\",\n \"markdown\",\n \"url\",\n \"email\",\n \"switch\",\n \"select\",\n \"multi_select\",\n \"number_input\",\n \"number_select\",\n \"multi_number_select\",\n \"file_upload\",\n \"multi_file_upload\",\n \"reference\",\n \"multi_references\",\n \"relation\",\n \"date_time\",\n \"group\",\n \"key_value\",\n \"repeat\",\n \"custom_array\",\n \"block\"\n ].includes(id);\n}\n"],"mappings":";;;AAAA,IAAM,gBAAgB;AAEtB,IAAa,eAAe,QAAiB;CACzC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,mBAAmB,IAAI,MAAM,aAAa;CAChD,IAAI,CAAC,kBAAkB,OAAO;CAC9B,OAAO,iBACF,KAAI,MAAK,EAAE,YAAY,CAAC,CAAC,CACzB,KAAK,GAAG;AACjB;AAEA,IAAM,iBAAiB;AAEvB,IAAa,eAAe,QAAiB;CACzC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,mBAAmB,IAAI,MAAM,cAAc;CACjD,IAAI,CAAC,kBAAkB,OAAO;CAC9B,OAAO,i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C;;;;;;;;;;;;;;;;;AAkBA,SAAgB,qBAAqB,MAAsB;CACvD,MAAM,QAAQ,YAAY,IAAI;CAC9B,OAAO,GAAG,MAAM,SAAS,GAAG,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI,MAAM;AAC/D;;;AC9DA,SAAgB,uBAAuB,IAAqB;CACxD,OAAO;EAAC;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,EAAE;AACjB"}
package/dist/objects.d.ts CHANGED
@@ -6,6 +6,18 @@ export declare const isFunction: (obj: unknown) => obj is (...args: unknown[]) =
6
6
  export declare const isInteger: (obj: unknown) => boolean;
7
7
  /** @private is the given object a NaN? */
8
8
  export declare const isNaN: (obj: unknown) => boolean;
9
+ /** Whether any segment of this path would traverse the prototype chain. */
10
+ export declare function pathTraversesPrototype(path: string | string[]): boolean;
11
+ /**
12
+ * Whether writing this single key with `obj[key] = …` would reach the prototype
13
+ * chain instead of creating a property.
14
+ *
15
+ * The single-key counterpart of {@link pathTraversesPrototype}, for the many
16
+ * places that copy an object one key at a time. `JSON.parse` creates
17
+ * `__proto__` as an *own* property, so it survives `hasOwnProperty` — and then
18
+ * `target[key] = value` invokes the setter and replaces the target's prototype.
19
+ */
20
+ export declare function isPrototypePollutingKey(key: string): boolean;
9
21
  /**
10
22
  * Deeply get a value from an object via its path.
11
23
  */
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Reading and writing the small amounts of JSON a UI keeps between sessions —
3
+ * open tabs, column widths, collapsed groups, recent searches.
4
+ *
5
+ * Every one of those reads is a read of *aged* state: it was written by whatever
6
+ * version of the app the user last ran, and it is parsed by this one. The same
7
+ * class the database upgrade path is careful about, in a place nothing migrates.
8
+ *
9
+ * A hand-rolled `JSON.parse(localStorage.getItem(key)!)` has four ways to throw
10
+ * and no way to recover from any of them:
11
+ *
12
+ * - `localStorage` itself throws on access when storage is disabled (Safari
13
+ * private browsing, blocked third-party cookies) or absent (SSR, Node).
14
+ * - the stored text is not JSON, because a write was interrupted or a user
15
+ * edited it.
16
+ * - the stored text is valid JSON of the *wrong shape*, because an older
17
+ * release wrote an object where this one expects an array. `parsed.map` is
18
+ * then not a function.
19
+ * - `setItem` throws `QuotaExceededError` once the origin's few megabytes are
20
+ * full, which a view that persists query text on every edit will reach.
21
+ *
22
+ * When any of those happens inside a `useState` initializer it throws during
23
+ * render, and the bad value is still there on reload, so the view is bricked
24
+ * until someone opens devtools. These helpers turn all four into the fallback.
25
+ */
26
+ export interface WebStorageLike {
27
+ getItem(key: string): string | null;
28
+ setItem(key: string, value: string): void;
29
+ removeItem(key: string): void;
30
+ }
31
+ /**
32
+ * The ambient `localStorage`, or `null` where there is not one. Access itself
33
+ * is what throws when storage is disabled, so even reaching for it is guarded.
34
+ */
35
+ export declare function getWebStorage(): WebStorageLike | null;
36
+ export type ReadStoredJsonOptions<T> = {
37
+ /** Returned whenever the stored value is missing, unreadable or rejected. */
38
+ fallback: T;
39
+ /**
40
+ * Whether the parsed value is the shape this caller expects. Pass it
41
+ * whenever the fallback is an array or a keyed object: valid JSON of the
42
+ * wrong shape is the failure an upgrade actually produces, and it survives
43
+ * `JSON.parse` untouched to fail later at the first `.map` or `.find`.
44
+ */
45
+ accept?: (value: unknown) => boolean;
46
+ /** Defaults to the ambient `localStorage`. */
47
+ storage?: WebStorageLike | null;
48
+ };
49
+ /**
50
+ * Reads and parses a JSON value a previous session stored, falling back rather
51
+ * than throwing. See the module comment for what it is falling back from.
52
+ *
53
+ * A rejected value is deliberately left in place rather than cleared: this
54
+ * version not understanding it is not evidence that nothing does.
55
+ */
56
+ export declare function readStoredJson<T>(key: string, options: ReadStoredJsonOptions<T>): T;
57
+ /**
58
+ * Persists a value as JSON. Returns whether it was stored, so a caller that
59
+ * cares can say so — most do not, and for them the point is simply that a full
60
+ * quota does not throw out of the effect doing the writing.
61
+ */
62
+ export declare function writeStoredJson(key: string, value: unknown, options?: {
63
+ storage?: WebStorageLike | null;
64
+ }): boolean;
65
+ /**
66
+ * Persists an already-serialised string, for the values kept as plain text
67
+ * rather than JSON — a selected id, a pane size.
68
+ */
69
+ export declare function writeStoredString(key: string, value: string, options?: {
70
+ storage?: WebStorageLike | null;
71
+ }): boolean;
72
+ /** Reads a plain string, absent rather than throwing where there is no storage. */
73
+ export declare function readStoredString(key: string, options?: {
74
+ storage?: WebStorageLike | null;
75
+ }): string | null;
76
+ /** `accept` for a caller whose fallback is an array. */
77
+ export declare const isArrayValue: (value: unknown) => boolean;
78
+ /** `accept` for a caller whose fallback is a keyed object — and not an array. */
79
+ export declare const isRecordValue: (value: unknown) => boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/utils",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.13.1-canary.g18cfeb7",
5
5
  "description": "Utility functions for Rebase",
6
6
  "funding": {
7
7
  "url": "https://github.com/sponsors/rebaseco"
@@ -39,7 +39,7 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "object-hash": "^3.0.0",
42
- "@rebasepro/types": "0.13.0"
42
+ "@rebasepro/types": "0.13.1-canary.g18cfeb7"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@jest/globals": "^30.4.1",
package/src/dates.ts CHANGED
@@ -1 +1,69 @@
1
1
  export const defaultDateFormat = "MMMM dd, yyyy, HH:mm:ss";
2
+
3
+ /** Seven days, the distance past which a relative phrase stops being useful. */
4
+ const DEFAULT_MAX_MS = 7 * 24 * 60 * 60 * 1000;
5
+
6
+ export type FormatRelativeTimeOptions = {
7
+ /**
8
+ * The instant the distance is measured from. Defaults to the current time.
9
+ * Pass it explicitly to make a caller testable without faking the clock.
10
+ */
11
+ now?: Date | number;
12
+ /**
13
+ * How far a value may sit from {@link now} and still be described
14
+ * relatively. Beyond it the function returns `null` and the caller renders
15
+ * an absolute date instead. Defaults to seven days.
16
+ */
17
+ maxMs?: number;
18
+ };
19
+
20
+ function toTime(value: Date | string | number | null | undefined): number | null {
21
+ if (value === null || value === undefined || value === "") return null;
22
+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime();
23
+ return Number.isNaN(time) ? null : time;
24
+ }
25
+
26
+ /**
27
+ * Describes an instant relative to another one — "5m ago", "in 3h".
28
+ *
29
+ * The direction is part of the answer. Every hand-rolled version of this in the
30
+ * codebase computed `now - then` and then tested only the positive side, so a
31
+ * timestamp in the future fell through to whichever branch happened to be
32
+ * first: a date scheduled for next month read "Just now", and one a couple of
33
+ * hours out read "-1d ago". Both are dates a CMS holds all the time — a publish
34
+ * date, a due date, an expiry — and neither shape can occur here, because the
35
+ * distance is measured with {@link Math.abs} and the tense is chosen from the
36
+ * sign rather than assumed.
37
+ *
38
+ * Returns `null` when the value is unreadable, or when it is further than
39
+ * {@link FormatRelativeTimeOptions.maxMs} away in either direction. `null` is
40
+ * "say it another way", not an error: the caller owns the absolute format, and
41
+ * the locale and precision that go with it.
42
+ */
43
+ export function formatRelativeTime(
44
+ value: Date | string | number | null | undefined,
45
+ options: FormatRelativeTimeOptions = {}
46
+ ): string | null {
47
+ const then = toTime(value);
48
+ if (then === null) return null;
49
+
50
+ const now = options.now instanceof Date ? options.now.getTime() : (options.now ?? Date.now());
51
+ const maxMs = options.maxMs ?? DEFAULT_MAX_MS;
52
+
53
+ // Positive is the past, which is the only case the callers used to handle.
54
+ const delta = now - then;
55
+ const distance = Math.abs(delta);
56
+ if (distance > maxMs) return null;
57
+
58
+ const future = delta < 0;
59
+
60
+ const minutes = Math.floor(distance / 60_000);
61
+ if (minutes < 1) return future ? "in a moment" : "just now";
62
+ if (minutes < 60) return future ? `in ${minutes}m` : `${minutes}m ago`;
63
+
64
+ const hours = Math.floor(distance / 3_600_000);
65
+ if (hours < 24) return future ? `in ${hours}h` : `${hours}h ago`;
66
+
67
+ const days = Math.floor(distance / 86_400_000);
68
+ return future ? `in ${days}d` : `${days}d ago`;
69
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./strings";
2
2
  export * from "./objects";
3
3
  export * from "./arrays";
4
4
  export * from "./dates";
5
+ export * from "./storage";
5
6
  export * from "./hash";
6
7
  export * from "./sha1";
7
8
  export * from "./policy-names";
package/src/objects.ts CHANGED
@@ -17,6 +17,38 @@ export const isInteger = (obj: unknown): boolean =>
17
17
 
18
18
  export const isNaN = (obj: unknown): boolean => obj !== obj;
19
19
 
20
+ /**
21
+ * Segments that reach the prototype chain rather than a property of the object.
22
+ *
23
+ * The twin of this function in `@rebasepro/forms` could be made to write onto
24
+ * `Object.prototype` through a path of `__proto__.x`. This copy survives the
25
+ * write by accident — its `clone` always spreads into a fresh object, while the
26
+ * form engine's has a "preserve class instances" branch that hands back
27
+ * `Object.prototype` itself — but `getIn` still *reads* through the chain, and
28
+ * handing back `Object.prototype` is how a polluted value is read out again.
29
+ *
30
+ * Closed on both sides here, so the two implementations agree.
31
+ */
32
+ const UNSAFE_PATH_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
33
+
34
+ /** Whether any segment of this path would traverse the prototype chain. */
35
+ export function pathTraversesPrototype(path: string | string[]): boolean {
36
+ return toPath(path).some(segment => UNSAFE_PATH_SEGMENTS.has(segment));
37
+ }
38
+
39
+ /**
40
+ * Whether writing this single key with `obj[key] = …` would reach the prototype
41
+ * chain instead of creating a property.
42
+ *
43
+ * The single-key counterpart of {@link pathTraversesPrototype}, for the many
44
+ * places that copy an object one key at a time. `JSON.parse` creates
45
+ * `__proto__` as an *own* property, so it survives `hasOwnProperty` — and then
46
+ * `target[key] = value` invokes the setter and replaces the target's prototype.
47
+ */
48
+ export function isPrototypePollutingKey(key: string): boolean {
49
+ return UNSAFE_PATH_SEGMENTS.has(key);
50
+ }
51
+
20
52
  /**
21
53
  * Deeply get a value from an object via its path.
22
54
  */
@@ -26,6 +58,8 @@ export function getIn(
26
58
  def?: unknown,
27
59
  p = 0
28
60
  ) {
61
+ if (pathTraversesPrototype(key)) return def;
62
+
29
63
  const path = toPath(key);
30
64
  while (obj && p < path.length) {
31
65
  obj = (obj as Record<string, unknown>)[path[p++]];
@@ -40,6 +74,11 @@ export function getIn(
40
74
  }
41
75
 
42
76
  export function setIn<T>(obj: T, path: string, value: unknown): T {
77
+ // See `pathTraversesPrototype`. This copy's `clone` happens to contain the
78
+ // write, but relying on that is relying on an implementation detail of a
79
+ // different function.
80
+ if (pathTraversesPrototype(path)) return obj;
81
+
43
82
  const res = clone(obj) as Record<string, unknown>;
44
83
  let resVal: Record<string, unknown> = res;
45
84
  let i = 0;
package/src/storage.ts ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Reading and writing the small amounts of JSON a UI keeps between sessions —
3
+ * open tabs, column widths, collapsed groups, recent searches.
4
+ *
5
+ * Every one of those reads is a read of *aged* state: it was written by whatever
6
+ * version of the app the user last ran, and it is parsed by this one. The same
7
+ * class the database upgrade path is careful about, in a place nothing migrates.
8
+ *
9
+ * A hand-rolled `JSON.parse(localStorage.getItem(key)!)` has four ways to throw
10
+ * and no way to recover from any of them:
11
+ *
12
+ * - `localStorage` itself throws on access when storage is disabled (Safari
13
+ * private browsing, blocked third-party cookies) or absent (SSR, Node).
14
+ * - the stored text is not JSON, because a write was interrupted or a user
15
+ * edited it.
16
+ * - the stored text is valid JSON of the *wrong shape*, because an older
17
+ * release wrote an object where this one expects an array. `parsed.map` is
18
+ * then not a function.
19
+ * - `setItem` throws `QuotaExceededError` once the origin's few megabytes are
20
+ * full, which a view that persists query text on every edit will reach.
21
+ *
22
+ * When any of those happens inside a `useState` initializer it throws during
23
+ * render, and the bad value is still there on reload, so the view is bricked
24
+ * until someone opens devtools. These helpers turn all four into the fallback.
25
+ */
26
+
27
+ export interface WebStorageLike {
28
+ getItem(key: string): string | null;
29
+ setItem(key: string, value: string): void;
30
+ removeItem(key: string): void;
31
+ }
32
+
33
+ /**
34
+ * The ambient `localStorage`, or `null` where there is not one. Access itself
35
+ * is what throws when storage is disabled, so even reaching for it is guarded.
36
+ */
37
+ export function getWebStorage(): WebStorageLike | null {
38
+ try {
39
+ const storage = (globalThis as { localStorage?: WebStorageLike }).localStorage;
40
+ return storage ?? null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ export type ReadStoredJsonOptions<T> = {
47
+ /** Returned whenever the stored value is missing, unreadable or rejected. */
48
+ fallback: T;
49
+ /**
50
+ * Whether the parsed value is the shape this caller expects. Pass it
51
+ * whenever the fallback is an array or a keyed object: valid JSON of the
52
+ * wrong shape is the failure an upgrade actually produces, and it survives
53
+ * `JSON.parse` untouched to fail later at the first `.map` or `.find`.
54
+ */
55
+ accept?: (value: unknown) => boolean;
56
+ /** Defaults to the ambient `localStorage`. */
57
+ storage?: WebStorageLike | null;
58
+ };
59
+
60
+ /**
61
+ * Reads and parses a JSON value a previous session stored, falling back rather
62
+ * than throwing. See the module comment for what it is falling back from.
63
+ *
64
+ * A rejected value is deliberately left in place rather than cleared: this
65
+ * version not understanding it is not evidence that nothing does.
66
+ */
67
+ export function readStoredJson<T>(key: string, options: ReadStoredJsonOptions<T>): T {
68
+ const storage = options.storage === undefined ? getWebStorage() : options.storage;
69
+ if (!storage) return options.fallback;
70
+
71
+ let raw: string | null;
72
+ try {
73
+ raw = storage.getItem(key);
74
+ } catch {
75
+ return options.fallback;
76
+ }
77
+ if (raw === null || raw === "") return options.fallback;
78
+
79
+ let parsed: unknown;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch {
83
+ return options.fallback;
84
+ }
85
+
86
+ if (options.accept && !options.accept(parsed)) return options.fallback;
87
+ return parsed as T;
88
+ }
89
+
90
+ /**
91
+ * Persists a value as JSON. Returns whether it was stored, so a caller that
92
+ * cares can say so — most do not, and for them the point is simply that a full
93
+ * quota does not throw out of the effect doing the writing.
94
+ */
95
+ export function writeStoredJson(
96
+ key: string,
97
+ value: unknown,
98
+ options: { storage?: WebStorageLike | null } = {}
99
+ ): boolean {
100
+ const storage = options.storage === undefined ? getWebStorage() : options.storage;
101
+ if (!storage) return false;
102
+ try {
103
+ storage.setItem(key, JSON.stringify(value));
104
+ return true;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Persists an already-serialised string, for the values kept as plain text
112
+ * rather than JSON — a selected id, a pane size.
113
+ */
114
+ export function writeStoredString(
115
+ key: string,
116
+ value: string,
117
+ options: { storage?: WebStorageLike | null } = {}
118
+ ): boolean {
119
+ const storage = options.storage === undefined ? getWebStorage() : options.storage;
120
+ if (!storage) return false;
121
+ try {
122
+ storage.setItem(key, value);
123
+ return true;
124
+ } catch {
125
+ return false;
126
+ }
127
+ }
128
+
129
+ /** Reads a plain string, absent rather than throwing where there is no storage. */
130
+ export function readStoredString(
131
+ key: string,
132
+ options: { storage?: WebStorageLike | null } = {}
133
+ ): string | null {
134
+ const storage = options.storage === undefined ? getWebStorage() : options.storage;
135
+ if (!storage) return null;
136
+ try {
137
+ return storage.getItem(key);
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+
143
+ /** `accept` for a caller whose fallback is an array. */
144
+ export const isArrayValue = (value: unknown): boolean => Array.isArray(value);
145
+
146
+ /** `accept` for a caller whose fallback is a keyed object — and not an array. */
147
+ export const isRecordValue = (value: unknown): boolean =>
148
+ typeof value === "object" && value !== null && !Array.isArray(value);