@dimah-s3/db 2.0.0-beta.1 → 2.0.0-beta.2

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 (66) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +12 -16
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/db-client.d.ts +1 -1
  5. package/dist/client/db-client.d.ts.map +1 -1
  6. package/dist/client/db-object-source.d.ts +5 -4
  7. package/dist/client/db-object-source.d.ts.map +1 -1
  8. package/dist/client/index.d.ts +1 -1
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +27 -12
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/drizzle/mysql.d.ts +44 -12
  13. package/dist/drizzle/mysql.d.ts.map +1 -1
  14. package/dist/drizzle/mysql.js +11 -8
  15. package/dist/drizzle/mysql.js.map +1 -1
  16. package/dist/drizzle/pg.d.ts +42 -12
  17. package/dist/drizzle/pg.d.ts.map +1 -1
  18. package/dist/drizzle/pg.js +13 -7
  19. package/dist/drizzle/pg.js.map +1 -1
  20. package/dist/drizzle/shared.d.ts +1 -1
  21. package/dist/drizzle/sqlite.d.ts +44 -12
  22. package/dist/drizzle/sqlite.d.ts.map +1 -1
  23. package/dist/drizzle/sqlite.js +13 -7
  24. package/dist/drizzle/sqlite.js.map +1 -1
  25. package/dist/folder-path.d.ts +9 -2
  26. package/dist/folder-path.d.ts.map +1 -1
  27. package/dist/fuma-db.d.ts +6 -5
  28. package/dist/fuma-db.d.ts.map +1 -1
  29. package/dist/index.js +347 -170
  30. package/dist/index.js.map +1 -1
  31. package/dist/plugin/create-database-endpoints.d.ts +38 -18
  32. package/dist/plugin/create-database-endpoints.d.ts.map +1 -1
  33. package/dist/plugin/create-database-lifecycle-hooks.d.ts +1 -1
  34. package/dist/plugin/create-database-lifecycle-hooks.d.ts.map +1 -1
  35. package/dist/plugin/db.d.ts.map +1 -1
  36. package/dist/plugin/object-access.d.ts +1 -1
  37. package/dist/plugin/object-access.d.ts.map +1 -1
  38. package/dist/plugin/public-stores.d.ts +4 -7
  39. package/dist/plugin/public-stores.d.ts.map +1 -1
  40. package/dist/plugin/schemas.d.ts +21 -12
  41. package/dist/plugin/schemas.d.ts.map +1 -1
  42. package/dist/plugin/to-db-client-object.d.ts.map +1 -1
  43. package/dist/schema/schema.d.ts +9 -8
  44. package/dist/schema/schema.d.ts.map +1 -1
  45. package/dist/store/folder-store.d.ts +41 -14
  46. package/dist/store/folder-store.d.ts.map +1 -1
  47. package/dist/store/list-cursor.d.ts +1 -1
  48. package/dist/store/list-cursor.d.ts.map +1 -1
  49. package/dist/store/map-row.d.ts +1 -1
  50. package/dist/store/map-row.d.ts.map +1 -1
  51. package/dist/store/object-store.d.ts +5 -5
  52. package/dist/store/object-store.d.ts.map +1 -1
  53. package/dist/types/client.d.ts +47 -18
  54. package/dist/types/client.d.ts.map +1 -1
  55. package/dist/types/plugin.d.ts +6 -1
  56. package/dist/types/plugin.d.ts.map +1 -1
  57. package/dist/types/storage-object.d.ts +8 -7
  58. package/dist/types/storage-object.d.ts.map +1 -1
  59. package/package.json +5 -5
  60. package/prisma/dimah-s3.prisma +14 -13
  61. package/sql/mysql.sql +12 -11
  62. package/sql/pg.sql +10 -10
  63. package/sql/sqlite.sql +10 -9
  64. package/src/drizzle/mysql.ts +10 -7
  65. package/src/drizzle/pg.ts +12 -6
  66. package/src/drizzle/sqlite.ts +12 -6
package/dist/index.js CHANGED
@@ -18,8 +18,8 @@ var storageObject = table("storage_object", {
18
18
  key: column("key", "string"),
19
19
  /** Named dimah-s3 route that created the object. */
20
20
  route: column("route", "string"),
21
- /** Logical folder path. `null` is the root. */
22
- folder: column("folder", "string").nullable(),
21
+ /** Folder that holds the object. `null` is the root. */
22
+ folderId: column("folder_id", "string").nullable(),
23
23
  filename: column("filename", "string"),
24
24
  contentType: column("content_type", "string").nullable(),
25
25
  /** Verified size from HeadObject, set on confirm. */
@@ -47,19 +47,20 @@ var storageObject = table("storage_object", {
47
47
  var storageFolder = table("storage_folder", {
48
48
  id: idColumn("id", "varchar(255)").defaultTo$("auto"),
49
49
  scope: column("scope", "string"),
50
- /** Full folder path. */
51
- path: column("path", "string"),
52
- /** Path of the containing folder. `null` is the root. */
53
- parent: column("parent", "string").nullable(),
50
+ /** Id of the containing folder. `""` is the root. */
51
+ parentId: column("parent_id", "string"),
54
52
  /** Last segment of `path`. */
55
53
  name: column("name", "string"),
56
- createdAt: column("created_at", "timestamp").defaultTo$("now")
57
- }).unique("storage_folder_scope_path_uk", ["scope", "path"]);
54
+ /** Full folder path. */
55
+ path: column("path", "string"),
56
+ createdAt: column("created_at", "timestamp").defaultTo$("now"),
57
+ updatedAt: column("updated_at", "timestamp").defaultTo$("now")
58
+ }).unique("storage_folder_scope_path_uk", ["scope", "path"]).unique("storage_folder_scope_parent_name_uk", ["scope", "parentId", "name"]);
58
59
  var schemaIndexes = [
59
60
  {
60
61
  name: "storage_object_scope_folder_idx",
61
62
  table: "storage_object",
62
- columns: ["scope", "status", "folder", "created_at"]
63
+ columns: ["scope", "status", "folder_id", "created_at"]
63
64
  },
64
65
  {
65
66
  name: "storage_object_scope_updated_idx",
@@ -80,11 +81,6 @@ var schemaIndexes = [
80
81
  name: "storage_object_status_expires_idx",
81
82
  table: "storage_object",
82
83
  columns: ["status", "expires_at"]
83
- },
84
- {
85
- name: "storage_folder_scope_parent_idx",
86
- table: "storage_folder",
87
- columns: ["scope", "parent"]
88
84
  }
89
85
  ];
90
86
  var custom = (sql) => ({ type: "custom", sql });
@@ -94,7 +90,7 @@ var predecessor = schema({
94
90
  tables: {}
95
91
  });
96
92
  var dbSchema = schema({
97
- version: "2.0.0",
93
+ version: "2.1.0",
98
94
  tables: {
99
95
  storageObject,
100
96
  storageFolder
@@ -123,9 +119,9 @@ var INVALID_CHARACTER = /[\p{Cc}\p{Cs}]/u;
123
119
  function characterCount(value) {
124
120
  return Array.from(value).length;
125
121
  }
126
- function isValidName(name) {
122
+ function isFolderName(name) {
127
123
  const length = characterCount(name);
128
- return length >= 1 && length <= FOLDER_NAME_MAX_LENGTH && name !== "." && name !== ".." && !INVALID_CHARACTER.test(name);
124
+ return length >= 1 && length <= FOLDER_NAME_MAX_LENGTH && name !== "." && name !== ".." && !name.includes("/") && !INVALID_CHARACTER.test(name);
129
125
  }
130
126
  function normalizeFolderPath(path) {
131
127
  if (!path.isWellFormed()) return null;
@@ -133,24 +129,14 @@ function normalizeFolderPath(path) {
133
129
  if (characterCount(normalized) > FOLDER_PATH_MAX_LENGTH) return null;
134
130
  const names = normalized.split("/");
135
131
  if (names.length > FOLDER_MAX_DEPTH) return null;
136
- return names.every(isValidName) ? normalized : null;
137
- }
138
- function parseFolder(value) {
139
- if (value === "") return null;
140
- const path = normalizeFolderPath(value);
141
- if (path === null) throw s3Error("FOLDER_INVALID");
142
- return path;
143
- }
144
- function parentFolderPath(path) {
145
- const index = path.lastIndexOf("/");
146
- return index === -1 ? null : path.slice(0, index);
132
+ return names.every(isFolderName) ? normalized : null;
147
133
  }
148
- function folderName(path) {
149
- return path.slice(path.lastIndexOf("/") + 1);
134
+ function childFolderPath(parent, name) {
135
+ if (!isFolderName(name)) return null;
136
+ return normalizeFolderPath(joinFolderPath(parent, name));
150
137
  }
151
- function folderAncestors(path) {
152
- const segments = path.split("/");
153
- return segments.map((_, index) => segments.slice(0, index + 1).join("/"));
138
+ function joinFolderPath(parent, name) {
139
+ return parent === null ? name : `${parent}/${name}`;
154
140
  }
155
141
  var DEFAULT_LIST_SORT = {
156
142
  field: "createdAt",
@@ -159,8 +145,8 @@ var DEFAULT_LIST_SORT = {
159
145
  var decoder = new TextDecoder();
160
146
  function fingerprint(filters) {
161
147
  const text = JSON.stringify([
162
- filters.folder === void 0,
163
- filters.folder ?? null,
148
+ filters.folderId === void 0,
149
+ filters.folderId ?? null,
164
150
  filters.search ?? null,
165
151
  filters.status,
166
152
  filters.route ?? null,
@@ -223,7 +209,7 @@ function mapStorageObjectRow(row) {
223
209
  bucket: row.bucket,
224
210
  key: row.key,
225
211
  route: row.route,
226
- folder: row.folder,
212
+ folderId: row.folderId,
227
213
  filename: row.filename,
228
214
  contentType: row.contentType,
229
215
  size: toNumber(row.size),
@@ -304,9 +290,9 @@ function filterConditions(b, filter, now) {
304
290
  b("scope", "=", filter.scope),
305
291
  status === "pending" ? b.and(b("status", "=", "pending"), b("expiresAt", ">=", now)) : b("status", "=", status)
306
292
  ];
307
- if (filter.folder === null) parts.push(b.isNull("folder"));
308
- else if (filter.folder !== void 0) {
309
- parts.push(b("folder", "=", filter.folder));
293
+ if (filter.folderId === null) parts.push(b.isNull("folderId"));
294
+ else if (filter.folderId !== void 0) {
295
+ parts.push(b("folderId", "=", filter.folderId));
310
296
  }
311
297
  if (filter.route) parts.push(b("route", "=", filter.route));
312
298
  if (filter.contentType?.endsWith("/*")) {
@@ -345,7 +331,7 @@ function createObjectStore(getOrm) {
345
331
  const after = direction === "desc" ? "<" : ">";
346
332
  const nullable = field === "size";
347
333
  const filters = {
348
- folder: input.folder,
334
+ folderId: input.folderId,
349
335
  search: input.search || void 0,
350
336
  status: input.status ?? "active",
351
337
  route: input.route || void 0,
@@ -462,7 +448,7 @@ function createObjectStore(getOrm) {
462
448
  ...ref,
463
449
  scope: input.scope,
464
450
  route: input.route,
465
- folder: input.folder,
451
+ folderId: input.folderId,
466
452
  filename: input.filename,
467
453
  contentType: input.contentType ?? null,
468
454
  size: null,
@@ -549,7 +535,7 @@ function createObjectStore(getOrm) {
549
535
  ),
550
536
  set: {
551
537
  ...input.filename !== void 0 && { filename: input.filename },
552
- ...input.folder !== void 0 && { folder: input.folder },
538
+ ...input.folderId !== void 0 && { folderId: input.folderId },
553
539
  ...input.attributes !== void 0 && {
554
540
  attributes: input.attributes
555
541
  },
@@ -658,72 +644,121 @@ function createObjectStore(getOrm) {
658
644
 
659
645
  // src/store/folder-store.ts
660
646
  var DEFAULT_FOLDER_CHILDREN_LIMIT = 1e3;
661
- function insertFolder(orm, scope, path) {
662
- return orm.create("storageFolder", {
663
- scope,
664
- path,
665
- parent: parentFolderPath(path),
666
- name: folderName(path),
667
- createdAt: /* @__PURE__ */ new Date()
668
- });
647
+ function isUniqueViolation(error) {
648
+ if (typeof error !== "object" || error === null) return false;
649
+ const code = "code" in error ? String(error.code) : "";
650
+ if (code === "23505" || code === "ER_DUP_ENTRY") return true;
651
+ const message = error instanceof Error ? error.message : "";
652
+ return /unique/i.test(message);
653
+ }
654
+ function storedParent(parentId) {
655
+ return parentId ?? "";
656
+ }
657
+ function readParent(parentId) {
658
+ return parentId === "" ? null : parentId;
659
+ }
660
+ function mapFolder(row) {
661
+ return {
662
+ id: row.id,
663
+ scope: row.scope,
664
+ parentId: readParent(row.parentId),
665
+ name: row.name,
666
+ path: row.path,
667
+ createdAt: row.createdAt,
668
+ updatedAt: row.updatedAt
669
+ };
669
670
  }
670
671
  function createFolderStore(getOrm) {
671
- const find = async (scope, path) => {
672
+ const find = async (scope, id) => {
672
673
  const orm = await getOrm();
673
- return orm.findFirst("storageFolder", {
674
- where: (b) => b.and(b("scope", "=", scope), b("path", "=", path))
674
+ const row = await orm.findFirst("storageFolder", {
675
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id))
675
676
  });
677
+ return row ? mapFolder(row) : null;
676
678
  };
677
- const insertMissing = async (scope, path) => {
678
- const existing = await find(scope, path);
679
- if (existing) return existing;
680
- try {
681
- return await insertFolder(await getOrm(), scope, path);
682
- } catch (error) {
683
- const raced = await find(scope, path);
684
- if (raced) return raced;
685
- throw error;
686
- }
687
- };
688
- const ensure = async (scope, path) => {
689
- if (path === null) return;
690
- const ancestors = folderAncestors(path);
679
+ const findNamed = async (scope, parentId, name) => {
691
680
  const orm = await getOrm();
692
- const present = new Set(
693
- (await orm.findMany("storageFolder", {
694
- select: ["path"],
695
- where: (b) => b.and(b("scope", "=", scope), b("path", "in", ancestors))
696
- })).map((folder) => folder.path)
697
- );
698
- for (const ancestor of ancestors) {
699
- if (!present.has(ancestor)) await insertMissing(scope, ancestor);
681
+ const row = await orm.findFirst("storageFolder", {
682
+ where: (b) => b.and(
683
+ b("scope", "=", scope),
684
+ b("parentId", "=", storedParent(parentId)),
685
+ b("name", "=", name)
686
+ )
687
+ });
688
+ return row ? mapFolder(row) : null;
689
+ };
690
+ const insertFolder = async (orm, folder) => {
691
+ const now = /* @__PURE__ */ new Date();
692
+ const row = await orm.create("storageFolder", {
693
+ ...folder.id !== void 0 && { id: folder.id },
694
+ scope: folder.scope,
695
+ parentId: storedParent(folder.parentId),
696
+ name: folder.name,
697
+ path: folder.path,
698
+ createdAt: folder.createdAt ?? now,
699
+ updatedAt: folder.updatedAt ?? now
700
+ });
701
+ return mapFolder(row);
702
+ };
703
+ const destination = async (scope, parentId, folderId) => {
704
+ if (parentId === null) return null;
705
+ if (parentId === folderId) throw s3Error("FOLDER_INVALID");
706
+ const parent = await find(scope, parentId);
707
+ if (!parent) throw s3Error("FOLDER_NOT_FOUND");
708
+ if (folderId !== void 0) {
709
+ let cursor = parent;
710
+ const seen = /* @__PURE__ */ new Set();
711
+ while (cursor && !seen.has(cursor.id)) {
712
+ if (cursor.id === folderId) throw s3Error("FOLDER_INVALID");
713
+ seen.add(cursor.id);
714
+ cursor = cursor.parentId ? await find(scope, cursor.parentId) : null;
715
+ }
700
716
  }
717
+ return parent;
701
718
  };
702
- const countContents = async (scope, path) => {
719
+ const countContents = async (scope, id) => {
703
720
  const orm = await getOrm();
704
721
  const now = /* @__PURE__ */ new Date();
705
722
  const [folders, objects] = await Promise.all([
706
723
  orm.count("storageFolder", {
707
- where: (b) => b.and(b("scope", "=", scope), b("parent", "=", path))
724
+ where: (b) => b.and(b("scope", "=", scope), b("parentId", "=", id))
708
725
  }),
709
726
  orm.count("storageObject", {
710
727
  where: (b) => b.and(
711
728
  b("scope", "=", scope),
712
- b("folder", "=", path),
729
+ b("folderId", "=", id),
713
730
  liveObject(b, now)
714
731
  )
715
732
  })
716
733
  ]);
717
734
  return folders + objects;
718
735
  };
736
+ const descendants = async (scope, path) => {
737
+ const orm = await getOrm();
738
+ const rows = await orm.findMany("storageFolder", {
739
+ where: (b) => b.and(b("scope", "=", scope), b("path", "starts with", `${path}/`)),
740
+ orderBy: [["id", "asc"]]
741
+ });
742
+ return rows.map(mapFolder);
743
+ };
744
+ const retain = async (folder) => {
745
+ if (await find(folder.scope, folder.id)) return;
746
+ const orm = await getOrm();
747
+ try {
748
+ await insertFolder(orm, folder);
749
+ } catch (error) {
750
+ if (await find(folder.scope, folder.id)) return;
751
+ throw error;
752
+ }
753
+ };
719
754
  return {
720
755
  find,
721
- async children(scope, parent, options = {}) {
756
+ async children(scope, parentId, options = {}) {
722
757
  const orm = await getOrm();
723
- return orm.findMany("storageFolder", {
758
+ const rows = await orm.findMany("storageFolder", {
724
759
  where: (b) => b.and(
725
760
  b("scope", "=", scope),
726
- parent === null ? b.isNull("parent") : b("parent", "=", parent)
761
+ b("parentId", "=", storedParent(parentId))
727
762
  ),
728
763
  orderBy: [
729
764
  ["name", "asc"],
@@ -731,33 +766,104 @@ function createFolderStore(getOrm) {
731
766
  ],
732
767
  limit: options.limit ?? DEFAULT_FOLDER_CHILDREN_LIMIT
733
768
  });
769
+ return rows.map(mapFolder);
734
770
  },
735
- ensure,
736
- async create(scope, path) {
737
- if (await find(scope, path)) throw s3Error("FOLDER_EXISTS");
738
- let folder;
771
+ async trail(scope, id) {
772
+ const chain = [];
773
+ const seen = /* @__PURE__ */ new Set();
774
+ let current = await find(scope, id);
775
+ if (!current) throw s3Error("FOLDER_NOT_FOUND");
776
+ while (current && !seen.has(current.id)) {
777
+ seen.add(current.id);
778
+ chain.push(current);
779
+ if (!current.parentId || chain.length > FOLDER_MAX_DEPTH) break;
780
+ current = await find(scope, current.parentId);
781
+ }
782
+ return chain.reverse();
783
+ },
784
+ async create(scope, input) {
785
+ const parent = await destination(scope, input.parentId);
786
+ const path = childFolderPath(parent?.path ?? null, input.name);
787
+ if (path === null) throw s3Error("FOLDER_INVALID");
788
+ const name = path.slice(path.lastIndexOf("/") + 1);
789
+ const orm = await getOrm();
739
790
  try {
740
- folder = await insertFolder(await getOrm(), scope, path);
791
+ return await insertFolder(orm, {
792
+ scope,
793
+ parentId: input.parentId,
794
+ name,
795
+ path
796
+ });
741
797
  } catch (error) {
742
- if (await find(scope, path)) throw s3Error("FOLDER_EXISTS");
798
+ if (await findNamed(scope, input.parentId, name)) {
799
+ throw s3Error("FOLDER_EXISTS");
800
+ }
743
801
  throw error;
744
802
  }
745
- await ensure(scope, parentFolderPath(path));
746
- return folder;
747
803
  },
748
- async delete(scope, path) {
749
- if (await countContents(scope, path) > 0) {
804
+ async update(scope, id, input) {
805
+ const folder = await find(scope, id);
806
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
807
+ const name = input.name ?? folder.name;
808
+ const parentId = input.parentId === void 0 ? folder.parentId : input.parentId;
809
+ if (name === folder.name && parentId === folder.parentId) return folder;
810
+ const parent = await destination(scope, parentId, id);
811
+ const path = childFolderPath(parent?.path ?? null, name);
812
+ if (path === null) throw s3Error("FOLDER_INVALID");
813
+ const storedName = path.slice(path.lastIndexOf("/") + 1);
814
+ const below = await descendants(scope, folder.path);
815
+ const prefix = folder.path;
816
+ const rewritten = below.map((child) => ({
817
+ id: child.id,
818
+ path: `${path}${child.path.slice(prefix.length)}`
819
+ }));
820
+ for (const next of [path, ...rewritten.map((child) => child.path)]) {
821
+ if (normalizeFolderPath(next) !== next) throw s3Error("FOLDER_INVALID");
822
+ }
823
+ const orm = await getOrm();
824
+ const now = /* @__PURE__ */ new Date();
825
+ await orm.transaction(async (tx) => {
826
+ try {
827
+ await tx.updateMany("storageFolder", {
828
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id)),
829
+ set: {
830
+ name: storedName,
831
+ parentId: storedParent(parentId),
832
+ path,
833
+ updatedAt: now
834
+ }
835
+ });
836
+ } catch (error) {
837
+ if (isUniqueViolation(error)) throw s3Error("FOLDER_EXISTS");
838
+ throw error;
839
+ }
840
+ for (const child of rewritten) {
841
+ await tx.updateMany("storageFolder", {
842
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", child.id)),
843
+ set: { path: child.path, updatedAt: now }
844
+ });
845
+ }
846
+ });
847
+ const updated = await find(scope, id);
848
+ if (!updated) throw s3Error("FOLDER_NOT_FOUND");
849
+ return updated;
850
+ },
851
+ async delete(scope, id) {
852
+ const folder = await find(scope, id);
853
+ if (!folder) return;
854
+ if (await countContents(scope, id) > 0) {
750
855
  throw s3Error("FOLDER_NOT_EMPTY");
751
856
  }
752
857
  const orm = await getOrm();
753
858
  await orm.deleteMany("storageFolder", {
754
- where: (b) => b.and(b("scope", "=", scope), b("path", "=", path))
859
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id))
755
860
  });
756
- if (await countContents(scope, path) > 0) {
757
- await insertMissing(scope, path);
861
+ if (await countContents(scope, id) > 0) {
862
+ await retain(folder);
758
863
  throw s3Error("FOLDER_NOT_EMPTY");
759
864
  }
760
- }
865
+ },
866
+ retain
761
867
  };
762
868
  }
763
869
 
@@ -865,7 +971,7 @@ var dbListSortQuerySchema = z.codec(
865
971
  }
866
972
  );
867
973
  var dbListQuerySchema = z.strictObject({
868
- folder: z.string().optional(),
974
+ folderId: z.string().optional(),
869
975
  route: routeNameSchema.optional(),
870
976
  // Rows that purge has claimed stay internal, as on `GET /db/object`.
871
977
  status: z.enum(["pending", "active", "deleted"]).optional(),
@@ -890,12 +996,21 @@ var dbUpdateObjectBodySchema = z.strictObject({
890
996
  key: objectKeySchema,
891
997
  bucket: trimmedString.optional(),
892
998
  filename: fileNameSchema.optional(),
893
- folder: z.string().nullable().optional(),
999
+ folderId: z.string().nullable().optional(),
894
1000
  /** `null` clears the attributes. */
895
1001
  attributes: z.record(z.string(), z.unknown()).nullable().optional()
896
1002
  });
897
- var dbFolderInputSchema = z.strictObject({
898
- path: z.string()
1003
+ var dbCreateFolderBodySchema = z.strictObject({
1004
+ parentId: z.string().nullable().optional(),
1005
+ name: z.string()
1006
+ });
1007
+ var dbUpdateFolderBodySchema = z.strictObject({
1008
+ id: trimmedString,
1009
+ name: z.string().optional(),
1010
+ parentId: z.string().nullable().optional()
1011
+ });
1012
+ var dbDeleteFolderQuerySchema = z.strictObject({
1013
+ id: trimmedString
899
1014
  });
900
1015
 
901
1016
  // src/plugin/to-db-client-object.ts
@@ -906,7 +1021,7 @@ function toDbClientObject(object2, toClient) {
906
1021
  bucket: object2.bucket,
907
1022
  key: object2.key,
908
1023
  route: object2.route,
909
- folder: object2.folder,
1024
+ folderId: object2.folderId,
910
1025
  filename: object2.filename,
911
1026
  contentType: object2.contentType,
912
1027
  size: object2.size,
@@ -924,10 +1039,12 @@ function toDbClientObject(object2, toClient) {
924
1039
  }
925
1040
  function toDbClientFolder(folder) {
926
1041
  return {
927
- path: folder.path,
1042
+ id: folder.id,
928
1043
  name: folder.name,
929
- parent: folder.parent,
930
- createdAt: folder.createdAt.toISOString()
1044
+ parentId: folder.parentId,
1045
+ path: folder.path,
1046
+ createdAt: folder.createdAt.toISOString(),
1047
+ updatedAt: folder.updatedAt.toISOString()
931
1048
  };
932
1049
  }
933
1050
 
@@ -959,13 +1076,16 @@ function matchingFolders(children, search) {
959
1076
  const text = search.toLowerCase();
960
1077
  return children.filter((child) => child.name.toLowerCase().includes(text));
961
1078
  }
962
- function parseFolderPath(value) {
963
- const path = parseFolder(value);
964
- if (path === null) throw s3Error("FOLDER_INVALID");
965
- return path;
1079
+ function wireFolderId(value) {
1080
+ if (value === void 0) return void 0;
1081
+ return value === "" || value === null ? null : value;
1082
+ }
1083
+ function folderTarget(folder) {
1084
+ if (folder === null) return { folder: null, folderId: null };
1085
+ return { folder: folder.path, folderId: folder.id };
966
1086
  }
967
1087
  function createDatabaseEndpoints(options) {
968
- const { access, quota, toClientObject } = options;
1088
+ const { access, quota, resolveScope, toClientObject } = options;
969
1089
  const { objects, folders } = options.store;
970
1090
  const parseAttributes = async (value) => {
971
1091
  const { attributes } = options;
@@ -989,33 +1109,46 @@ function createDatabaseEndpoints(options) {
989
1109
  }
990
1110
  return result.value;
991
1111
  };
1112
+ const openFolder = async (scope, wire) => {
1113
+ const folderId = wireFolderId(wire);
1114
+ if (folderId === void 0) return void 0;
1115
+ if (folderId === null) return null;
1116
+ const folder = await folders.find(scope, folderId);
1117
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
1118
+ return folder;
1119
+ };
992
1120
  return {
993
- /** One page of the caller's objects. `folder` omitted lists every folder. */
1121
+ /** One page of the caller's objects. `folderId` omitted lists every folder. */
994
1122
  objects: createS3Endpoint(
995
1123
  pluginPath("db", "objects"),
996
1124
  { method: "GET", query: dbListQuerySchema },
997
1125
  async (ctx) => {
998
- const { folder: wireFolder, ...filters } = ctx.query;
999
- const folder = wireFolder === void 0 ? void 0 : parseFolder(wireFolder);
1126
+ const { folderId: wireFolder, ...filters } = ctx.query;
1127
+ const peeked = await resolveScope(ctx.context, {
1128
+ operation: "list",
1129
+ route: filters.route
1130
+ });
1131
+ const opened = await openFolder(peeked.scope, wireFolder);
1000
1132
  const scope = await access.scope(ctx.context, {
1001
1133
  operation: "list",
1002
1134
  route: filters.route,
1003
- ...folder !== void 0 && { folder }
1135
+ ...opened !== void 0 && folderTarget(opened)
1004
1136
  });
1005
1137
  const page = await objects.list({
1006
1138
  ...filters,
1007
1139
  scope: scope.scope,
1008
- folder
1140
+ folderId: opened === void 0 ? void 0 : opened?.id ?? null
1009
1141
  });
1010
1142
  const response = {
1011
1143
  objects: page.objects.map((object2) => toClientObject(object2)),
1012
1144
  nextCursor: page.nextCursor
1013
1145
  };
1014
1146
  if (!page.firstPage) return response;
1015
- const [usage, limits, children] = await Promise.all([
1147
+ const [usage, limits, children, trail] = await Promise.all([
1016
1148
  objects.getUsage(scope.scope),
1017
1149
  quota.limits(scope),
1018
- folder === void 0 ? void 0 : folders.children(scope.scope, folder)
1150
+ opened === void 0 ? void 0 : folders.children(scope.scope, opened?.id ?? null),
1151
+ opened === void 0 ? void 0 : opened === null ? [] : folders.trail(scope.scope, opened.id)
1019
1152
  ]);
1020
1153
  return {
1021
1154
  ...response,
@@ -1025,7 +1158,8 @@ function createDatabaseEndpoints(options) {
1025
1158
  folders: matchingFolders(children, filters.search).map(
1026
1159
  toDbClientFolder
1027
1160
  )
1028
- }
1161
+ },
1162
+ ...trail && { trail: trail.map(toDbClientFolder) }
1029
1163
  };
1030
1164
  }
1031
1165
  ),
@@ -1051,8 +1185,7 @@ function createDatabaseEndpoints(options) {
1051
1185
  ),
1052
1186
  /**
1053
1187
  * Renames, moves, or sets the attributes of an active object. A move
1054
- * checks the target folder like an upload: validated, authorized, and
1055
- * created when missing.
1188
+ * requires the target folder to exist and authorizes that folder.
1056
1189
  */
1057
1190
  updateObject: createS3Endpoint(
1058
1191
  pluginPath("db", "object"),
@@ -1064,55 +1197,95 @@ function createDatabaseEndpoints(options) {
1064
1197
  ctx.body.bucket,
1065
1198
  "body.bucket"
1066
1199
  );
1067
- const folder = ctx.body.folder === void 0 ? void 0 : parseFolder(ctx.body.folder ?? "");
1200
+ const folderId = wireFolderId(ctx.body.folderId);
1201
+ const peeked = await resolveScope(ctx.context, {
1202
+ operation: "update"
1203
+ });
1204
+ const opened = folderId === void 0 ? void 0 : await openFolder(peeked.scope, folderId ?? "");
1068
1205
  const { scope, object: object2 } = await access.object(
1069
1206
  ctx.context,
1070
1207
  {
1071
1208
  operation: "update",
1072
1209
  key,
1073
- ...folder !== void 0 && { folder }
1210
+ ...opened !== void 0 && folderTarget(opened)
1074
1211
  },
1075
1212
  { bucket, key }
1076
1213
  );
1077
1214
  if (object2.status !== "active") throw s3Error("OBJECT_NOT_FOUND");
1078
1215
  const attributes = ctx.body.attributes === void 0 || ctx.body.attributes === null ? ctx.body.attributes : await parseAttributes(ctx.body.attributes);
1079
- if (filename === void 0 && folder === void 0 && attributes === void 0) {
1216
+ if (filename === void 0 && folderId === void 0 && attributes === void 0) {
1080
1217
  return { object: toClientObject(object2) };
1081
1218
  }
1082
1219
  const updated = await options.objects.update(
1083
1220
  { bucket, key, id: object2.id, scope: scope.scope },
1084
- { filename, folder, attributes }
1221
+ { filename, folderId, attributes }
1085
1222
  );
1086
1223
  if (!updated) throw s3Error("OBJECT_NOT_FOUND");
1087
1224
  return { object: toClientObject(updated) };
1088
1225
  }
1089
1226
  ),
1090
- /** Creates a folder and its missing ancestors. */
1227
+ /** Creates one folder inside a parent that already exists. */
1091
1228
  createFolder: createS3Endpoint(
1092
1229
  pluginPath("db", "folder"),
1093
- { method: "POST", body: dbFolderInputSchema },
1230
+ { method: "POST", body: dbCreateFolderBodySchema },
1094
1231
  async (ctx) => {
1095
- const path = parseFolderPath(ctx.body.path);
1232
+ const parentId = wireFolderId(ctx.body.parentId) ?? null;
1233
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1234
+ const parent = parentId === null ? null : await openFolder(peeked.scope, parentId);
1235
+ const path = childFolderPath(parent?.path ?? null, ctx.body.name);
1236
+ if (path === null) throw s3Error("FOLDER_INVALID");
1096
1237
  const scope = await access.scope(ctx.context, {
1097
1238
  operation: "update",
1098
1239
  folder: path
1099
1240
  });
1100
- const folder = await folders.create(scope.scope, path);
1241
+ const folder = await folders.create(scope.scope, {
1242
+ parentId,
1243
+ name: ctx.body.name
1244
+ });
1245
+ return { folder: toDbClientFolder(folder) };
1246
+ }
1247
+ ),
1248
+ /** Renames a folder, moves it, or both. */
1249
+ updateFolder: createS3Endpoint(
1250
+ pluginPath("db", "folder"),
1251
+ { method: "PATCH", body: dbUpdateFolderBodySchema },
1252
+ async (ctx) => {
1253
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1254
+ const current = await folders.find(peeked.scope, ctx.body.id);
1255
+ if (!current) throw s3Error("FOLDER_NOT_FOUND");
1256
+ const parentId = ctx.body.parentId === void 0 ? current.parentId : wireFolderId(ctx.body.parentId) ?? null;
1257
+ const parent = parentId === null ? null : await openFolder(peeked.scope, parentId);
1258
+ const path = childFolderPath(
1259
+ parent?.path ?? null,
1260
+ ctx.body.name ?? current.name
1261
+ );
1262
+ if (path === null) throw s3Error("FOLDER_INVALID");
1263
+ await access.scope(ctx.context, {
1264
+ operation: "update",
1265
+ folder: path,
1266
+ folderId: current.id
1267
+ });
1268
+ const folder = await folders.update(peeked.scope, current.id, {
1269
+ ...ctx.body.name !== void 0 && { name: ctx.body.name },
1270
+ ...ctx.body.parentId !== void 0 && { parentId }
1271
+ });
1101
1272
  return { folder: toDbClientFolder(folder) };
1102
1273
  }
1103
1274
  ),
1104
1275
  /** Removes an empty folder. A missing folder is not an error. */
1105
1276
  deleteFolder: createS3Endpoint(
1106
1277
  pluginPath("db", "folder"),
1107
- { method: "DELETE", query: dbFolderInputSchema },
1278
+ { method: "DELETE", query: dbDeleteFolderQuerySchema },
1108
1279
  async (ctx) => {
1109
- const path = parseFolderPath(ctx.query.path);
1110
- const scope = await access.scope(ctx.context, {
1280
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1281
+ const current = await folders.find(peeked.scope, ctx.query.id);
1282
+ if (!current) return { id: ctx.query.id };
1283
+ await access.scope(ctx.context, {
1111
1284
  operation: "update",
1112
- folder: path
1285
+ ...folderTarget(current)
1113
1286
  });
1114
- await folders.delete(scope.scope, path);
1115
- return { path };
1287
+ await folders.delete(peeked.scope, current.id);
1288
+ return { id: current.id };
1116
1289
  }
1117
1290
  )
1118
1291
  };
@@ -1132,12 +1305,9 @@ function refOf(context) {
1132
1305
  function objectTarget(context, operation) {
1133
1306
  return { operation, route: context.route, key: context.key };
1134
1307
  }
1135
- function uploadTarget(context) {
1136
- return {
1137
- ...objectTarget(context, "upload"),
1138
- folder: parseFolder(context.clientMetadata?.folder ?? ""),
1139
- clientMetadata: context.clientMetadata
1140
- };
1308
+ function requestedFolderId(metadata) {
1309
+ const value = metadata?.folderId ?? "";
1310
+ return value === "" ? null : value;
1141
1311
  }
1142
1312
  function writtenBy(object2, uploadToken) {
1143
1313
  return object2 !== null && object2.uploadToken === uploadToken;
@@ -1163,16 +1333,22 @@ function createDatabaseLifecycleHooks(options) {
1163
1333
  if (!live) throw s3Error("OBJECT_NOT_FOUND");
1164
1334
  };
1165
1335
  const uploadWrite = async (context) => {
1166
- const target = uploadTarget(context);
1167
1336
  const existing = await objects.find(refOf(context));
1168
- if (existing?.status !== "active" || routes.replace(context.route) !== "overwrite") {
1169
- return { target, existing, replaced: null };
1337
+ const replaced = existing?.status === "active" && routes.replace(context.route) === "overwrite" ? existing : null;
1338
+ const folderId = replaced ? replaced.folderId : requestedFolderId(context.clientMetadata);
1339
+ const scope = await resolveScope(context, objectTarget(context, "upload"));
1340
+ let folder = null;
1341
+ if (folderId !== null) {
1342
+ folder = await folders.find(scope.scope, folderId);
1343
+ if (!folder && !replaced) throw s3Error("FOLDER_NOT_FOUND");
1170
1344
  }
1171
- return {
1172
- target: { ...target, folder: existing.folder },
1173
- existing,
1174
- replaced: existing
1345
+ const target = {
1346
+ ...objectTarget(context, "upload"),
1347
+ folderId,
1348
+ clientMetadata: context.clientMetadata,
1349
+ ...folder ? { folder: folder.path } : folderId === null ? { folder: null } : {}
1175
1350
  };
1351
+ return { target, existing, replaced, folder };
1176
1352
  };
1177
1353
  const abortPendingMultipart = async (context, row) => {
1178
1354
  const client = routes.client(context.route);
@@ -1220,13 +1396,13 @@ function createDatabaseLifecycleHooks(options) {
1220
1396
  });
1221
1397
  },
1222
1398
  async onStart(context) {
1223
- const { target } = await uploadWrite(context);
1224
- const { scope } = await resolveScope(context, target);
1225
- const row = await objects.upsertPending({
1399
+ const written = await uploadWrite(context);
1400
+ const { scope } = await resolveScope(context, written.target);
1401
+ await objects.upsertPending({
1226
1402
  ...refOf(context),
1227
1403
  scope,
1228
1404
  route: context.route,
1229
- folder: target.folder ?? null,
1405
+ folderId: written.target.folderId ?? null,
1230
1406
  filename: context.file.name,
1231
1407
  contentType: context.file.type ?? null,
1232
1408
  declaredSize: context.file.size,
@@ -1236,7 +1412,7 @@ function createDatabaseLifecycleHooks(options) {
1236
1412
  expiresAt: context.expiresAt,
1237
1413
  overwrite: routes.replace(context.route) === "overwrite"
1238
1414
  });
1239
- await folders.ensure(scope, row.folder);
1415
+ if (written.folder) await folders.retain(written.folder);
1240
1416
  },
1241
1417
  async confirmGuard(context) {
1242
1418
  await assertUploadRow(context, "confirm", {
@@ -1341,6 +1517,7 @@ function createObjectAccess(options) {
1341
1517
  ...scope,
1342
1518
  ...target?.key !== void 0 && { key: target.key },
1343
1519
  ...target?.folder !== void 0 && { folder: target.folder },
1520
+ ...target?.folderId !== void 0 && { folderId: target.folderId },
1344
1521
  ...target?.clientMetadata !== void 0 && {
1345
1522
  clientMetadata: target.clientMetadata
1346
1523
  },
@@ -1370,10 +1547,16 @@ function createObjectAccess(options) {
1370
1547
  assertOwner
1371
1548
  };
1372
1549
  }
1373
- function folderPath(path) {
1374
- const normalized = normalizeFolderPath(path);
1375
- if (normalized === null) throw s3Error("FOLDER_INVALID");
1376
- return normalized;
1550
+ function rootId(folderId) {
1551
+ return folderId === "" ? null : folderId;
1552
+ }
1553
+ async function targetFolder(folders, scope, folderId) {
1554
+ if (folderId === void 0) return void 0;
1555
+ const id = rootId(folderId);
1556
+ if (id === null) return null;
1557
+ const folder = await folders.find(scope, id);
1558
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
1559
+ return folder;
1377
1560
  }
1378
1561
  function createPublicStores(store) {
1379
1562
  const { objects, folders } = store;
@@ -1384,26 +1567,19 @@ function createPublicStores(store) {
1384
1567
  count: objects.count,
1385
1568
  getUsage: objects.getUsage,
1386
1569
  async update(ref, input) {
1387
- const folder = input.folder === void 0 || input.folder === null ? input.folder : folderPath(input.folder);
1388
- const row = await objects.update(ref, { ...input, folder });
1389
- if (row && folder !== void 0) {
1390
- await folders.ensure(row.scope, row.folder);
1570
+ const folderId = input.folderId === void 0 ? void 0 : rootId(input.folderId);
1571
+ let folder;
1572
+ if (typeof folderId === "string") {
1573
+ const scope = ref.scope ?? (await objects.find(ref))?.scope;
1574
+ if (!scope) return null;
1575
+ folder = await targetFolder(folders, scope, folderId);
1391
1576
  }
1577
+ const row = await objects.update(ref, { ...input, folderId });
1578
+ if (row && folder) await folders.retain(folder);
1392
1579
  return row;
1393
1580
  }
1394
1581
  },
1395
- // Async, so an invalid path is a rejection like any other failure.
1396
- folders: {
1397
- find: async (scope, path) => folders.find(scope, folderPath(path)),
1398
- children: async (scope, parent, options) => folders.children(
1399
- scope,
1400
- parent === null ? null : folderPath(parent),
1401
- options
1402
- ),
1403
- ensure: async (scope, path) => folders.ensure(scope, path === null ? null : folderPath(path)),
1404
- create: async (scope, path) => folders.create(scope, folderPath(path)),
1405
- delete: async (scope, path) => folders.delete(scope, folderPath(path))
1406
- }
1582
+ folders
1407
1583
  };
1408
1584
  }
1409
1585
  async function abortUpload(client, row, uploadId) {
@@ -1600,6 +1776,7 @@ function db(options) {
1600
1776
  store,
1601
1777
  objects: stores.objects,
1602
1778
  access,
1779
+ resolveScope,
1603
1780
  quota,
1604
1781
  attributes: options.attributes,
1605
1782
  toClientObject