@cravery/core 0.0.4 → 0.0.6

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 (77) hide show
  1. package/dist/lib/ai/cost.d.ts.map +1 -1
  2. package/dist/lib/ai/cost.js +10 -1
  3. package/dist/lib/ai/cost.js.map +1 -1
  4. package/dist/lib/ai/embedding.d.ts.map +1 -1
  5. package/dist/lib/ai/embedding.js +6 -1
  6. package/dist/lib/ai/embedding.js.map +1 -1
  7. package/dist/lib/errors/index.d.ts +31 -0
  8. package/dist/lib/errors/index.d.ts.map +1 -0
  9. package/dist/lib/errors/index.js +70 -0
  10. package/dist/lib/errors/index.js.map +1 -0
  11. package/dist/lib/index.d.ts +2 -0
  12. package/dist/lib/index.d.ts.map +1 -1
  13. package/dist/lib/index.js +2 -0
  14. package/dist/lib/index.js.map +1 -1
  15. package/dist/lib/repository/factory.d.ts +9 -0
  16. package/dist/lib/repository/factory.d.ts.map +1 -0
  17. package/dist/lib/repository/factory.js +16 -0
  18. package/dist/lib/repository/factory.js.map +1 -0
  19. package/dist/lib/repository/firestore.repository.d.ts.map +1 -1
  20. package/dist/lib/repository/firestore.repository.js +6 -3
  21. package/dist/lib/repository/firestore.repository.js.map +1 -1
  22. package/dist/lib/repository/index.d.ts +1 -0
  23. package/dist/lib/repository/index.d.ts.map +1 -1
  24. package/dist/lib/repository/index.js +1 -0
  25. package/dist/lib/repository/index.js.map +1 -1
  26. package/dist/lib/repository/rtdb.repository.d.ts.map +1 -1
  27. package/dist/lib/repository/rtdb.repository.js.map +1 -1
  28. package/dist/lib/repository/settings.repository.d.ts +2 -1
  29. package/dist/lib/repository/settings.repository.d.ts.map +1 -1
  30. package/dist/lib/repository/settings.repository.js +18 -0
  31. package/dist/lib/repository/settings.repository.js.map +1 -1
  32. package/dist/lib/storage.d.ts.map +1 -1
  33. package/dist/lib/storage.js +16 -0
  34. package/dist/lib/storage.js.map +1 -1
  35. package/dist/lib/utils/index.d.ts +2 -0
  36. package/dist/lib/utils/index.d.ts.map +1 -0
  37. package/dist/lib/utils/index.js +18 -0
  38. package/dist/lib/utils/index.js.map +1 -0
  39. package/dist/lib/utils/sanitize.d.ts +20 -0
  40. package/dist/lib/utils/sanitize.d.ts.map +1 -0
  41. package/dist/lib/utils/sanitize.js +40 -0
  42. package/dist/lib/utils/sanitize.js.map +1 -0
  43. package/dist/types/index.d.ts +1 -0
  44. package/dist/types/index.d.ts.map +1 -1
  45. package/dist/types/index.js +1 -0
  46. package/dist/types/index.js.map +1 -1
  47. package/dist/types/repository.d.ts.map +1 -1
  48. package/dist/types/response.d.ts +16 -0
  49. package/dist/types/response.d.ts.map +1 -0
  50. package/dist/types/response.js +14 -0
  51. package/dist/types/response.js.map +1 -0
  52. package/dist/types/settings.d.ts +2 -14
  53. package/dist/types/settings.d.ts.map +1 -1
  54. package/dist/types/settings.js +3 -37
  55. package/dist/types/settings.js.map +1 -1
  56. package/dist/types/user.d.ts.map +1 -1
  57. package/package.json +1 -1
  58. package/src/lib/ai/cost.ts +10 -1
  59. package/src/lib/ai/embedding.ts +6 -1
  60. package/src/lib/errors/index.ts +79 -0
  61. package/src/lib/index.ts +2 -0
  62. package/src/lib/repository/errors.ts +37 -37
  63. package/src/lib/repository/factory.ts +14 -0
  64. package/src/lib/repository/firestore.repository.ts +633 -607
  65. package/src/lib/repository/index.ts +7 -6
  66. package/src/lib/repository/profile.repository.ts +51 -51
  67. package/src/lib/repository/rtdb.repository.ts +67 -68
  68. package/src/lib/repository/settings.repository.ts +57 -38
  69. package/src/lib/repository/user.repository.ts +44 -44
  70. package/src/lib/storage.ts +18 -0
  71. package/src/lib/utils/index.ts +1 -0
  72. package/src/lib/utils/sanitize.ts +38 -0
  73. package/src/types/index.ts +1 -0
  74. package/src/types/repository.ts +140 -115
  75. package/src/types/response.ts +30 -0
  76. package/src/types/settings.ts +44 -85
  77. package/src/types/user.ts +4 -1
@@ -1,6 +1,7 @@
1
- export * from "./errors";
2
- export * from "./firestore.repository";
3
- export * from "./rtdb.repository";
4
- export * from "./user.repository";
5
- export * from "./profile.repository";
6
- export * from "./settings.repository";
1
+ export * from "./errors";
2
+ export * from "./factory";
3
+ export * from "./firestore.repository";
4
+ export * from "./rtdb.repository";
5
+ export * from "./user.repository";
6
+ export * from "./profile.repository";
7
+ export * from "./settings.repository";
@@ -1,51 +1,51 @@
1
- import { Firestore } from "firebase-admin/firestore";
2
- import { FirestoreRepository } from "./firestore.repository";
3
- import type { Profile } from "../../types/profile";
4
- import { ProfileSchema } from "../../types/profile";
5
- import { Collections } from "../../config/collections";
6
- import { RepositoryError, RepositoryErrorCode } from "./errors";
7
-
8
- export class ProfileRepository extends FirestoreRepository<Profile> {
9
- constructor(firestore: Firestore) {
10
- super(firestore, Collections.Profiles, {
11
- enableTimestamps: true,
12
- enableSoftDelete: true,
13
- validateOnWrite: true,
14
- });
15
- }
16
-
17
- protected validate(data: Partial<Profile>): void {
18
- const result = ProfileSchema.partial().safeParse(data);
19
- if (!result.success) {
20
- throw new RepositoryError(
21
- RepositoryErrorCode.VALIDATION_ERROR,
22
- "Profile validation failed",
23
- { errors: result.error.issues },
24
- );
25
- }
26
- }
27
-
28
- async findByHandle(handle: string): Promise<Profile | null> {
29
- const results = await this.findWhere(
30
- [{ field: "handle", op: "==", value: handle }],
31
- { limit: 1 },
32
- );
33
- return results[0] ?? null;
34
- }
35
-
36
- async findByUserId(userId: string): Promise<Profile | null> {
37
- return this.findById(userId);
38
- }
39
-
40
- async createWithUserId(
41
- userId: string,
42
- data: Omit<Profile, "id">,
43
- ): Promise<Profile> {
44
- return this.create(data, userId);
45
- }
46
-
47
- async handleExists(handle: string): Promise<boolean> {
48
- const profile = await this.findByHandle(handle);
49
- return profile !== null;
50
- }
51
- }
1
+ import { Firestore } from "firebase-admin/firestore";
2
+ import { FirestoreRepository } from "./firestore.repository";
3
+ import type { Profile } from "../../types/profile";
4
+ import { ProfileSchema } from "../../types/profile";
5
+ import { Collections } from "../../config/collections";
6
+ import { RepositoryError, RepositoryErrorCode } from "./errors";
7
+
8
+ export class ProfileRepository extends FirestoreRepository<Profile> {
9
+ constructor(firestore: Firestore) {
10
+ super(firestore, Collections.Profiles, {
11
+ enableTimestamps: true,
12
+ enableSoftDelete: true,
13
+ validateOnWrite: true,
14
+ });
15
+ }
16
+
17
+ protected validate(data: Partial<Profile>): void {
18
+ const result = ProfileSchema.partial().safeParse(data);
19
+ if (!result.success) {
20
+ throw new RepositoryError(
21
+ RepositoryErrorCode.VALIDATION_ERROR,
22
+ "Profile validation failed",
23
+ { errors: result.error.issues },
24
+ );
25
+ }
26
+ }
27
+
28
+ async findByHandle(handle: string): Promise<Profile | null> {
29
+ const results = await this.findWhere(
30
+ [{ field: "handle", op: "==", value: handle }],
31
+ { limit: 1 },
32
+ );
33
+ return results[0] ?? null;
34
+ }
35
+
36
+ async findByUserId(userId: string): Promise<Profile | null> {
37
+ return this.findById(userId);
38
+ }
39
+
40
+ async createWithUserId(
41
+ userId: string,
42
+ data: Omit<Profile, "id">,
43
+ ): Promise<Profile> {
44
+ return this.create(data, userId);
45
+ }
46
+
47
+ async handleExists(handle: string): Promise<boolean> {
48
+ const profile = await this.findByHandle(handle);
49
+ return profile !== null;
50
+ }
51
+ }
@@ -1,68 +1,67 @@
1
- import { Database, Reference } from "firebase-admin/database";
2
- import type { IRTDBRepository } from "../../types/repository";
3
-
4
- export abstract class RTDBRepository<T extends { id: string }>
5
- implements IRTDBRepository<T>
6
- {
7
- protected readonly ref: Reference;
8
-
9
- constructor(
10
- protected readonly database: Database,
11
- protected readonly path: string,
12
- ) {
13
- this.ref = database.ref(path);
14
- }
15
-
16
- protected toDocument(entity: Partial<T>): Record<string, unknown> {
17
- return { ...entity };
18
- }
19
-
20
- protected fromDocument(id: string, data: Record<string, unknown>): T {
21
- return { id, ...data } as T;
22
- }
23
-
24
- async get(id: string): Promise<T | null> {
25
- const snapshot = await this.ref.child(id).get();
26
- if (!snapshot.exists()) return null;
27
- return this.fromDocument(id, snapshot.val());
28
- }
29
-
30
- async getAll(): Promise<T[]> {
31
- const snapshot = await this.ref.get();
32
- if (!snapshot.exists()) return [];
33
-
34
- const results: T[] = [];
35
- snapshot.forEach((child) => {
36
- results.push(this.fromDocument(child.key!, child.val()));
37
- });
38
- return results;
39
- }
40
-
41
- async set(id: string, data: T): Promise<void> {
42
- const docData = this.toDocument(data);
43
- await this.ref.child(id).set(docData);
44
- }
45
-
46
- async update(id: string, data: Partial<T>): Promise<void> {
47
- const docData = this.toDocument(data);
48
- await this.ref.child(id).update(docData);
49
- }
50
-
51
- async remove(id: string): Promise<void> {
52
- await this.ref.child(id).remove();
53
- }
54
-
55
- async increment(id: string, field: string, delta: number = 1): Promise<void> {
56
- const fieldRef = this.ref.child(id).child(field);
57
- await fieldRef.transaction((current) => (current || 0) + delta);
58
- }
59
-
60
- async decrement(id: string, field: string, delta: number = 1): Promise<void> {
61
- await this.increment(id, field, -delta);
62
- }
63
-
64
- async multiUpdate(updates: Record<string, unknown>): Promise<void> {
65
- await this.ref.update(updates);
66
- }
67
-
68
- }
1
+ import { Database, Reference } from "firebase-admin/database";
2
+ import type { IRTDBRepository } from "../../types/repository";
3
+
4
+ export abstract class RTDBRepository<
5
+ T extends { id: string },
6
+ > implements IRTDBRepository<T> {
7
+ protected readonly ref: Reference;
8
+
9
+ constructor(
10
+ protected readonly database: Database,
11
+ protected readonly path: string,
12
+ ) {
13
+ this.ref = database.ref(path);
14
+ }
15
+
16
+ protected toDocument(entity: Partial<T>): Record<string, unknown> {
17
+ return { ...entity };
18
+ }
19
+
20
+ protected fromDocument(id: string, data: Record<string, unknown>): T {
21
+ return { id, ...data } as T;
22
+ }
23
+
24
+ async get(id: string): Promise<T | null> {
25
+ const snapshot = await this.ref.child(id).get();
26
+ if (!snapshot.exists()) return null;
27
+ return this.fromDocument(id, snapshot.val());
28
+ }
29
+
30
+ async getAll(): Promise<T[]> {
31
+ const snapshot = await this.ref.get();
32
+ if (!snapshot.exists()) return [];
33
+
34
+ const results: T[] = [];
35
+ snapshot.forEach((child) => {
36
+ results.push(this.fromDocument(child.key!, child.val()));
37
+ });
38
+ return results;
39
+ }
40
+
41
+ async set(id: string, data: T): Promise<void> {
42
+ const docData = this.toDocument(data);
43
+ await this.ref.child(id).set(docData);
44
+ }
45
+
46
+ async update(id: string, data: Partial<T>): Promise<void> {
47
+ const docData = this.toDocument(data);
48
+ await this.ref.child(id).update(docData);
49
+ }
50
+
51
+ async remove(id: string): Promise<void> {
52
+ await this.ref.child(id).remove();
53
+ }
54
+
55
+ async increment(id: string, field: string, delta: number = 1): Promise<void> {
56
+ const fieldRef = this.ref.child(id).child(field);
57
+ await fieldRef.transaction((current) => (current || 0) + delta);
58
+ }
59
+
60
+ async decrement(id: string, field: string, delta: number = 1): Promise<void> {
61
+ await this.increment(id, field, -delta);
62
+ }
63
+
64
+ async multiUpdate(updates: Record<string, unknown>): Promise<void> {
65
+ await this.ref.update(updates);
66
+ }
67
+ }
@@ -1,38 +1,57 @@
1
- import { Firestore } from "firebase-admin/firestore";
2
- import { FirestoreRepository } from "./firestore.repository";
3
- import type { Settings } from "../../types/settings";
4
- import { SettingsSchema } from "../../types/settings";
5
- import { Collections } from "../../config/collections";
6
- import { RepositoryError, RepositoryErrorCode } from "./errors";
7
-
8
- export class SettingsRepository extends FirestoreRepository<Settings> {
9
- constructor(firestore: Firestore) {
10
- super(firestore, Collections.Settings, {
11
- enableTimestamps: true,
12
- enableSoftDelete: false,
13
- validateOnWrite: true,
14
- });
15
- }
16
-
17
- protected validate(data: Partial<Settings>): void {
18
- const result = SettingsSchema.partial().safeParse(data);
19
- if (!result.success) {
20
- throw new RepositoryError(
21
- RepositoryErrorCode.VALIDATION_ERROR,
22
- "Settings validation failed",
23
- { errors: result.error.issues },
24
- );
25
- }
26
- }
27
-
28
- async findByUserId(userId: string): Promise<Settings | null> {
29
- return this.findById(userId);
30
- }
31
-
32
- async createForUser(
33
- userId: string,
34
- data: Omit<Settings, "id">,
35
- ): Promise<Settings> {
36
- return this.create(data, userId);
37
- }
38
- }
1
+ import { Firestore } from "firebase-admin/firestore";
2
+ import { FirestoreRepository } from "./firestore.repository";
3
+ import type { Settings, SettingsInput } from "../../types/settings";
4
+ import { SettingsSchema } from "../../types/settings";
5
+ import { Collections } from "../../config/collections";
6
+ import { RepositoryError, RepositoryErrorCode } from "./errors";
7
+
8
+ export class SettingsRepository extends FirestoreRepository<Settings> {
9
+ constructor(firestore: Firestore) {
10
+ super(firestore, Collections.Settings, {
11
+ enableTimestamps: true,
12
+ enableSoftDelete: false,
13
+ validateOnWrite: true,
14
+ });
15
+ }
16
+
17
+ protected validate(data: Partial<Settings>): void {
18
+ const result = SettingsSchema.partial().safeParse(data);
19
+ if (!result.success) {
20
+ throw new RepositoryError(
21
+ RepositoryErrorCode.VALIDATION_ERROR,
22
+ "Settings validation failed",
23
+ { errors: result.error.issues },
24
+ );
25
+ }
26
+ }
27
+
28
+ async findByUserId(userId: string): Promise<Settings | null> {
29
+ return this.findById(userId);
30
+ }
31
+
32
+ async createForUser(
33
+ userId: string,
34
+ data: Omit<Settings, "id">,
35
+ ): Promise<Settings> {
36
+ return this.create(data, userId);
37
+ }
38
+
39
+ static createDefaultSettings(): SettingsInput {
40
+ return {
41
+ allergens: [],
42
+ dietaryTags: [],
43
+ cuisines: [],
44
+ excludedIngredients: [],
45
+ locale: "en",
46
+ temperatureUnit: "celsius",
47
+ measurementSystem: "metric",
48
+ theme: "system",
49
+ notifications: {
50
+ email: true,
51
+ push: true,
52
+ marketing: false,
53
+ weeklyDigest: true,
54
+ },
55
+ };
56
+ }
57
+ }
@@ -1,44 +1,44 @@
1
- import { Firestore } from "firebase-admin/firestore";
2
- import { FirestoreRepository } from "./firestore.repository";
3
- import type { User } from "../../types/user";
4
- import { UserSchema } from "../../types/user";
5
- import { Collections } from "../../config/collections";
6
- import { RepositoryError, RepositoryErrorCode } from "./errors";
7
-
8
- export class UserRepository extends FirestoreRepository<User> {
9
- constructor(firestore: Firestore) {
10
- super(firestore, Collections.Users, {
11
- enableTimestamps: true,
12
- enableSoftDelete: true,
13
- validateOnWrite: true,
14
- });
15
- }
16
-
17
- protected validate(data: Partial<User>): void {
18
- const result = UserSchema.partial().safeParse(data);
19
- if (!result.success) {
20
- throw new RepositoryError(
21
- RepositoryErrorCode.VALIDATION_ERROR,
22
- "User validation failed",
23
- { errors: result.error.issues },
24
- );
25
- }
26
- }
27
-
28
- async findByEmail(email: string): Promise<User | null> {
29
- const results = await this.findWhere(
30
- [{ field: "email", op: "==", value: email }],
31
- { limit: 1 },
32
- );
33
- return results[0] ?? null;
34
- }
35
-
36
- async createWithId(uid: string, data: Omit<User, "id">): Promise<User> {
37
- return this.create(data, uid);
38
- }
39
-
40
- async emailExists(email: string): Promise<boolean> {
41
- const user = await this.findByEmail(email);
42
- return user !== null;
43
- }
44
- }
1
+ import { Firestore } from "firebase-admin/firestore";
2
+ import { FirestoreRepository } from "./firestore.repository";
3
+ import type { User } from "../../types/user";
4
+ import { UserSchema } from "../../types/user";
5
+ import { Collections } from "../../config/collections";
6
+ import { RepositoryError, RepositoryErrorCode } from "./errors";
7
+
8
+ export class UserRepository extends FirestoreRepository<User> {
9
+ constructor(firestore: Firestore) {
10
+ super(firestore, Collections.Users, {
11
+ enableTimestamps: true,
12
+ enableSoftDelete: true,
13
+ validateOnWrite: true,
14
+ });
15
+ }
16
+
17
+ protected validate(data: Partial<User>): void {
18
+ const result = UserSchema.partial().safeParse(data);
19
+ if (!result.success) {
20
+ throw new RepositoryError(
21
+ RepositoryErrorCode.VALIDATION_ERROR,
22
+ "User validation failed",
23
+ { errors: result.error.issues },
24
+ );
25
+ }
26
+ }
27
+
28
+ async findByEmail(email: string): Promise<User | null> {
29
+ const results = await this.findWhere(
30
+ [{ field: "email", op: "==", value: email }],
31
+ { limit: 1 },
32
+ );
33
+ return results[0] ?? null;
34
+ }
35
+
36
+ async createWithId(uid: string, data: Omit<User, "id">): Promise<User> {
37
+ return this.create(data, uid);
38
+ }
39
+
40
+ async emailExists(email: string): Promise<boolean> {
41
+ const user = await this.findByEmail(email);
42
+ return user !== null;
43
+ }
44
+ }
@@ -1,15 +1,33 @@
1
1
  import { getStorage } from "firebase-admin/storage";
2
+ import { ValidationError } from "./errors";
2
3
 
3
4
  export interface UploadImageResult {
4
5
  url: string;
5
6
  path: string;
6
7
  }
7
8
 
9
+ function validateStoragePath(path: string): void {
10
+ if (!path || path.length === 0) {
11
+ throw new ValidationError("Storage path cannot be empty");
12
+ }
13
+ if (path.includes("..")) {
14
+ throw new ValidationError("Storage path cannot contain '..'", { path });
15
+ }
16
+ if (path.startsWith("/")) {
17
+ throw new ValidationError("Storage path cannot start with '/'", { path });
18
+ }
19
+ if (path.includes("//")) {
20
+ throw new ValidationError("Storage path cannot contain '//'", { path });
21
+ }
22
+ }
23
+
8
24
  export const uploadImageToStorage = async (
9
25
  base64Data: string,
10
26
  path: string,
11
27
  contentType: string = "image/png",
12
28
  ): Promise<UploadImageResult> => {
29
+ validateStoragePath(path);
30
+
13
31
  try {
14
32
  const bucket = getStorage().bucket();
15
33
  const buffer = Buffer.from(base64Data, "base64");
@@ -0,0 +1 @@
1
+ export * from "./sanitize";
@@ -0,0 +1,38 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Removes HTML tags and script content from a string.
5
+ * Use for text fields that should not contain HTML (descriptions, bios, etc.)
6
+ */
7
+ export function sanitizeText(text: string): string {
8
+ return text
9
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
10
+ .replace(/<[^>]*>/g, "")
11
+ .trim();
12
+ }
13
+
14
+ /**
15
+ * Creates a Zod string schema that sanitizes HTML on transformation.
16
+ * Use in schemas where text input needs to be cleaned.
17
+ *
18
+ * @example
19
+ * const BioSchema = sanitizedString(z.string().max(280));
20
+ */
21
+ export function sanitizedString<T extends z.ZodString>(schema: T) {
22
+ return schema.transform(sanitizeText);
23
+ }
24
+
25
+ /**
26
+ * Escapes HTML special characters to prevent XSS.
27
+ * Use when HTML needs to be displayed as text.
28
+ */
29
+ export function escapeHtml(text: string): string {
30
+ const htmlEscapes: Record<string, string> = {
31
+ "&": "&amp;",
32
+ "<": "&lt;",
33
+ ">": "&gt;",
34
+ '"': "&quot;",
35
+ "'": "&#39;",
36
+ };
37
+ return text.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
38
+ }
@@ -7,6 +7,7 @@ export * from "./nutrition";
7
7
  export * from "./profile";
8
8
  export * from "./recipe";
9
9
  export * from "./repository";
10
+ export * from "./response";
10
11
  export * from "./settings";
11
12
  export * from "./subscription";
12
13
  export * from "./temperature";