@dimah-s3/db 2.0.0-beta.5 → 2.0.0-beta.7

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 (49) hide show
  1. package/README.md +15 -6
  2. package/dist/adapters/drizzle.d.ts +2 -3
  3. package/dist/adapters/drizzle.d.ts.map +1 -1
  4. package/dist/adapters/kysely.d.ts +1 -1
  5. package/dist/adapters/prisma.d.ts +1 -1
  6. package/dist/cli.d.ts +17 -12
  7. package/dist/cli.d.ts.map +1 -1
  8. package/dist/cli.js +42 -74
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client/index.js +1 -0
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/folder-path.d.ts +8 -2
  13. package/dist/folder-path.d.ts.map +1 -1
  14. package/dist/fuma-db.d.ts +19 -22
  15. package/dist/fuma-db.d.ts.map +1 -1
  16. package/dist/index.js +69 -101
  17. package/dist/index.js.map +1 -1
  18. package/dist/plugin/scope.d.ts +2 -0
  19. package/dist/plugin/scope.d.ts.map +1 -1
  20. package/dist/schema/schema.d.ts +33 -48
  21. package/dist/schema/schema.d.ts.map +1 -1
  22. package/dist/store/folder-store.d.ts.map +1 -1
  23. package/dist/store/map-row.d.ts +2 -8
  24. package/dist/store/map-row.d.ts.map +1 -1
  25. package/dist/store/object-store.d.ts.map +1 -1
  26. package/dist/types/plugin.d.ts +4 -3
  27. package/dist/types/plugin.d.ts.map +1 -1
  28. package/package.json +8 -26
  29. package/dist/drizzle/mysql.d.ts +0 -1057
  30. package/dist/drizzle/mysql.d.ts.map +0 -1
  31. package/dist/drizzle/mysql.js +0 -120
  32. package/dist/drizzle/mysql.js.map +0 -1
  33. package/dist/drizzle/pg.d.ts +0 -994
  34. package/dist/drizzle/pg.d.ts.map +0 -1
  35. package/dist/drizzle/pg.js +0 -104
  36. package/dist/drizzle/pg.js.map +0 -1
  37. package/dist/drizzle/shared.d.ts +0 -7
  38. package/dist/drizzle/shared.d.ts.map +0 -1
  39. package/dist/drizzle/sqlite.d.ts +0 -1056
  40. package/dist/drizzle/sqlite.d.ts.map +0 -1
  41. package/dist/drizzle/sqlite.js +0 -107
  42. package/dist/drizzle/sqlite.js.map +0 -1
  43. package/prisma/dimah-s3.prisma +0 -81
  44. package/sql/mysql.sql +0 -60
  45. package/sql/pg.sql +0 -53
  46. package/sql/sqlite.sql +0 -55
  47. package/src/drizzle/mysql.ts +0 -175
  48. package/src/drizzle/pg.ts +0 -146
  49. package/src/drizzle/sqlite.ts +0 -150
package/README.md CHANGED
@@ -12,16 +12,25 @@ Optional database plugin for [dimah-s3](https://github.com/dimah-kz/dimah-s3). I
12
12
  pnpm add @dimah-s3/db@beta @dimah-s3/server@beta
13
13
  ```
14
14
 
15
- You do not install `fumadb`: the adapters ship from `@dimah-s3/db/adapters/*`.
15
+ You do not install `fumadb`: the adapters ship from `@dimah-s3/db/adapters/*`, and the FumaDB CLI from `@dimah-s3/db/cli`.
16
16
 
17
17
  ## Tables
18
18
 
19
- Create the schema with one of:
19
+ `runCli(client)` from `@dimah-s3/db/cli` runs the FumaDB CLI for this schema:
20
20
 
21
- - Drizzle: copy `src/drizzle/{sqlite,pg,mysql}.ts` from the package into your schema so you can add columns. Or import `dimahS3Tables` from `@dimah-s3/db/drizzle/{sqlite,pg,mysql}` when the tables stay as they are.
22
- - Prisma: copy [`prisma/dimah-s3.prisma`](./prisma/dimah-s3.prisma) into your schema.
23
- - Plain SQL: run [`sql/<dialect>.sql`](./sql).
24
- - Kysely: call `migrate(client)` from `@dimah-s3/db/cli`. It creates the tables and the indexes. The FumaDB CLI from `runCli` does the same only with `migrate:up`; its `migrate` command jumps straight to the latest schema and skips the indexes.
21
+ - Drizzle or Prisma: `generate` writes the tables or models, with the indexes and the MySQL prefix lengths and collations. Apply them with `drizzle-kit` or Prisma Migrate. Generating does not connect to the database.
22
+ - Kysely: `migrate` creates the tables and the indexes, and so does `migrate(client)`.
23
+
24
+ ```ts
25
+ // scripts/dimah-s3.ts — npx tsx scripts/dimah-s3.ts generate latest -o db/dimah-s3.ts
26
+ import { DimahS3DB } from "@dimah-s3/db";
27
+ import { drizzleAdapter } from "@dimah-s3/db/adapters/drizzle";
28
+ import { runCli } from "@dimah-s3/db/cli";
29
+
30
+ await runCli(
31
+ DimahS3DB.client(drizzleAdapter({ db: undefined, provider: "sqlite" })),
32
+ );
33
+ ```
25
34
 
26
35
  The package reads schema `2.1.0` and does not upgrade a 1.x or `2.0.0` database: create the tables on a new database. A database at another schema version throws on the first query. Call `s3.db.checkSchema()` at startup to fail fast.
27
36
 
@@ -1,7 +1,6 @@
1
1
  /**
2
- * The FumaDB Drizzle adapter. Pass a Drizzle instance whose schema includes
3
- * the tables from `src/drizzle/<dialect>.ts`, copied into the app or
4
- * imported as `dimahS3Tables` from `@dimah-s3/db/drizzle/<dialect>`:
2
+ * The FumaDB Drizzle adapter. Pass a Drizzle instance whose relations include
3
+ * the tables `runCli` → `generate` writes:
5
4
  * `DimahS3DB.client(drizzleAdapter({ db, provider: "postgresql" }))`.
6
5
  */
7
6
  export { drizzleAdapter, type DrizzleConfig } from "fumadb/adapters/drizzle";
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.d.ts","sourceRoot":"","sources":["../../src/adapters/drizzle.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,cAAc,EAAE,KAAK,aAAa,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"drizzle.d.ts","sourceRoot":"","sources":["../../src/adapters/drizzle.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,cAAc,EAAE,KAAK,aAAa,EAAE,MAAM,yBAAyB,CAAC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The FumaDB Kysely adapter. It can also migrate the schema:
2
+ * The FumaDB Kysely adapter. `migrate(client)` creates the schema through it:
3
3
  * `DimahS3DB.client(kyselyAdapter({ db, provider: "postgresql" }))`.
4
4
  */
5
5
  export { kyselyAdapter } from "fumadb/adapters/kysely";
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The FumaDB Prisma adapter. Pass a Prisma client generated with the models
3
- * from `prisma/dimah-s3.prisma`:
3
+ * `runCli` → `generate` writes:
4
4
  * `DimahS3DB.client(prismaAdapter({ prisma, provider: "postgresql" }))`.
5
5
  */
6
6
  export { prismaAdapter, type PrismaConfig } from "fumadb/adapters/prisma";
package/dist/cli.d.ts CHANGED
@@ -1,25 +1,30 @@
1
1
  import { type DimahS3DbClient } from "./fuma-db";
2
2
  /**
3
- * Runs the interactive FumaDB CLI: generate the ORM schema, or migrate when
4
- * the client uses the Kysely adapter. Prefer {@link migrate}. Only
5
- * `migrate:up`, one version at a time, runs the steps the schema needs,
6
- * including the indexes. The CLI `migrate` command jumps to the latest
7
- * schema and skips them.
3
+ * Runs the FumaDB CLI for the @dimah-s3/db schema. `generate` writes the
4
+ * Drizzle or Prisma schema for the client's adapter, and with Kysely, the SQL
5
+ * that creates the tables. `migrate` creates them with Kysely.
6
+ *
7
+ * Generating does not query the database, so the client can wrap an adapter
8
+ * that has no connection yet.
8
9
  *
9
10
  * ```ts
10
- * // scripts/db.ts
11
+ * // scripts/dimah-s3.mts
12
+ * import { DimahS3DB } from "@dimah-s3/db";
13
+ * import { drizzleAdapter } from "@dimah-s3/db/adapters/drizzle";
11
14
  * import { runCli } from "@dimah-s3/db/cli";
12
- * import { dimahS3Db } from "../lib/s3";
13
15
  *
14
- * await runCli(dimahS3Db);
16
+ * await runCli(DimahS3DB.client(drizzleAdapter({ db: undefined, provider: "postgresql" })));
15
17
  * ```
18
+ *
19
+ * `node scripts/dimah-s3.mts generate latest -o db/dimah-s3.ts`
16
20
  */
17
21
  export declare function runCli(client: DimahS3DbClient): Promise<void>;
18
22
  /**
19
- * Creates the schema this package reads, one version at a time, so the
20
- * schema's own steps run (the indexes among them). It needs the Kysely
21
- * adapter; with Drizzle or Prisma, use your ORM's migrations or the files
22
- * in `sql/`. It does not upgrade a database at another version.
23
+ * Creates the schema this package reads, with its indexes, on an empty
24
+ * database. It needs the Kysely adapter; with Drizzle or Prisma, generate the
25
+ * schema with {@link runCli} and apply it with your ORM. It does nothing on a
26
+ * database already at {@link DB_SCHEMA_VERSION}, and throws on a database at
27
+ * another version: this package does not upgrade one.
23
28
  *
24
29
  * ```ts
25
30
  * import { DimahS3DB } from "@dimah-s3/db";
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,KAAK,eAAe,EAAE,MAAM,WAAW,CAAC;AAYpE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAS7D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,OAAO,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBpE"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,KAAK,eAAe,EAAE,MAAM,WAAW,CAAC;AAIpE;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAS7D;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAcpE"}
package/dist/cli.js CHANGED
@@ -3,120 +3,90 @@ import { fumadb } from 'fumadb';
3
3
  import { table, column, idColumn, schema } from 'fumadb/schema';
4
4
 
5
5
  // src/cli.ts
6
- function byteCount(name) {
7
- return column(name, "bigint").nullable();
6
+ var BINARY = { mysql: "utf8mb4_bin" };
7
+ var TEXT = { mysql: "utf8mb4_unicode_ci" };
8
+ var LONG_PREFIX = 512;
9
+ var SCOPE_MAX_LENGTH = 255;
10
+ function string(name, length = 255) {
11
+ return column(name, `varchar(${length})`).collate(BINARY);
8
12
  }
9
13
  var storageObject = table("storage_object", {
10
- id: idColumn("id", "varchar(255)").defaultTo$("auto"),
14
+ id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
11
15
  /** Owner, for example `user:123` or `org:acme`. */
12
- scope: column("scope", "string"),
13
- bucket: column("bucket", "string"),
14
- key: column("key", "string"),
16
+ scope: string("scope", SCOPE_MAX_LENGTH),
17
+ bucket: string("bucket"),
18
+ key: string("key", 1024),
15
19
  /** Named dimah-s3 route that created the object. */
16
- route: column("route", "string"),
20
+ route: string("route"),
17
21
  /** Folder that holds the object. `null` is the root. */
18
- folderId: column("folder_id", "string").nullable(),
19
- filename: column("filename", "string"),
20
- contentType: column("content_type", "string").nullable(),
22
+ folderId: string("folder_id").nullable(),
23
+ filename: column("filename", "varchar(255)").collate(TEXT),
24
+ contentType: string("content_type").nullable(),
21
25
  /** Verified size from HeadObject, set on confirm. */
22
- size: byteCount("size"),
26
+ size: column("size", "bigint").nullable(),
23
27
  /** Size the client declared before confirm. Quota counts it while pending. */
24
- declaredSize: byteCount("declared_size"),
25
- eTag: column("e_tag", "string").nullable(),
26
- status: column("status", "string"),
28
+ declaredSize: column("declared_size", "bigint").nullable(),
29
+ eTag: string("e_tag").nullable(),
30
+ status: string("status", 16),
27
31
  /** S3 user metadata of the verified object. */
28
32
  s3Metadata: column("s3_metadata", "json").nullable(),
29
33
  /** App attributes, validated by the plugin's `attributes.schema`. */
30
34
  attributes: column("attributes", "json").nullable(),
31
- acl: column("acl", "string").nullable(),
35
+ acl: string("acl").nullable(),
32
36
  /** Multipart upload ID while the row is pending. */
33
- uploadId: column("upload_id", "string").nullable(),
37
+ uploadId: column("upload_id", "string").collate(BINARY).nullable(),
34
38
  /** Token of the upload ticket that wrote the row. Confirm and purge match it. */
35
- uploadToken: column("upload_token", "string").nullable(),
39
+ uploadToken: string("upload_token", 64).nullable(),
36
40
  /** Confirm deadline of a pending row (the upload ticket's expiry). */
37
41
  expiresAt: column("expires_at", "timestamp").nullable(),
38
42
  confirmedAt: column("confirmed_at", "timestamp").nullable(),
39
43
  createdAt: column("created_at", "timestamp").defaultTo$("now"),
40
44
  updatedAt: column("updated_at", "timestamp").defaultTo$("now"),
41
45
  deletedAt: column("deleted_at", "timestamp").nullable()
42
- }).unique("storage_object_bucket_key_uk", ["bucket", "key"]);
46
+ }).unique("storage_object_bucket_key_uk", ["bucket", "key"], {
47
+ length: { key: LONG_PREFIX }
48
+ }).index("storage_object_scope_folder_idx", [
49
+ "scope",
50
+ "status",
51
+ "folderId",
52
+ "createdAt"
53
+ ]).index("storage_object_scope_updated_idx", ["scope", "status", "updatedAt"]).index("storage_object_scope_filename_idx", ["scope", "status", "filename"]).index("storage_object_scope_size_idx", ["scope", "status", "size"]).index("storage_object_status_expires_idx", ["status", "expiresAt"]);
43
54
  var storageFolder = table("storage_folder", {
44
- id: idColumn("id", "varchar(255)").defaultTo$("auto"),
45
- scope: column("scope", "string"),
55
+ id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
56
+ scope: string("scope", SCOPE_MAX_LENGTH),
46
57
  /** Id of the containing folder. `""` is the root. */
47
- parentId: column("parent_id", "string"),
58
+ parentId: string("parent_id").defaultTo(""),
48
59
  /** Last segment of `path`. */
49
- name: column("name", "string"),
60
+ name: string("name"),
50
61
  /** Full folder path. */
51
- path: column("path", "string"),
62
+ path: string("path", 1024),
52
63
  createdAt: column("created_at", "timestamp").defaultTo$("now"),
53
64
  updatedAt: column("updated_at", "timestamp").defaultTo$("now")
54
- }).unique("storage_folder_scope_path_uk", ["scope", "path"]).unique("storage_folder_scope_parent_name_uk", ["scope", "parentId", "name"]);
55
- var schemaIndexes = [
56
- {
57
- name: "storage_object_scope_folder_idx",
58
- table: "storage_object",
59
- columns: ["scope", "status", "folder_id", "created_at"]
60
- },
61
- {
62
- name: "storage_object_scope_updated_idx",
63
- table: "storage_object",
64
- columns: ["scope", "status", "updated_at"]
65
- },
66
- {
67
- name: "storage_object_scope_filename_idx",
68
- table: "storage_object",
69
- columns: ["scope", "status", "filename"]
70
- },
71
- {
72
- name: "storage_object_scope_size_idx",
73
- table: "storage_object",
74
- columns: ["scope", "status", "size"]
75
- },
76
- {
77
- name: "storage_object_status_expires_idx",
78
- table: "storage_object",
79
- columns: ["status", "expires_at"]
80
- }
81
- ];
82
- var custom = (sql) => ({ type: "custom", sql });
83
- var PREDECESSOR_VERSION = "0.0.1";
84
- var predecessor = schema({
85
- version: PREDECESSOR_VERSION,
86
- tables: {}
87
- });
65
+ }).unique("storage_folder_scope_path_uk", ["scope", "path"], {
66
+ length: { path: LONG_PREFIX }
67
+ }).unique("storage_folder_scope_parent_name_uk", ["scope", "parentId", "name"]);
88
68
  var dbSchema = schema({
89
69
  version: "2.1.0",
90
70
  tables: {
91
71
  storageObject,
92
72
  storageFolder
93
- },
94
- async up({ auto }) {
95
- const indexes = schemaIndexes.map((index) => {
96
- const columns = index.columns.map((name) => `"${name}"`).join(", ");
97
- return custom(
98
- `CREATE INDEX IF NOT EXISTS "${index.name}" ON "${index.table}" (${columns})`
99
- );
100
- });
101
- return [...await auto(), ...indexes];
102
73
  }
103
74
  });
104
75
 
105
76
  // src/fuma-db.ts
106
77
  fumadb({
107
78
  namespace: "dimah_s3",
108
- schemas: [predecessor, dbSchema]
79
+ schemas: [dbSchema]
109
80
  });
110
81
  var DB_SCHEMA_VERSION = dbSchema.version;
111
82
 
112
83
  // src/cli.ts
113
- var RESUMABLE = /* @__PURE__ */ new Set([PREDECESSOR_VERSION, DB_SCHEMA_VERSION]);
114
84
  function runCli(client) {
115
85
  const { main } = createCli({
116
86
  db: client,
117
87
  command: "dimah-s3-db",
118
88
  description: "FumaDB CLI for @dimah-s3/db",
119
- version: "2.0.0-beta.5"
89
+ version: "2.0.0-beta.7"
120
90
  });
121
91
  return main();
122
92
  }
@@ -127,15 +97,13 @@ async function migrate(client) {
127
97
  } catch {
128
98
  version = void 0;
129
99
  }
130
- if (version !== void 0 && !RESUMABLE.has(version)) {
100
+ if (version === DB_SCHEMA_VERSION) return;
101
+ if (version !== void 0) {
131
102
  throw new Error(
132
103
  `[dimah-s3/db] The database is at schema ${version}, which this package does not upgrade. Create schema ${DB_SCHEMA_VERSION} on a new database.`
133
104
  );
134
105
  }
135
- const migrator = client.createMigrator();
136
- for (let next = await migrator.next(); next; next = await migrator.next()) {
137
- await (await migrator.up()).execute();
138
- }
106
+ await (await client.createMigrator().migrateToLatest()).execute();
139
107
  }
140
108
 
141
109
  export { migrate, runCli };
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/schema.ts","../src/fuma-db.ts","../src/cli.ts"],"names":[],"mappings":";;;;;AASA,SAAS,UAAU,IAAA,EAAc;AAC/B,EAAA,OAAO,MAAA,CAAO,IAAA,EAAM,QAAQ,CAAA,CAAE,QAAA,EAAS;AAKzC;AAOA,IAAM,aAAA,GAAgB,MAAM,gBAAA,EAAkB;AAAA,EAC5C,IAAI,QAAA,CAAS,IAAA,EAAM,cAAc,CAAA,CAAE,WAAW,MAAM,CAAA;AAAA;AAAA,EAEpD,KAAA,EAAO,MAAA,CAAO,OAAA,EAAS,QAAQ,CAAA;AAAA,EAC/B,MAAA,EAAQ,MAAA,CAAO,QAAA,EAAU,QAAQ,CAAA;AAAA,EACjC,GAAA,EAAK,MAAA,CAAO,KAAA,EAAO,QAAQ,CAAA;AAAA;AAAA,EAE3B,KAAA,EAAO,MAAA,CAAO,OAAA,EAAS,QAAQ,CAAA;AAAA;AAAA,EAE/B,QAAA,EAAU,MAAA,CAAO,WAAA,EAAa,QAAQ,EAAE,QAAA,EAAS;AAAA,EACjD,QAAA,EAAU,MAAA,CAAO,UAAA,EAAY,QAAQ,CAAA;AAAA,EACrC,WAAA,EAAa,MAAA,CAAO,cAAA,EAAgB,QAAQ,EAAE,QAAA,EAAS;AAAA;AAAA,EAEvD,IAAA,EAAM,UAAU,MAAM,CAAA;AAAA;A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,EAAI,MAAA;AAAA,IACJ,OAAA,EAAS,aAAA;AAAA,IACT,WAAA,EAAa,6BAAA;AAAA,IACb,OAAA,EAAS;AAAA,GACV,CAAA;AAED,EAAA,OAAO,IAAA,EAAK;AACd;AAgBA,eAAsB,QAAQ,MAAA,EAAwC;AACpE,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAO,OAAA,EAAQ;AAAA,EACjC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAA,GAAU,MAAA;AAAA,EACZ;AACA,EAAA,IAAI,YAAY,MAAA,IAAa,CAAC,SAAA,CAAU,GAAA,CAAI,OAAO,CAAA,EAAG;AACpD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wCAAA,EAA2C,OAAO,CAAA,qDAAA,EAAwD,iBAAiB,CAAA,mBAAA;AAAA,KAC7H;AAAA,EACF;AACA,EAAA,MAAM,QAAA,GAAW,OAAO,cAAA,EAAe;AACvC,EAAA,KAAA,IAAS,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK,EAAG,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK,EAAG;AACzE,IAAA,MAAA,CAAO,MAAM,QAAA,CAAS,EAAA,EAAG,EAAG,OAAA,EAAQ;AAAA,EACtC;AACF","file":"cli.js","sourcesContent":["import { column, idColumn, schema, table, type Column } from \"fumadb/schema\";\n\n/**\n * A byte count. The column is a `bigint` (int8 on PostgreSQL and MySQL), but\n * values are bound as numbers so SQLite stores a number instead of FumaDB's\n * 8-byte blob, which would sort after every number: INTEGER in the shipped\n * SQL, or REAL in a column FumaDB created, compared by value either way.\n * Drivers read int8 back as a number, a bigint, or a string.\n */\nfunction byteCount(name: string) {\n return column(name, \"bigint\").nullable() as unknown as Column<\n \"bigint\",\n number | null,\n number | bigint | string | null\n >;\n}\n\n/**\n * One row per tracked object:\n * `pending` (presigned) → `active` (confirmed) → `deleted` (soft delete).\n * `purging` marks a stale pending row that purge has claimed.\n */\nconst storageObject = table(\"storage_object\", {\n id: idColumn(\"id\", \"varchar(255)\").defaultTo$(\"auto\"),\n /** Owner, for example `user:123` or `org:acme`. */\n scope: column(\"scope\", \"string\"),\n bucket: column(\"bucket\", \"string\"),\n key: column(\"key\", \"string\"),\n /** Named dimah-s3 route that created the object. */\n route: column(\"route\", \"string\"),\n /** Folder that holds the object. `null` is the root. */\n folderId: column(\"folder_id\", \"string\").nullable(),\n filename: column(\"filename\", \"string\"),\n contentType: column(\"content_type\", \"string\").nullable(),\n /** Verified size from HeadObject, set on confirm. */\n size: byteCount(\"size\"),\n /** Size the client declared before confirm. Quota counts it while pending. */\n declaredSize: byteCount(\"declared_size\"),\n eTag: column(\"e_tag\", \"string\").nullable(),\n status: column(\"status\", \"string\"),\n /** S3 user metadata of the verified object. */\n s3Metadata: column(\"s3_metadata\", \"json\").nullable(),\n /** App attributes, validated by the plugin's `attributes.schema`. */\n attributes: column(\"attributes\", \"json\").nullable(),\n acl: column(\"acl\", \"string\").nullable(),\n /** Multipart upload ID while the row is pending. */\n uploadId: column(\"upload_id\", \"string\").nullable(),\n /** Token of the upload ticket that wrote the row. Confirm and purge match it. */\n uploadToken: column(\"upload_token\", \"string\").nullable(),\n /** Confirm deadline of a pending row (the upload ticket's expiry). */\n expiresAt: column(\"expires_at\", \"timestamp\").nullable(),\n confirmedAt: column(\"confirmed_at\", \"timestamp\").nullable(),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n deletedAt: column(\"deleted_at\", \"timestamp\").nullable(),\n}).unique(\"storage_object_bucket_key_uk\", [\"bucket\", \"key\"]);\n\n/**\n * One row per folder, so an empty folder still lists. `parentId` is `\"\"` at\n * the root: a nullable parent cannot be unique on PostgreSQL, MySQL, and\n * SQLite, and the root is not a row. `path` is a cache of `name` joined\n * through the parents, rewritten when a folder is renamed or moved.\n */\nconst storageFolder = table(\"storage_folder\", {\n id: idColumn(\"id\", \"varchar(255)\").defaultTo$(\"auto\"),\n scope: column(\"scope\", \"string\"),\n /** Id of the containing folder. `\"\"` is the root. */\n parentId: column(\"parent_id\", \"string\"),\n /** Last segment of `path`. */\n name: column(\"name\", \"string\"),\n /** Full folder path. */\n path: column(\"path\", \"string\"),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n})\n .unique(\"storage_folder_scope_path_uk\", [\"scope\", \"path\"])\n .unique(\"storage_folder_scope_parent_name_uk\", [\"scope\", \"parentId\", \"name\"]);\n\n/** A secondary index, by SQL table and column names. */\nexport type SchemaIndex = {\n name: string;\n table: \"storage_object\" | \"storage_folder\";\n columns: readonly string[];\n};\n\n/**\n * Secondary indexes. FumaDB cannot declare them, so {@link dbSchema}'s\n * migration, the SQL files, the Drizzle tables, and the Prisma schema carry\n * them.\n */\nexport const schemaIndexes: readonly SchemaIndex[] = [\n {\n name: \"storage_object_scope_folder_idx\",\n table: \"storage_object\",\n columns: [\"scope\", \"status\", \"folder_id\", \"created_at\"],\n },\n {\n name: \"storage_object_scope_updated_idx\",\n table: \"storage_object\",\n columns: [\"scope\", \"status\", \"updated_at\"],\n },\n {\n name: \"storage_object_scope_filename_idx\",\n table: \"storage_object\",\n columns: [\"scope\", \"status\", \"filename\"],\n },\n {\n name: \"storage_object_scope_size_idx\",\n table: \"storage_object\",\n columns: [\"scope\", \"status\", \"size\"],\n },\n {\n name: \"storage_object_status_expires_idx\",\n table: \"storage_object\",\n columns: [\"status\", \"expires_at\"],\n },\n];\n\nconst custom = (sql: string) => ({ type: \"custom\" as const, sql });\n\n/**\n * FumaDB runs `up` only when migrating from the previous entry, and skips\n * `up` on the first one. This empty entry exists so {@link dbSchema} can\n * create the indexes on a new database. A finished database is at\n * {@link dbSchema}.\n */\nexport const PREDECESSOR_VERSION = \"0.0.1\";\n\nexport const predecessor = schema({\n version: PREDECESSOR_VERSION,\n tables: {},\n});\n\n/**\n * The @dimah-s3/db schema, version `2.1.0`. The migration creates the\n * secondary indexes after the tables, because FumaDB cannot declare them.\n */\nexport const dbSchema = schema({\n version: \"2.1.0\",\n tables: {\n storageObject,\n storageFolder,\n },\n async up({ auto }) {\n const indexes = schemaIndexes.map((index) => {\n const columns = index.columns.map((name) => `\"${name}\"`).join(\", \");\n return custom(\n `CREATE INDEX IF NOT EXISTS \"${index.name}\" ON \"${index.table}\" (${columns})`,\n );\n });\n return [...(await auto()), ...indexes];\n },\n});\n","import { fumadb, type InferFumaDB } from \"fumadb\";\nimport { dbSchema, predecessor } from \"./schema/schema\";\n\n/**\n * The @dimah-s3/db FumaDB library. Call `DimahS3DB.client(adapter)` with an\n * adapter from `@dimah-s3/db/adapters/*` to get a {@link DimahS3DbClient}.\n *\n * `predecessor` is empty. FumaDB skips `up` on the first schema, and the\n * indexes are created in {@link dbSchema}'s `up`.\n */\nexport const DimahS3DB = fumadb({\n namespace: \"dimah_s3\",\n schemas: [predecessor, dbSchema],\n});\n\n/** FumaDB client for the @dimah-s3/db schema. */\nexport type DimahS3DbClient = InferFumaDB<typeof DimahS3DB>;\n\n/** The schema version the stores read and write. */\nexport const DB_SCHEMA_VERSION = dbSchema.version;\n","import { createCli } from \"fumadb/cli\";\nimport { DB_SCHEMA_VERSION, type DimahS3DbClient } from \"./fuma-db\";\nimport { PREDECESSOR_VERSION } from \"./schema/schema\";\n\ndeclare const __DIMAH_S3_DB_VERSION__: string;\n\n/**\n * Versions `migrate` may continue from: an empty database, a migration that\n * stopped on the empty predecessor, or a database already at\n * {@link DB_SCHEMA_VERSION}.\n */\nconst RESUMABLE = new Set<string>([PREDECESSOR_VERSION, DB_SCHEMA_VERSION]);\n\n/**\n * Runs the interactive FumaDB CLI: generate the ORM schema, or migrate when\n * the client uses the Kysely adapter. Prefer {@link migrate}. Only\n * `migrate:up`, one version at a time, runs the steps the schema needs,\n * including the indexes. The CLI `migrate` command jumps to the latest\n * schema and skips them.\n *\n * ```ts\n * // scripts/db.ts\n * import { runCli } from \"@dimah-s3/db/cli\";\n * import { dimahS3Db } from \"../lib/s3\";\n *\n * await runCli(dimahS3Db);\n * ```\n */\nexport function runCli(client: DimahS3DbClient): Promise<void> {\n const { main } = createCli({\n db: client,\n command: \"dimah-s3-db\",\n description: \"FumaDB CLI for @dimah-s3/db\",\n version: __DIMAH_S3_DB_VERSION__,\n });\n\n return main();\n}\n\n/**\n * Creates the schema this package reads, one version at a time, so the\n * schema's own steps run (the indexes among them). It needs the Kysely\n * adapter; with Drizzle or Prisma, use your ORM's migrations or the files\n * in `sql/`. It does not upgrade a database at another version.\n *\n * ```ts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { kyselyAdapter } from \"@dimah-s3/db/adapters/kysely\";\n * import { migrate } from \"@dimah-s3/db/cli\";\n *\n * await migrate(DimahS3DB.client(kyselyAdapter({ db: kysely, provider: \"postgresql\" })));\n * ```\n */\nexport async function migrate(client: DimahS3DbClient): Promise<void> {\n let version: string | undefined;\n try {\n version = await client.version();\n } catch {\n version = undefined;\n }\n if (version !== undefined && !RESUMABLE.has(version)) {\n throw new Error(\n `[dimah-s3/db] The database is at schema ${version}, which this package does not upgrade. Create schema ${DB_SCHEMA_VERSION} on a new database.`,\n );\n }\n const migrator = client.createMigrator();\n for (let next = await migrator.next(); next; next = await migrator.next()) {\n await (await migrator.up()).execute();\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/schema/schema.ts","../src/fuma-db.ts","../src/cli.ts"],"names":[],"mappings":";;;;;AAMA,IAAM,MAAA,GAAS,EAAE,KAAA,EAAO,aAAA,EAAc;AAGtC,IAAM,IAAA,GAAO,EAAE,KAAA,EAAO,oBAAA,EAAqB;AAO3C,IAAM,WAAA,GAAc,GAAA;AAMb,IAAM,gBAAA,GAAmB,GAAA;AAEhC,SAAS,MAAA,CAAO,IAAA,EAAc,MAAA,GAAS,GAAA,EAAK;AAC1C,EAAA,OAAO,OAAO,IAAA,EAAM,C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ACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAO,OAAA,EAAQ;AAAA,EACjC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAA,GAAU,MAAA;AAAA,EACZ;AACA,EAAA,IAAI,YAAY,iBAAA,EAAmB;AACnC,EAAA,IAAI,YAAY,MAAA,EAAW;AACzB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wCAAA,EAA2C,OAAO,CAAA,qDAAA,EAAwD,iBAAiB,CAAA,mBAAA;AAAA,KAC7H;AAAA,EACF;AACA,EAAA,MAAA,CAAO,MAAM,MAAA,CAAO,cAAA,EAAe,CAAE,eAAA,IAAmB,OAAA,EAAQ;AAClE","file":"cli.js","sourcesContent":["import { column, idColumn, schema, table } from \"fumadb/schema\";\n\n/**\n * MySQL collation of every text column but `filename`: keys, scopes, ids, and\n * upload tokens compare byte for byte.\n */\nconst BINARY = { mysql: \"utf8mb4_bin\" };\n\n/** MySQL collation of `filename`: case-insensitive, for search. */\nconst TEXT = { mysql: \"utf8mb4_unicode_ci\" };\n\n/**\n * InnoDB indexes at most 3072 bytes, so S3 keys and folder paths are indexed\n * on their first 512 characters on MySQL. Two values that share those\n * characters share an index entry, and the unique keys treat them as equal.\n */\nconst LONG_PREFIX = 512;\n\n/**\n * Longest scope `resolveScope` may return, in characters. The `scope`\n * columns are `varchar(255)`.\n */\nexport const SCOPE_MAX_LENGTH = 255;\n\nfunction string(name: string, length = 255) {\n return column(name, `varchar(${length})`).collate(BINARY);\n}\n\n/**\n * One row per tracked object:\n * `pending` (presigned) → `active` (confirmed) → `deleted` (soft delete).\n * `purging` marks a stale pending row that purge has claimed.\n */\nconst storageObject = table(\"storage_object\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n /** Owner, for example `user:123` or `org:acme`. */\n scope: string(\"scope\", SCOPE_MAX_LENGTH),\n bucket: string(\"bucket\"),\n key: string(\"key\", 1024),\n /** Named dimah-s3 route that created the object. */\n route: string(\"route\"),\n /** Folder that holds the object. `null` is the root. */\n folderId: string(\"folder_id\").nullable(),\n filename: column(\"filename\", \"varchar(255)\").collate(TEXT),\n contentType: string(\"content_type\").nullable(),\n /** Verified size from HeadObject, set on confirm. */\n size: column(\"size\", \"bigint\").nullable(),\n /** Size the client declared before confirm. Quota counts it while pending. */\n declaredSize: column(\"declared_size\", \"bigint\").nullable(),\n eTag: string(\"e_tag\").nullable(),\n status: string(\"status\", 16),\n /** S3 user metadata of the verified object. */\n s3Metadata: column(\"s3_metadata\", \"json\").nullable(),\n /** App attributes, validated by the plugin's `attributes.schema`. */\n attributes: column(\"attributes\", \"json\").nullable(),\n acl: string(\"acl\").nullable(),\n /** Multipart upload ID while the row is pending. */\n uploadId: column(\"upload_id\", \"string\").collate(BINARY).nullable(),\n /** Token of the upload ticket that wrote the row. Confirm and purge match it. */\n uploadToken: string(\"upload_token\", 64).nullable(),\n /** Confirm deadline of a pending row (the upload ticket's expiry). */\n expiresAt: column(\"expires_at\", \"timestamp\").nullable(),\n confirmedAt: column(\"confirmed_at\", \"timestamp\").nullable(),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n deletedAt: column(\"deleted_at\", \"timestamp\").nullable(),\n})\n .unique(\"storage_object_bucket_key_uk\", [\"bucket\", \"key\"], {\n length: { key: LONG_PREFIX },\n })\n .index(\"storage_object_scope_folder_idx\", [\n \"scope\",\n \"status\",\n \"folderId\",\n \"createdAt\",\n ])\n .index(\"storage_object_scope_updated_idx\", [\"scope\", \"status\", \"updatedAt\"])\n .index(\"storage_object_scope_filename_idx\", [\"scope\", \"status\", \"filename\"])\n .index(\"storage_object_scope_size_idx\", [\"scope\", \"status\", \"size\"])\n .index(\"storage_object_status_expires_idx\", [\"status\", \"expiresAt\"]);\n\n/**\n * One row per folder, so an empty folder still lists. `parentId` is `\"\"` at\n * the root: a nullable parent cannot be unique on PostgreSQL, MySQL, and\n * SQLite, and the root is not a row. `path` is a cache of `name` joined\n * through the parents, rewritten when a folder is renamed or moved.\n */\nconst storageFolder = table(\"storage_folder\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n scope: string(\"scope\", SCOPE_MAX_LENGTH),\n /** Id of the containing folder. `\"\"` is the root. */\n parentId: string(\"parent_id\").defaultTo(\"\"),\n /** Last segment of `path`. */\n name: string(\"name\"),\n /** Full folder path. */\n path: string(\"path\", 1024),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n})\n .unique(\"storage_folder_scope_path_uk\", [\"scope\", \"path\"], {\n length: { path: LONG_PREFIX },\n })\n .unique(\"storage_folder_scope_parent_name_uk\", [\"scope\", \"parentId\", \"name\"]);\n\n/**\n * The @dimah-s3/db schema, version `2.1.0`. The tables, their indexes, and\n * the MySQL collations and prefix lengths are all declared here, so FumaDB\n * creates them (`migrate`) and generates them for Drizzle and Prisma.\n */\nexport const dbSchema = schema({\n version: \"2.1.0\",\n tables: {\n storageObject,\n storageFolder,\n },\n});\n","import { fumadb, type InferFumaDB } from \"fumadb\";\nimport { dbSchema } from \"./schema/schema\";\n\n/**\n * The @dimah-s3/db FumaDB library. Call `DimahS3DB.client(adapter)` with an\n * adapter from `@dimah-s3/db/adapters/*` to get a {@link DimahS3DbClient}.\n */\nexport const DimahS3DB = fumadb({\n namespace: \"dimah_s3\",\n schemas: [dbSchema],\n});\n\n/** FumaDB client for the @dimah-s3/db schema. */\nexport type DimahS3DbClient = InferFumaDB<typeof DimahS3DB>;\n\n/** The schema version the stores read and write. */\nexport const DB_SCHEMA_VERSION = dbSchema.version;\n","import { createCli } from \"fumadb/cli\";\nimport { DB_SCHEMA_VERSION, type DimahS3DbClient } from \"./fuma-db\";\n\ndeclare const __DIMAH_S3_DB_VERSION__: string;\n\n/**\n * Runs the FumaDB CLI for the @dimah-s3/db schema. `generate` writes the\n * Drizzle or Prisma schema for the client's adapter, and with Kysely, the SQL\n * that creates the tables. `migrate` creates them with Kysely.\n *\n * Generating does not query the database, so the client can wrap an adapter\n * that has no connection yet.\n *\n * ```ts\n * // scripts/dimah-s3.mts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { drizzleAdapter } from \"@dimah-s3/db/adapters/drizzle\";\n * import { runCli } from \"@dimah-s3/db/cli\";\n *\n * await runCli(DimahS3DB.client(drizzleAdapter({ db: undefined, provider: \"postgresql\" })));\n * ```\n *\n * `node scripts/dimah-s3.mts generate latest -o db/dimah-s3.ts`\n */\nexport function runCli(client: DimahS3DbClient): Promise<void> {\n const { main } = createCli({\n db: client,\n command: \"dimah-s3-db\",\n description: \"FumaDB CLI for @dimah-s3/db\",\n version: __DIMAH_S3_DB_VERSION__,\n });\n\n return main();\n}\n\n/**\n * Creates the schema this package reads, with its indexes, on an empty\n * database. It needs the Kysely adapter; with Drizzle or Prisma, generate the\n * schema with {@link runCli} and apply it with your ORM. It does nothing on a\n * database already at {@link DB_SCHEMA_VERSION}, and throws on a database at\n * another version: this package does not upgrade one.\n *\n * ```ts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { kyselyAdapter } from \"@dimah-s3/db/adapters/kysely\";\n * import { migrate } from \"@dimah-s3/db/cli\";\n *\n * await migrate(DimahS3DB.client(kyselyAdapter({ db: kysely, provider: \"postgresql\" })));\n * ```\n */\nexport async function migrate(client: DimahS3DbClient): Promise<void> {\n let version: string | undefined;\n try {\n version = await client.version();\n } catch {\n version = undefined;\n }\n if (version === DB_SCHEMA_VERSION) return;\n if (version !== undefined) {\n throw new Error(\n `[dimah-s3/db] The database is at schema ${version}, which this package does not upgrade. Create schema ${DB_SCHEMA_VERSION} on a new database.`,\n );\n }\n await (await client.createMigrator().migrateToLatest()).execute();\n}\n"]}
@@ -45,6 +45,7 @@ function dbClient() {
45
45
  }
46
46
  var FOLDER_NAME_MAX_LENGTH = 255;
47
47
  var INVALID_CHARACTER = /[\p{Cc}\p{Cs}]/u;
48
+ new TextEncoder();
48
49
  function characterCount(value) {
49
50
  return Array.from(value).length;
50
51
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/db-client.ts","../../src/folder-path.ts","../../src/client/db-object-source.ts"],"names":["s3Error"],"mappings":";;;AAeA,SAAS,KAAK,OAAA,EAAuC;AACnD,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,OAAA,EAAS,SAAS,OAAA,EAAQ;AAC9D;AAGA,SAAS,UAAU,KAAA,EAAsC;AACvD,EAAA,IAAI,KAAA,EAAO,QAAA,KAAa,IAAA,EAAM,OAAO,KAAA;AACrC,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAU,EAAA,EAAG;AAClC;AAqBO,SAAS,QAAA,GAAsC;AACpD,EAAA,OAAO,kBAAA,CAAmB;AAAA,IACxB,EAAA,EAAI,IAAA;AAAA,IACJ,oBAAoB,EAAC;AAAA,IACrB,UAAA,EAAY,CAAC,MAAA,MAAgD;AAAA,MAC3D,WAAA,EAAa,CAAC,KAAA,EAAO,OAAA,KACnB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,SAAS,CAAA;AAAA,QAC1B,EAAE,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,SAAA,CAAU,KAAK,CAAA,EAAG,GAAG,IAAA,CAAK,OAAO,CAAA;AAAE,OAC7D;AAAA,MACF,SAAA,EAAW,CAAC,KAAA,EAAO,OAAA,KACjB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,QAAQ,CAAA;AAAA,QACzB,EAAE,QAAQ,KAAA,EAAO,KAAA,EAAO,OAAO,GAAG,IAAA,CAAK,OAAO,CAAA;AAAE,OAClD;AAAA,MACF,YAAA,EAAc,CAAC,KAAA,EAAO,OAAA,KACpB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,QAAQ,CAAA;AAAA,QACzB,EAAE,QAAQ,OAAA,EAAS,I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AA,CAAa;AAAA,QAC7C,IAAI,MAAA,CAAO,EAAA;AAAA,QACX;AAAA,OACD,CAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,OAAA,CAAQ,EAAA,EAAI,IAAA,EAAM,QAAQ,IAAA,EAAK;AAAA,IAC9C,CAAA;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import {\n defineClientPlugin,\n pluginPath,\n type S3RequestOptions,\n} from \"@dimah-s3/core\";\nimport type { db } from \"@/plugin/db\";\nimport type {\n DbClientActions,\n DbClientFolder,\n DbClientListInput,\n DbClientListResponse,\n DbClientObject,\n} from \"@/types/client\";\n\n/** The per-call options better-fetch reads: the abort signal and headers. */\nfunction call(options: S3RequestOptions | undefined) {\n return { signal: options?.signal, headers: options?.headers };\n}\n\n/** The list query on the wire, where the root folder is `\"\"`. */\nfunction listQuery(input: DbClientListInput | undefined) {\n if (input?.folderId !== null) return input;\n return { ...input, folderId: \"\" };\n}\n\n/**\n * Client plugin for the server `db()` endpoints. Its actions are\n * {@link DbClientActions} on `api.db`. Pass `TClientAttributes` to type the\n * `attributes` the plugin's `attributes.toClient` returns.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/react\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const s3Client = createS3Client({\n * plugins: [dbClient()],\n * });\n *\n * const page = await s3Client.db.listObjects({ folderId: \"\" });\n * ```\n *\n * The server resolves the scope from the request, so no action takes one.\n * Server code skips HTTP and uses `s3.db.objects` and `s3.db.folders`.\n */\nexport function dbClient<TClientAttributes = never>() {\n return defineClientPlugin({\n id: \"db\",\n $InferServerPlugin: {} as ReturnType<typeof db>,\n getActions: ($fetch): DbClientActions<TClientAttributes> => ({\n listObjects: (input, options) =>\n $fetch<DbClientListResponse<TClientAttributes>>(\n pluginPath(\"db\", \"objects\"),\n { method: \"GET\", query: listQuery(input), ...call(options) },\n ),\n getObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"GET\", query: input, ...call(options) },\n ),\n updateObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"PATCH\", body: input, ...call(options) },\n ),\n createFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"POST\",\n body: input,\n ...call(options),\n }),\n updateFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"PATCH\",\n body: input,\n ...call(options),\n }),\n deleteFolder: (input, options) =>\n $fetch<{ id: string }>(pluginPath(\"db\", \"folder\"), {\n method: \"DELETE\",\n query: input,\n ...call(options),\n }),\n }),\n });\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/**\n * Logical folder paths. A path is NFC-normalized and `/`-separated, with no\n * leading or trailing `/`. `null` is the root. The wire addresses a folder\n * by id; the path is the cached label of that id.\n */\n\n/** Longest folder path, in characters. */\nexport const FOLDER_PATH_MAX_LENGTH = 1024;\n\n/** Longest folder name (one path segment), in characters. */\nexport const FOLDER_NAME_MAX_LENGTH = 255;\n\n/** Most segments in a folder path. Each one is a row the server keeps. */\nexport const FOLDER_MAX_DEPTH = 32;\n\n/** Control characters and lone surrogates. */\nconst INVALID_CHARACTER = /[\\p{Cc}\\p{Cs}]/u;\n\n/** Counts code points, so a character outside the BMP counts once. */\nfunction characterCount(value: string): number {\n return Array.from(value).length;\n}\n\n/** True when `name` can be one segment of a folder path. */\nexport function isFolderName(name: string): boolean {\n const length = characterCount(name);\n return (\n length >= 1 &&\n length <= FOLDER_NAME_MAX_LENGTH &&\n name !== \".\" &&\n name !== \"..\" &&\n !name.includes(\"/\") &&\n !INVALID_CHARACTER.test(name)\n );\n}\n\n/**\n * Returns the NFC form of `path`, or `null` when it is not a valid folder\n * path. The root (`\"\"`) is not a folder path.\n */\nexport function normalizeFolderPath(path: string): string | null {\n if (!path.isWellFormed()) return null;\n const normalized = path.normalize(\"NFC\");\n if (characterCount(normalized) > FOLDER_PATH_MAX_LENGTH) return null;\n const names = normalized.split(\"/\");\n if (names.length > FOLDER_MAX_DEPTH) return null;\n return names.every(isFolderName) ? normalized : null;\n}\n\n/**\n * Reads a wire folder value. `\"\"` is the root and returns `null`.\n * @throws `FOLDER_INVALID` when the value is not a valid folder path.\n */\nexport function parseFolder(value: string): string | null {\n if (value === \"\") return null;\n const path = normalizeFolderPath(value);\n if (path === null) throw s3Error(\"FOLDER_INVALID\");\n return path;\n}\n\n/** Writes a folder for the wire. The root becomes `\"\"`. */\nexport function formatFolder(folder: string | null): string {\n return folder ?? \"\";\n}\n\n/**\n * The path of `name` inside `parent`. `null` when `name` is not a folder\n * name or the joined path is too long or too deep.\n */\nexport function childFolderPath(\n parent: string | null,\n name: string,\n): string | null {\n if (!isFolderName(name)) return null;\n return normalizeFolderPath(joinFolderPath(parent, name));\n}\n\n/** Appends `name` to `parent`. The result is not validated. */\nexport function joinFolderPath(parent: string | null, name: string): string {\n return parent === null ? name : `${parent}/${name}`;\n}\n\n/** The folder that contains `path`. `null` for a top-level folder. */\nexport function parentFolderPath(path: string): string | null {\n const index = path.lastIndexOf(\"/\");\n return index === -1 ? null : path.slice(0, index);\n}\n\n/** The last segment of `path`. */\nexport function folderName(path: string): string {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\n\n/** Every folder from the top level down to `path` itself. */\nexport function folderAncestors(path: string): string[] {\n const segments = path.split(\"/\");\n return segments.map((_, index) => segments.slice(0, index + 1).join(\"/\"));\n}\n","import { s3Error } from \"@dimah-s3/core\";\nimport { isFolderName } from \"@/folder-path\";\nimport type {\n DbClientActions,\n DbClientListInput,\n DbClientObject,\n DbListSort,\n DbListSortField,\n DbObjectSource,\n DbObjectSourceFile,\n DbObjectSourceOptions,\n DbObjectSourceQueryInput,\n} from \"@/types/client\";\n\n/** The `api.db` actions {@link dbObjectSource} calls. */\nexport type DbObjectSourceActions<TClientAttributes = never> = Pick<\n DbClientActions<TClientAttributes>,\n \"listObjects\"\n> &\n Partial<\n Pick<\n DbClientActions<TClientAttributes>,\n \"createFolder\" | \"updateObject\" | \"updateFolder\"\n >\n >;\n\n/** List sort fields and the `listObjects` columns they order by. */\nconst SORT_FIELDS = new Map<string, DbListSortField>([\n [\"name\", \"filename\"],\n [\"size\", \"size\"],\n [\"updatedAt\", \"updatedAt\"],\n]);\n\nfunction toListSort(\n sort: DbObjectSourceQueryInput[\"sort\"],\n): DbListSort | undefined {\n const field = sort ? SORT_FIELDS.get(sort.field) : undefined;\n return sort && field ? { field, direction: sort.direction } : undefined;\n}\n\nfunction toFile(object: DbClientObject<unknown>): DbObjectSourceFile {\n return {\n name: object.filename,\n objectKey: object.key,\n size: object.size,\n contentType: object.contentType,\n updatedAt: object.updatedAt,\n };\n}\n\n/**\n * A `useObjectList` source over `api.db`.\n *\n * With `folders` on (the default), `parent` is a folder id: each page lists\n * one folder, the first page carries its child folders and the breadcrumb\n * trail, uploads go to the open folder, and \"New folder\" calls\n * `api.db.createFolder`. Rename calls `api.db.updateObject` (`filename`) or\n * `api.db.updateFolder` (`name`) and leaves the object key as it is. With\n * `folders: false`, the list is flat: file rename stays, and folder actions\n * do not.\n *\n * `search` matches the filename on the server. `sort` maps `name` to\n * `filename`; `size` and `updatedAt` keep their names, and other fields keep\n * the server's order (newest first). `usage` is the scope total with its\n * caps, not the open folder's.\n *\n * ```ts\n * const list = useObjectList({\n * ...dbObjectSource(api.db, { route: \"docs\" }),\n * queryKey: [\"docs\"],\n * });\n * ```\n */\nexport function dbObjectSource<TClientAttributes = never>(\n db: DbObjectSourceActions<TClientAttributes>,\n options: DbObjectSourceOptions = {},\n): DbObjectSource<TClientAttributes> {\n const folders = options.folders !== false;\n\n const source: DbObjectSource<TClientAttributes> = {\n getKey: (item) => item.id,\n getFile: toFile,\n async query({ parent, cursor, sort, search, signal }) {\n const input: DbClientListInput = {};\n if (folders) input.folderId = parent ?? \"\";\n if (cursor) input.cursor = cursor;\n if (search) input.search = search;\n const listSort = toListSort(sort);\n if (listSort) input.sort = listSort;\n if (options.route) input.route = options.route;\n if (options.status) input.status = options.status;\n if (options.contentType) input.contentType = options.contentType;\n if (options.limit !== undefined) input.limit = options.limit;\n\n const page = await db.listObjects(input, { signal });\n return {\n items: page.objects,\n nextCursor: page.nextCursor,\n ...(page.folders && {\n folders: page.folders.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.trail && {\n trail: page.trail.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.usage && { usage: { ...page.usage, ...page.limits } }),\n };\n },\n };\n\n const updateObject = db.updateObject?.bind(db);\n if (updateObject) {\n source.renameFile = async ({ item, name }) => {\n const { object } = await updateObject({\n key: item.key,\n bucket: item.bucket,\n filename: name,\n });\n return object;\n };\n }\n if (!folders) return source;\n\n source.uploadOptions = (parent) => ({\n metadata: { folderId: parent ?? \"\" },\n });\n const createFolder = db.createFolder?.bind(db);\n if (createFolder) {\n source.createFolder = async ({ parent, name }) => {\n // A `/` would be a nested path. The server creates one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder } = await createFolder({\n parentId: parent,\n name,\n });\n return { id: folder.id, name: folder.name };\n };\n }\n const updateFolder = db.updateFolder?.bind(db);\n if (updateFolder) {\n source.renameFolder = async ({ folder, name }) => {\n // A `/` would be a nested path. The server renames one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder: updated } = await updateFolder({\n id: folder.id,\n name,\n });\n return { id: updated.id, name: updated.name };\n };\n }\n return source;\n}\n"]}
1
+ {"version":3,"sources":["../../src/client/db-client.ts","../../src/folder-path.ts","../../src/client/db-object-source.ts"],"names":["s3Error"],"mappings":";;;AAeA,SAAS,KAAK,OAAA,EAAuC;AACnD,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,OAAA,EAAS,SAAS,OAAA,EAAQ;AAC9D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/plugin/db\";\nimport type {\n DbClientActions,\n DbClientFolder,\n DbClientListInput,\n DbClientListResponse,\n DbClientObject,\n} from \"@/types/client\";\n\n/** The per-call options better-fetch reads: the abort signal and headers. */\nfunction call(options: S3RequestOptions | undefined) {\n return { signal: options?.signal, headers: options?.headers };\n}\n\n/** The list query on the wire, where the root folder is `\"\"`. */\nfunction listQuery(input: DbClientListInput | undefined) {\n if (input?.folderId !== null) return input;\n return { ...input, folderId: \"\" };\n}\n\n/**\n * Client plugin for the server `db()` endpoints. Its actions are\n * {@link DbClientActions} on `api.db`. Pass `TClientAttributes` to type the\n * `attributes` the plugin's `attributes.toClient` returns.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/react\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const s3Client = createS3Client({\n * plugins: [dbClient()],\n * });\n *\n * const page = await s3Client.db.listObjects({ folderId: \"\" });\n * ```\n *\n * The server resolves the scope from the request, so no action takes one.\n * Server code skips HTTP and uses `s3.db.objects` and `s3.db.folders`.\n */\nexport function dbClient<TClientAttributes = never>() {\n return defineClientPlugin({\n id: \"db\",\n $InferServerPlugin: {} as ReturnType<typeof db>,\n getActions: ($fetch): DbClientActions<TClientAttributes> => ({\n listObjects: (input, options) =>\n $fetch<DbClientListResponse<TClientAttributes>>(\n pluginPath(\"db\", \"objects\"),\n { method: \"GET\", query: listQuery(input), ...call(options) },\n ),\n getObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"GET\", query: input, ...call(options) },\n ),\n updateObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"PATCH\", body: input, ...call(options) },\n ),\n createFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"POST\",\n body: input,\n ...call(options),\n }),\n updateFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"PATCH\",\n body: input,\n ...call(options),\n }),\n deleteFolder: (input, options) =>\n $fetch<{ id: string }>(pluginPath(\"db\", \"folder\"), {\n method: \"DELETE\",\n query: input,\n ...call(options),\n }),\n }),\n });\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/**\n * Logical folder paths. A path is NFC-normalized and `/`-separated, with no\n * leading or trailing `/`. `null` is the root. The wire addresses a folder\n * by id; the path is the cached label of that id.\n */\n\n/**\n * Longest folder path, in UTF-8 bytes, like an S3 key. With the longest scope,\n * the `(scope, path)` unique key stays under PostgreSQL's 2704-byte limit\n * for a btree entry.\n */\nexport const FOLDER_PATH_MAX_BYTES = 1024;\n\n/** Longest folder name (one path segment), in characters. */\nexport const FOLDER_NAME_MAX_LENGTH = 255;\n\n/** Most segments in a folder path. Each one is a row the server keeps. */\nexport const FOLDER_MAX_DEPTH = 32;\n\n/** Control characters and lone surrogates. */\nconst INVALID_CHARACTER = /[\\p{Cc}\\p{Cs}]/u;\n\nconst utf8 = new TextEncoder();\n\n/** Counts code points, so a character outside the BMP counts once. */\nexport function characterCount(value: string): number {\n return Array.from(value).length;\n}\n\n/** True when `name` can be one segment of a folder path. */\nexport function isFolderName(name: string): boolean {\n const length = characterCount(name);\n return (\n length >= 1 &&\n length <= FOLDER_NAME_MAX_LENGTH &&\n name !== \".\" &&\n name !== \"..\" &&\n !name.includes(\"/\") &&\n !INVALID_CHARACTER.test(name)\n );\n}\n\n/**\n * Returns the NFC form of `path`, or `null` when it is not a valid folder\n * path. The root (`\"\"`) is not a folder path.\n */\nexport function normalizeFolderPath(path: string): string | null {\n if (!path.isWellFormed()) return null;\n const normalized = path.normalize(\"NFC\");\n if (utf8.encode(normalized).byteLength > FOLDER_PATH_MAX_BYTES) return null;\n const names = normalized.split(\"/\");\n if (names.length > FOLDER_MAX_DEPTH) return null;\n return names.every(isFolderName) ? normalized : null;\n}\n\n/**\n * Reads a wire folder value. `\"\"` is the root and returns `null`.\n * @throws `FOLDER_INVALID` when the value is not a valid folder path.\n */\nexport function parseFolder(value: string): string | null {\n if (value === \"\") return null;\n const path = normalizeFolderPath(value);\n if (path === null) throw s3Error(\"FOLDER_INVALID\");\n return path;\n}\n\n/** Writes a folder for the wire. The root becomes `\"\"`. */\nexport function formatFolder(folder: string | null): string {\n return folder ?? \"\";\n}\n\n/**\n * The path of `name` inside `parent`. `null` when `name` is not a folder\n * name or the joined path is too long or too deep.\n */\nexport function childFolderPath(\n parent: string | null,\n name: string,\n): string | null {\n if (!isFolderName(name)) return null;\n return normalizeFolderPath(joinFolderPath(parent, name));\n}\n\n/** Appends `name` to `parent`. The result is not validated. */\nexport function joinFolderPath(parent: string | null, name: string): string {\n return parent === null ? name : `${parent}/${name}`;\n}\n\n/** The folder that contains `path`. `null` for a top-level folder. */\nexport function parentFolderPath(path: string): string | null {\n const index = path.lastIndexOf(\"/\");\n return index === -1 ? null : path.slice(0, index);\n}\n\n/** The last segment of `path`. */\nexport function folderName(path: string): string {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\n\n/** Every folder from the top level down to `path` itself. */\nexport function folderAncestors(path: string): string[] {\n const segments = path.split(\"/\");\n return segments.map((_, index) => segments.slice(0, index + 1).join(\"/\"));\n}\n","import { s3Error } from \"@dimah-s3/core\";\nimport { isFolderName } from \"@/folder-path\";\nimport type {\n DbClientActions,\n DbClientListInput,\n DbClientObject,\n DbListSort,\n DbListSortField,\n DbObjectSource,\n DbObjectSourceFile,\n DbObjectSourceOptions,\n DbObjectSourceQueryInput,\n} from \"@/types/client\";\n\n/** The `api.db` actions {@link dbObjectSource} calls. */\nexport type DbObjectSourceActions<TClientAttributes = never> = Pick<\n DbClientActions<TClientAttributes>,\n \"listObjects\"\n> &\n Partial<\n Pick<\n DbClientActions<TClientAttributes>,\n \"createFolder\" | \"updateObject\" | \"updateFolder\"\n >\n >;\n\n/** List sort fields and the `listObjects` columns they order by. */\nconst SORT_FIELDS = new Map<string, DbListSortField>([\n [\"name\", \"filename\"],\n [\"size\", \"size\"],\n [\"updatedAt\", \"updatedAt\"],\n]);\n\nfunction toListSort(\n sort: DbObjectSourceQueryInput[\"sort\"],\n): DbListSort | undefined {\n const field = sort ? SORT_FIELDS.get(sort.field) : undefined;\n return sort && field ? { field, direction: sort.direction } : undefined;\n}\n\nfunction toFile(object: DbClientObject<unknown>): DbObjectSourceFile {\n return {\n name: object.filename,\n objectKey: object.key,\n size: object.size,\n contentType: object.contentType,\n updatedAt: object.updatedAt,\n };\n}\n\n/**\n * A `useObjectList` source over `api.db`.\n *\n * With `folders` on (the default), `parent` is a folder id: each page lists\n * one folder, the first page carries its child folders and the breadcrumb\n * trail, uploads go to the open folder, and \"New folder\" calls\n * `api.db.createFolder`. Rename calls `api.db.updateObject` (`filename`) or\n * `api.db.updateFolder` (`name`) and leaves the object key as it is. With\n * `folders: false`, the list is flat: file rename stays, and folder actions\n * do not.\n *\n * `search` matches the filename on the server. `sort` maps `name` to\n * `filename`; `size` and `updatedAt` keep their names, and other fields keep\n * the server's order (newest first). `usage` is the scope total with its\n * caps, not the open folder's.\n *\n * ```ts\n * const list = useObjectList({\n * ...dbObjectSource(api.db, { route: \"docs\" }),\n * queryKey: [\"docs\"],\n * });\n * ```\n */\nexport function dbObjectSource<TClientAttributes = never>(\n db: DbObjectSourceActions<TClientAttributes>,\n options: DbObjectSourceOptions = {},\n): DbObjectSource<TClientAttributes> {\n const folders = options.folders !== false;\n\n const source: DbObjectSource<TClientAttributes> = {\n getKey: (item) => item.id,\n getFile: toFile,\n async query({ parent, cursor, sort, search, signal }) {\n const input: DbClientListInput = {};\n if (folders) input.folderId = parent ?? \"\";\n if (cursor) input.cursor = cursor;\n if (search) input.search = search;\n const listSort = toListSort(sort);\n if (listSort) input.sort = listSort;\n if (options.route) input.route = options.route;\n if (options.status) input.status = options.status;\n if (options.contentType) input.contentType = options.contentType;\n if (options.limit !== undefined) input.limit = options.limit;\n\n const page = await db.listObjects(input, { signal });\n return {\n items: page.objects,\n nextCursor: page.nextCursor,\n ...(page.folders && {\n folders: page.folders.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.trail && {\n trail: page.trail.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.usage && { usage: { ...page.usage, ...page.limits } }),\n };\n },\n };\n\n const updateObject = db.updateObject?.bind(db);\n if (updateObject) {\n source.renameFile = async ({ item, name }) => {\n const { object } = await updateObject({\n key: item.key,\n bucket: item.bucket,\n filename: name,\n });\n return object;\n };\n }\n if (!folders) return source;\n\n source.uploadOptions = (parent) => ({\n metadata: { folderId: parent ?? \"\" },\n });\n const createFolder = db.createFolder?.bind(db);\n if (createFolder) {\n source.createFolder = async ({ parent, name }) => {\n // A `/` would be a nested path. The server creates one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder } = await createFolder({\n parentId: parent,\n name,\n });\n return { id: folder.id, name: folder.name };\n };\n }\n const updateFolder = db.updateFolder?.bind(db);\n if (updateFolder) {\n source.renameFolder = async ({ folder, name }) => {\n // A `/` would be a nested path. The server renames one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder: updated } = await updateFolder({\n id: folder.id,\n name,\n });\n return { id: updated.id, name: updated.name };\n };\n }\n return source;\n}\n"]}
@@ -3,12 +3,18 @@
3
3
  * leading or trailing `/`. `null` is the root. The wire addresses a folder
4
4
  * by id; the path is the cached label of that id.
5
5
  */
6
- /** Longest folder path, in characters. */
7
- export declare const FOLDER_PATH_MAX_LENGTH = 1024;
6
+ /**
7
+ * Longest folder path, in UTF-8 bytes, like an S3 key. With the longest scope,
8
+ * the `(scope, path)` unique key stays under PostgreSQL's 2704-byte limit
9
+ * for a btree entry.
10
+ */
11
+ export declare const FOLDER_PATH_MAX_BYTES = 1024;
8
12
  /** Longest folder name (one path segment), in characters. */
9
13
  export declare const FOLDER_NAME_MAX_LENGTH = 255;
10
14
  /** Most segments in a folder path. Each one is a row the server keeps. */
11
15
  export declare const FOLDER_MAX_DEPTH = 32;
16
+ /** Counts code points, so a character outside the BMP counts once. */
17
+ export declare function characterCount(value: string): number;
12
18
  /** True when `name` can be one segment of a folder path. */
13
19
  export declare function isFolderName(name: string): boolean;
14
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"folder-path.d.ts","sourceRoot":"","sources":["../src/folder-path.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,0CAA0C;AAC1C,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C,6DAA6D;AAC7D,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAE1C,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,KAAK,CAAC;AAUnC,4DAA4D;AAC5D,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAUlD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAO/D;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAKxD;AAED,2DAA2D;AAC3D,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE1D;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,IAAI,EAAE,MAAM,GACX,MAAM,GAAG,IAAI,CAGf;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1E;AAED,sEAAsE;AACtE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAG5D;AAED,kCAAkC;AAClC,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED,6DAA6D;AAC7D,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAA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29 +2,26 @@ import { type InferFumaDB } from "fumadb";
2
2
  /**
3
3
  * The @dimah-s3/db FumaDB library. Call `DimahS3DB.client(adapter)` with an
4
4
  * adapter from `@dimah-s3/db/adapters/*` to get a {@link DimahS3DbClient}.
5
- *
6
- * `predecessor` is empty. FumaDB skips `up` on the first schema, and the
7
- * indexes are created in {@link dbSchema}'s `up`.
8
5
  */
9
- export declare const DimahS3DB: import("fumadb").FumaDBFactory<(import("fumadb/schema").Schema<"0.0.1", {}> | import("fumadb/schema").Schema<"2.1.0", {
6
+ export declare const DimahS3DB: import("fumadb").FumaDBFactory<import("fumadb/schema").Schema<"2.1.0", {
10
7
  storageObject: import("fumadb/schema").Table<{
11
8
  id: import("fumadb/schema").IdColumn<"varchar(255)", string | null, string>;
12
- scope: import("fumadb/schema").Column<"string", string, string>;
13
- bucket: import("fumadb/schema").Column<"string", string, string>;
14
- key: import("fumadb/schema").Column<"string", string, string>;
15
- route: import("fumadb/schema").Column<"string", string, string>;
16
- folderId: import("fumadb/schema").Column<"string", string | null, string | null>;
17
- filename: import("fumadb/schema").Column<"string", string, string>;
18
- contentType: import("fumadb/schema").Column<"string", string | null, string | null>;
19
- size: import("fumadb/schema").Column<"bigint", number | null, string | number | bigint | null>;
20
- declaredSize: import("fumadb/schema").Column<"bigint", number | null, string | number | bigint | null>;
21
- eTag: import("fumadb/schema").Column<"string", string | null, string | null>;
22
- status: import("fumadb/schema").Column<"string", string, string>;
9
+ scope: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
10
+ bucket: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
11
+ key: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
12
+ route: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
13
+ folderId: import("fumadb/schema").Column<`varchar(${number})`, string | null, string | null>;
14
+ filename: import("fumadb/schema").Column<"varchar(255)", string, string>;
15
+ contentType: import("fumadb/schema").Column<`varchar(${number})`, string | null, string | null>;
16
+ size: import("fumadb/schema").Column<"bigint", bigint | null, bigint | null>;
17
+ declaredSize: import("fumadb/schema").Column<"bigint", bigint | null, bigint | null>;
18
+ eTag: import("fumadb/schema").Column<`varchar(${number})`, string | null, string | null>;
19
+ status: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
23
20
  s3Metadata: import("fumadb/schema").Column<"json", unknown, unknown>;
24
21
  attributes: import("fumadb/schema").Column<"json", unknown, unknown>;
25
- acl: import("fumadb/schema").Column<"string", string | null, string | null>;
22
+ acl: import("fumadb/schema").Column<`varchar(${number})`, string | null, string | null>;
26
23
  uploadId: import("fumadb/schema").Column<"string", string | null, string | null>;
27
- uploadToken: import("fumadb/schema").Column<"string", string | null, string | null>;
24
+ uploadToken: import("fumadb/schema").Column<`varchar(${number})`, string | null, string | null>;
28
25
  expiresAt: import("fumadb/schema").Column<"timestamp", Date | null, Date | null>;
29
26
  confirmedAt: import("fumadb/schema").Column<"timestamp", Date | null, Date | null>;
30
27
  createdAt: import("fumadb/schema").Column<"timestamp", Date | null, Date>;
@@ -33,14 +30,14 @@ export declare const DimahS3DB: import("fumadb").FumaDBFactory<(import("fumadb/s
33
30
  }, {}>;
34
31
  storageFolder: import("fumadb/schema").Table<{
35
32
  id: import("fumadb/schema").IdColumn<"varchar(255)", string | null, string>;
36
- scope: import("fumadb/schema").Column<"string", string, string>;
37
- parentId: import("fumadb/schema").Column<"string", string, string>;
38
- name: import("fumadb/schema").Column<"string", string, string>;
39
- path: import("fumadb/schema").Column<"string", string, string>;
33
+ scope: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
34
+ parentId: import("fumadb/schema").Column<`varchar(${number})`, string | null, string>;
35
+ name: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
36
+ path: import("fumadb/schema").Column<`varchar(${number})`, string, string>;
40
37
  createdAt: import("fumadb/schema").Column<"timestamp", Date | null, Date>;
41
38
  updatedAt: import("fumadb/schema").Column<"timestamp", Date | null, Date>;
42
39
  }, {}>;
43
- }>)[]>;
40
+ }>[]>;
44
41
  /** FumaDB client for the @dimah-s3/db schema. */
45
42
  export type DimahS3DbClient = InferFumaDB<typeof DimahS3DB>;
46
43
  /** The schema version the stores read and write. */
@@ -1 +1 @@
1
- {"version":3,"file":"fuma-db.d.ts","sourceRoot":"","sources":["../src/fuma-db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,WAAW,EAAE,MAAM,QAAQ,CAAC;AAGlD;;;;;;GAMG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAGpB,CAAC;AAEH,iDAAiD;AACjD,MAAM,MAAM,eAAe,GAAG,WAAW,CAAC,OAAO,SAAS,CAAC,CAAC;AAE5D,oDAAoD;AACpD,eAAO,MAAM,iBAAiB,SAAmB,CAAC"}
1
+ {"version":3,"file":"fuma-db.d.ts","sourceRoot":"","sources":["../src/fuma-db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,WAAW,EAAE,MAAM,QAAQ,CAAC;AAGlD;;;GAGG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAGpB,CAAC;AAEH,iDAAiD;AACjD,MAAM,MAAM,eAAe,GAAG,WAAW,CAAC,OAAO,SAAS,CAAC,CAAC;AAE5D,oDAAoD;AACpD,eAAO,MAAM,iBAAiB,SAAmB,CAAC"}