@rebasepro/common 0.0.1-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +174 -0
  3. package/dist/collections/CollectionRegistry.d.ts +48 -0
  4. package/dist/collections/index.d.ts +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.es.js +2380 -0
  7. package/dist/index.es.js.map +1 -0
  8. package/dist/index.umd.js +2379 -0
  9. package/dist/index.umd.js.map +1 -0
  10. package/dist/util/arrays.d.ts +1 -0
  11. package/dist/util/builders.d.ts +64 -0
  12. package/dist/util/callbacks.d.ts +6 -0
  13. package/dist/util/collections.d.ts +11 -0
  14. package/dist/util/common.d.ts +2 -0
  15. package/dist/util/conditions.d.ts +26 -0
  16. package/dist/util/dates.d.ts +1 -0
  17. package/dist/util/entities.d.ts +28 -0
  18. package/dist/util/entity_actions.d.ts +2 -0
  19. package/dist/util/enums.d.ts +3 -0
  20. package/dist/util/fields.d.ts +2 -0
  21. package/dist/util/flatten_object.d.ts +5 -0
  22. package/dist/util/hash.d.ts +1 -0
  23. package/dist/util/index.d.ts +26 -0
  24. package/dist/util/names.d.ts +22 -0
  25. package/dist/util/navigation_from_path.d.ts +29 -0
  26. package/dist/util/navigation_utils.d.ts +31 -0
  27. package/dist/util/objects.d.ts +26 -0
  28. package/dist/util/os.d.ts +2 -0
  29. package/dist/util/parent_references_from_path.d.ts +6 -0
  30. package/dist/util/paths.d.ts +14 -0
  31. package/dist/util/permissions.d.ts +5 -0
  32. package/dist/util/permissions.test.d.ts +1 -0
  33. package/dist/util/plurals.d.ts +16 -0
  34. package/dist/util/references.d.ts +2 -0
  35. package/dist/util/regexp.d.ts +7 -0
  36. package/dist/util/relations.d.ts +12 -0
  37. package/dist/util/resolutions.d.ts +74 -0
  38. package/dist/util/storage.d.ts +24 -0
  39. package/dist/util/strings.d.ts +7 -0
  40. package/package.json +118 -0
  41. package/src/collections/CollectionRegistry.ts +319 -0
  42. package/src/collections/index.ts +1 -0
  43. package/src/index.ts +2 -0
  44. package/src/util/arrays.ts +3 -0
  45. package/src/util/builders.ts +138 -0
  46. package/src/util/callbacks.ts +115 -0
  47. package/src/util/collections.ts +126 -0
  48. package/src/util/common.ts +2 -0
  49. package/src/util/conditions.ts +348 -0
  50. package/src/util/dates.ts +1 -0
  51. package/src/util/entities.ts +212 -0
  52. package/src/util/entity_actions.ts +28 -0
  53. package/src/util/enums.ts +26 -0
  54. package/src/util/fields.ts +28 -0
  55. package/src/util/flatten_object.ts +45 -0
  56. package/src/util/hash.ts +11 -0
  57. package/src/util/index.ts +26 -0
  58. package/src/util/names.ts +30 -0
  59. package/src/util/navigation_from_path.ts +121 -0
  60. package/src/util/navigation_utils.ts +222 -0
  61. package/src/util/objects.ts +376 -0
  62. package/src/util/os.ts +13 -0
  63. package/src/util/parent_references_from_path.ts +57 -0
  64. package/src/util/paths.ts +27 -0
  65. package/src/util/permissions.test.ts +716 -0
  66. package/src/util/permissions.ts +235 -0
  67. package/src/util/plurals.ts +188 -0
  68. package/src/util/references.ts +34 -0
  69. package/src/util/regexp.ts +32 -0
  70. package/src/util/relations.ts +211 -0
  71. package/src/util/resolutions.ts +383 -0
  72. package/src/util/storage.ts +144 -0
  73. package/src/util/strings.ts +84 -0
@@ -0,0 +1,376 @@
1
+ import hash from "object-hash";
2
+ import { GeoPoint } from "@rebasepro/types";
3
+
4
+ /** @private is the value an empty array? */
5
+ export const isEmptyArray = (value?: unknown) =>
6
+ Array.isArray(value) && value.length === 0;
7
+
8
+ /** @private is the given object a Function? */
9
+ export const isFunction = (obj: unknown): obj is Function =>
10
+ typeof obj === "function";
11
+
12
+ /** @private is the given object an integer? */
13
+ export const isInteger = (obj: unknown): boolean =>
14
+ String(Math.floor(Number(obj))) === String(obj);
15
+
16
+ /** @private is the given object a NaN? */
17
+ // eslint-disable-next-line no-self-compare
18
+ export const isNaN = (obj: unknown): boolean => obj !== obj;
19
+
20
+ /**
21
+ * Deeply get a value from an object via its path.
22
+ */
23
+ export function getIn(
24
+ obj: Record<string, unknown> | unknown[] | unknown,
25
+ key: string | string[],
26
+ def?: unknown,
27
+ p = 0
28
+ ) {
29
+ const path = toPath(key);
30
+ while (obj && p < path.length) {
31
+ obj = (obj as Record<string, unknown>)[path[p++]];
32
+ }
33
+
34
+ // check if path is not in the end
35
+ if (p !== path.length && !obj) {
36
+ return def;
37
+ }
38
+
39
+ return obj === undefined ? def : obj;
40
+ }
41
+
42
+ export function setIn<T>(obj: T, path: string, value: unknown): T {
43
+ const res = clone(obj) as Record<string, unknown>;
44
+ let resVal: Record<string, unknown> = res;
45
+ let i = 0;
46
+ const pathArray = toPath(path);
47
+
48
+ for (; i < pathArray.length - 1; i++) {
49
+ const currentPath: string = pathArray[i];
50
+ const currentObj = getIn(obj as Record<string, unknown>, pathArray.slice(0, i + 1));
51
+
52
+ if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {
53
+ resVal = resVal[currentPath] = clone(currentObj) as Record<string, unknown>;
54
+ } else {
55
+ const nextPath: string = pathArray[i + 1];
56
+ resVal = resVal[currentPath] =
57
+ (isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}) as Record<string, unknown>;
58
+ }
59
+ }
60
+
61
+ // Return original object if new value is the same as current
62
+ if ((i === 0 ? obj as Record<string, unknown> : resVal)[pathArray[i]] === value) {
63
+ return obj;
64
+ }
65
+
66
+ if (value === undefined) {
67
+ delete resVal[pathArray[i]];
68
+ } else {
69
+ resVal[pathArray[i]] = value;
70
+ }
71
+
72
+ // If the path array has a single element, the loop did not run.
73
+ // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.
74
+ if (i === 0 && value === undefined) {
75
+ delete res[pathArray[i]];
76
+ }
77
+
78
+ return res as T;
79
+ }
80
+
81
+ export function clone<T>(value: T): T {
82
+ if (Array.isArray(value)) {
83
+ return [...value] as unknown as T;
84
+ } else if (typeof value === "object" && value !== null) {
85
+ return { ...value } as T;
86
+ } else {
87
+ return value; // This is for primitive types which do not need cloning.
88
+ }
89
+ }
90
+
91
+ function toPath(value: string | string[]) {
92
+ if (Array.isArray(value)) return value; // Already in path array form.
93
+ // Replace brackets with dots, remove leading/trailing dots, then split by dot.
94
+ return value.replace(/\[(\d+)]/g, ".$1").replace(/^\./, "").replace(/\.$/, "").split(".");
95
+ }
96
+
97
+
98
+ export const pick: <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => Partial<T> = <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => ({
99
+ ...args.reduce<Record<string, unknown>>((res, key) => ({
100
+ ...res,
101
+ [key as string]: obj[key as string]
102
+ }), {})
103
+ }) as Partial<T>;
104
+
105
+ export function isObject(item: unknown): item is Record<string, unknown> {
106
+ return !!item && typeof item === "object" && !Array.isArray(item);
107
+ }
108
+
109
+ export function isPlainObject(obj: unknown): obj is Record<string, unknown> {
110
+ // 1. Rule out non-objects, null, and arrays
111
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
112
+ return false;
113
+ }
114
+
115
+ // 2. Get the object's direct prototype
116
+ const proto = Object.getPrototypeOf(obj);
117
+
118
+ // 3. A plain object's direct prototype is Object.prototype
119
+ return proto === Object.prototype;
120
+ }
121
+
122
+ export function mergeDeep<T extends Record<string, any>, U extends Record<string, any>>(
123
+ target: T,
124
+ source: U,
125
+ ignoreUndefined: boolean = false
126
+ ): T & U {
127
+ // If target is not a true object (e.g., null, array, primitive), return target itself.
128
+ if (!isObject(target)) {
129
+ return target as T & U;
130
+ }
131
+
132
+ // Create a shallow copy of the target to avoid modifying the original object.
133
+ const output = { ...target };
134
+
135
+ // If source is not a true object, there's nothing to merge from it.
136
+ // Return the shallow copy of target.
137
+ if (!isObject(source)) {
138
+ return output as T & U;
139
+ }
140
+
141
+ // Iterate over keys in the source object.
142
+ for (const key in source) {
143
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
144
+ const sourceValue = source[key];
145
+ const outputValue = (output as any)[key]; // Current value in our merged object (originating from target)
146
+
147
+ // Skip if source value is undefined and ignoreUndefined is true.
148
+ // This handles both not adding new undefined properties and not overwriting existing properties with undefined.
149
+ if (ignoreUndefined && sourceValue === undefined) {
150
+ continue;
151
+ }
152
+
153
+ if ((sourceValue as unknown) instanceof Date) {
154
+ // If source value is a Date, create a new Date instance.
155
+ (output as Record<string, unknown>)[key] = new Date((sourceValue as unknown as Date).getTime());
156
+ } else if (Array.isArray(sourceValue)) {
157
+ if (Array.isArray(outputValue)) {
158
+ const newArray = [];
159
+ const maxLength = Math.max(outputValue.length, sourceValue.length);
160
+ for (let i = 0; i < maxLength; i++) {
161
+ const sourceItem = sourceValue[i];
162
+ const targetItem = outputValue[i];
163
+
164
+ if (i >= sourceValue.length) { // source is shorter
165
+ newArray[i] = targetItem;
166
+ } else if (i >= outputValue.length) { // target is shorter
167
+ newArray[i] = sourceItem;
168
+ } else if (sourceItem === null) {
169
+ newArray[i] = targetItem;
170
+ } else if (isPlainObject(sourceItem) && isPlainObject(targetItem)) {
171
+ // Only recursively merge plain objects, preserve class instances
172
+ newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);
173
+ } else {
174
+ // For class instances and primitives, use source directly
175
+ newArray[i] = sourceItem;
176
+ }
177
+ }
178
+ (output as Record<string, unknown>)[key] = newArray;
179
+ } else {
180
+ // If output's value (from target) is not an array,
181
+ // overwrite with a shallow copy of the source array.
182
+ (output as Record<string, unknown>)[key] = [...sourceValue];
183
+ }
184
+ } else if (isPlainObject(sourceValue)) {
185
+ // If source value is a plain object (not a class instance like EntityReference, GeoPoint, etc.):
186
+ if (isPlainObject(outputValue)) {
187
+ // If the corresponding value in output (from target) is also a plain object, recurse.
188
+ // Ensure the ignoreUndefined flag is passed down.
189
+ (output as Record<string, unknown>)[key] = mergeDeep(outputValue as Record<string, unknown>, sourceValue, ignoreUndefined);
190
+ } else {
191
+ // 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),
192
+ // overwrite with the source object.
193
+ (output as Record<string, unknown>)[key] = sourceValue;
194
+ }
195
+ } else if (isObject(sourceValue)) {
196
+ // If source value is a class instance (not a plain object), use it directly to preserve prototype
197
+ (output as Record<string, unknown>)[key] = sourceValue;
198
+ } else {
199
+ // If source value is a primitive, null, or undefined (and not ignored).
200
+ (output as Record<string, unknown>)[key] = sourceValue;
201
+ }
202
+ }
203
+ }
204
+
205
+ return output as T & U;
206
+ }
207
+
208
+ export function getValueInPath(o: object | undefined, path: string): unknown {
209
+ if (!o) return undefined;
210
+ if (typeof o === "object") {
211
+ if (path in o) {
212
+ return (o as Record<string, unknown>)[path];
213
+ }
214
+ if (path.includes(".") || path.includes("[")) {
215
+ let pathSegments = path.split(/[.[]/);
216
+ if (path.includes("[")) {
217
+ pathSegments = pathSegments.map(segment => segment.replace("]", ""));
218
+ }
219
+ const firstSegment = pathSegments[0];
220
+ const isArrayAndIndexExists = Array.isArray((o as Record<string, unknown>)[firstSegment]) && !isNaN(parseInt(pathSegments[1]));
221
+ const nextObject = isArrayAndIndexExists
222
+ ? ((o as Record<string, unknown>)[firstSegment] as unknown[])[parseInt(pathSegments[1])]
223
+ : (o as Record<string, unknown>)[firstSegment];
224
+
225
+ const nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(".");
226
+ if (nextPath === "")
227
+ return nextObject;
228
+ return getValueInPath(nextObject as object | undefined, nextPath);
229
+ }
230
+ }
231
+ return undefined;
232
+ }
233
+
234
+ export function removeInPath(o: object, path: string): object | undefined {
235
+ let currentObject = { ...o };
236
+ const parts = path.split(".");
237
+ const last = parts.pop();
238
+ for (const part of parts) {
239
+ currentObject = (currentObject as Record<string, unknown>)[part] as Record<string, unknown>;
240
+ }
241
+ if (last)
242
+ delete (currentObject as Record<string, unknown>)[last];
243
+ return currentObject;
244
+ }
245
+
246
+ export function removeFunctions(o: unknown): unknown {
247
+ if (o === undefined) return undefined;
248
+ if (o === null) return null;
249
+ if (typeof o === "object") {
250
+ // Handle arrays first - map over them recursively
251
+ if (Array.isArray(o)) {
252
+ return o.map(v => removeFunctions(v));
253
+ }
254
+ // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them
255
+ if (!isPlainObject(o)) {
256
+ return o;
257
+ }
258
+ return Object.entries(o)
259
+ .filter(([_, value]) => typeof value !== "function")
260
+ .map(([key, value]) => {
261
+ if (Array.isArray(value)) {
262
+ return { [key]: value.map(v => removeFunctions(v)) };
263
+ } else if (typeof value === "object") {
264
+ return { [key]: removeFunctions(value) };
265
+ } else return { [key]: value };
266
+ })
267
+ .reduce((a, b) => ({ ...a, ...b }), {});
268
+ }
269
+ return o;
270
+ }
271
+
272
+ export function getHashValue<T>(v: T): string | null {
273
+ if (!v) return null;
274
+ if (typeof v === "object" && v !== null) {
275
+ if ("id" in v)
276
+ return String((v as Record<string, unknown>).id);
277
+ else if (v instanceof Date)
278
+ return v.toLocaleString();
279
+ else if (v instanceof GeoPoint)
280
+ return hash(v as unknown as Record<string, unknown>);
281
+ }
282
+ return hash(v as object, { ignoreUnknown: true });
283
+ }
284
+
285
+ export function removeUndefined(value: unknown, removeEmptyStrings?: boolean): unknown {
286
+ if (typeof value === "function") {
287
+ return value;
288
+ }
289
+ if (Array.isArray(value)) {
290
+ return value.map((v: unknown) => removeUndefined(v, removeEmptyStrings));
291
+ }
292
+ if (typeof value === "object") {
293
+ if (value === null)
294
+ return value;
295
+ // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them
296
+ if (!isPlainObject(value)) {
297
+ return value;
298
+ }
299
+ const res: Record<string, unknown> = {};
300
+ Object.keys(value).forEach((key) => {
301
+ if (!isEmptyObject(value as object)) {
302
+ const childRes = removeUndefined((value as Record<string, unknown>)[key], removeEmptyStrings);
303
+ const isString = typeof childRes === "string";
304
+ const shouldKeepIfString = !removeEmptyStrings || (removeEmptyStrings && !isString) || (removeEmptyStrings && isString && childRes !== "");
305
+ if (childRes !== undefined && !isEmptyObject(childRes as object) && shouldKeepIfString)
306
+ res[key] = childRes;
307
+ }
308
+ });
309
+ return res;
310
+ }
311
+ return value;
312
+ }
313
+
314
+ export function removeNulls(value: unknown): unknown {
315
+ if (typeof value === "function") {
316
+ return value;
317
+ }
318
+ if (Array.isArray(value)) {
319
+ return value.map((v: unknown) => removeNulls(v));
320
+ }
321
+ if (typeof value === "object") {
322
+ if (value === null)
323
+ return value;
324
+ // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them
325
+ if (!isPlainObject(value)) {
326
+ return value;
327
+ }
328
+ const res: Record<string, unknown> = {};
329
+ const obj = value as Record<string, unknown>;
330
+ Object.keys(obj).forEach((key) => {
331
+ if (obj[key] !== null)
332
+ res[key] = removeNulls(obj[key]);
333
+ });
334
+ return res;
335
+ }
336
+ return value;
337
+ }
338
+
339
+ export function isEmptyObject(obj: object) {
340
+ return obj &&
341
+ Object.getPrototypeOf(obj) === Object.prototype &&
342
+ Object.keys(obj).length === 0
343
+ }
344
+
345
+ export function removePropsIfExisting(source: Record<string, unknown> | unknown[], comparison: Record<string, unknown> | unknown[]) {
346
+ const isObject = (val: unknown): val is Record<string, unknown> => typeof val === "object" && val !== null;
347
+ const isArray = (val: unknown): val is unknown[] => Array.isArray(val);
348
+
349
+ if (!isObject(source) || !isObject(comparison)) {
350
+ return source;
351
+ }
352
+
353
+ const res = isArray(source) ? [...source] : { ...source };
354
+
355
+ if (isArray(res)) {
356
+ for (let i = res.length - 1; i >= 0; i--) {
357
+ if (res[i] === comparison[i]) {
358
+ res.splice(i, 1);
359
+ } else if (isObject(res[i]) && isObject(comparison[i])) {
360
+ res[i] = removePropsIfExisting(res[i] as Record<string, unknown>, (comparison as unknown as unknown[])[i] as Record<string, unknown>);
361
+ }
362
+ }
363
+ } else {
364
+ Object.keys(comparison).forEach(key => {
365
+ if (key in res) {
366
+ if (isObject(res[key]) && isObject(comparison[key])) {
367
+ res[key] = removePropsIfExisting(res[key], comparison[key]);
368
+ } else if (res[key] === comparison[key]) {
369
+ delete res[key];
370
+ }
371
+ }
372
+ });
373
+ }
374
+
375
+ return res;
376
+ }
package/src/util/os.ts ADDED
@@ -0,0 +1,13 @@
1
+ export function getOS() {
2
+ let OS = "Unknown";
3
+ if (navigator.userAgent.indexOf("Win") !== -1) OS = "Windows";
4
+ if (navigator.userAgent.indexOf("Mac") !== -1) OS = "MacOS";
5
+ if (navigator.userAgent.indexOf("X11") !== -1) OS = "UNIX";
6
+ if (navigator.userAgent.indexOf("Linux") !== -1) OS = "Linux";
7
+ return OS;
8
+ }
9
+
10
+ export function getAltSymbol() {
11
+ if (getOS() === "MacOS") return "⌥";
12
+ return "Alt";
13
+ }
@@ -0,0 +1,57 @@
1
+ import { EntityCollection, EntityReference } from "@rebasepro/types";
2
+ import { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from "./navigation_utils";
3
+ import { getSubcollections } from "./resolutions";
4
+
5
+ export function getParentReferencesFromPath(props: {
6
+ path: string,
7
+ collections: EntityCollection[] | undefined,
8
+ currentFullPath?: string,
9
+ }): EntityReference[] {
10
+
11
+ const {
12
+ path,
13
+ collections = [],
14
+ currentFullPath,
15
+ } = props;
16
+
17
+ const subpaths = removeInitialAndTrailingSlashes(path).split("/");
18
+ const subpathCombinations = getCollectionPathsCombinations(subpaths);
19
+
20
+ const result: EntityReference[] = [];
21
+ for (let i = 0; i < subpathCombinations.length; i++) {
22
+ const subpathCombination = subpathCombinations[i];
23
+
24
+ const collection: EntityCollection | undefined = collections && collections.find((entry) => entry.slug === subpathCombination);
25
+
26
+ // If we find a collection, we add the reference and continue
27
+ if (collection) {
28
+ const collectionPath = currentFullPath && currentFullPath.length > 0
29
+ ? (currentFullPath + "/" + collection.slug) // Use the current full path if provided
30
+ : collection.slug;
31
+
32
+ const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
33
+ const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
34
+ if (nextSegments.length > 0) {
35
+ const entityId = nextSegments[0];
36
+ const path = collectionPath + "/" + entityId;
37
+ result.push(new EntityReference({ id: entityId, path: collectionPath }));
38
+ if (nextSegments.length > 1) {
39
+ const newPath = nextSegments.slice(1).join("/");
40
+ if (!collection) {
41
+ throw Error("collection not found resolving path: " + collection);
42
+ }
43
+ if (collection.subcollections) {
44
+ result.push(...getParentReferencesFromPath({
45
+ path: newPath,
46
+ collections: getSubcollections(collection),
47
+ currentFullPath: path
48
+ }));
49
+ }
50
+ }
51
+ }
52
+ break;
53
+ }
54
+
55
+ }
56
+ return result;
57
+ }
@@ -0,0 +1,27 @@
1
+ export const COLLECTION_PATH_SEPARATOR = "::";
2
+
3
+ /**
4
+ * Remove the entity ids from a given path
5
+ * `products/B44RG6APH/locales` => `products::locales`
6
+ * @param path
7
+ */
8
+ export function stripCollectionPath(path: string): string {
9
+ return segmentsToStrippedPath(fullPathToCollectionSegments(path));
10
+ }
11
+
12
+ export function segmentsToStrippedPath(paths: string[]) {
13
+ if (paths.length === 1)
14
+ return paths[0];
15
+ return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);
16
+ }
17
+
18
+ /**
19
+ * Extract the collection path routes
20
+ * `products/B44RG6APH/locales` => [`products`, `locales`]
21
+ * @param path
22
+ */
23
+ export function fullPathToCollectionSegments(path: string): string[] {
24
+ return path
25
+ .split("/")
26
+ .filter((e, i) => i % 2 === 0);
27
+ }