@genoacms/adapter-gcp 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2026 Filip Holčík
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,4 +1,4 @@
1
- import type { Adapter } from '@genoacms/contracts/database';
1
+ import { type Adapter } from '@genoacms/contracts/database';
2
2
  import type { GcpDatabaseOptions } from './descriptor.js';
3
3
  /** One Firestore provider, with its own client and credential. */
4
4
  declare const _default: import("@genoacms/contracts").AdapterRuntime<GcpDatabaseOptions, Adapter>;
@@ -1,5 +1,117 @@
1
+ import { DocumentNotFoundError, UnsupportedQueryError } from '@genoacms/contracts/database';
2
+ import { checkQuery, checkValues, decodeToken, encodeToken, matches } from '@genoacms/contracts/database/query';
1
3
  import { defineRuntime } from '@genoacms/contracts';
2
- import { Firestore } from '@google-cloud/firestore';
4
+ import { FieldPath, Firestore } from '@google-cloud/firestore';
5
+ const MAXIMUM_ID_BYTES = 1500;
6
+ const FAILED_PRECONDITION = 9;
7
+ const NOT_FOUND = 5;
8
+ // DATA-2
9
+ const asJson = (data) => JSON.parse(JSON.stringify(data));
10
+ // DATA-3
11
+ const withKey = (collection, id, data) => {
12
+ const keyed = { ...data, [collection.primaryKey.key]: id };
13
+ return keyed;
14
+ };
15
+ const snapshotOf = (collection, document) => ({ reference: { collection, id: document.id }, data: withKey(collection, document.id, document.data()) });
16
+ const errorCode = (error) => error?.code;
17
+ const isInequality = ({ operator }) => operator !== '==';
18
+ // DATA-5
19
+ const isStorableId = (id) => id !== '' && !id.includes('/') && id !== '.' && id !== '..' && !/^__.*__$/.test(id) && Buffer.byteLength(id) <= MAXIMUM_ID_BYTES;
20
+ // DATA-9
21
+ const isUnstorableKeyCondition = (collection, { field, value }) => field === collection.primaryKey.key && typeof value === 'string' && !isStorableId(value);
22
+ // DATA-9
23
+ const matchesNothing = (collection, conditions) => conditions.some(condition => {
24
+ const { field, operator, value } = condition;
25
+ return (field === collection.primaryKey.key && typeof value !== 'string') ||
26
+ (value === null && operator !== '==') ||
27
+ (isUnstorableKeyCondition(collection, condition) && operator === '==');
28
+ });
29
+ // DATA-9
30
+ const withoutVacuousConditions = (collection, conditions) => conditions.filter(condition => !(isUnstorableKeyCondition(collection, condition) && condition.operator === '!='));
31
+ // DATA-9
32
+ const sentToStore = (collection, conditions) => conditions.filter(condition => !isUnstorableKeyCondition(collection, condition));
33
+ const fieldPathOf = (collection, field) => field === collection.primaryKey.key ? FieldPath.documentId() : new FieldPath(field);
34
+ // DB-5
35
+ const inequalityFields = (collection, conditions) => [...new Set(conditions.filter(isInequality).map(({ field }) => field))]
36
+ .filter(field => field !== collection.primaryKey.key)
37
+ .sort();
38
+ const filteredQuery = (query, collection, conditions) => conditions.reduce((filtered, { field, operator, value }) => filtered.where(fieldPathOf(collection, field), operator, value), query);
39
+ const orderedQuery = (query, fields) => [...fields.map(field => new FieldPath(field)), FieldPath.documentId()].reduce((ordered, field) => ordered.orderBy(field), query);
40
+ const cursorAfter = (fields, document, collection) => {
41
+ const data = withKey(collection, document.id, document.data());
42
+ return { values: fields.map(field => data[field]), id: document.id };
43
+ };
44
+ const batchQuery = ({ base, limit, fields }, token) => {
45
+ const resumed = token === undefined ? base : base.startAfter(...cursorValues(token, fields));
46
+ return limit === undefined ? resumed : resumed.limit(limit);
47
+ };
48
+ async function fetchBatch(query) {
49
+ const fetched = [];
50
+ const result = await query.get().catch(refuseUnservableQuery);
51
+ result.forEach(document => { fetched.push(document); });
52
+ return fetched;
53
+ }
54
+ // DATA-11
55
+ function refuseUnservableQuery(error) {
56
+ if (errorCode(error) === FAILED_PRECONDITION && /index/i.test(error.message))
57
+ throw new UnsupportedQueryError(error.message);
58
+ throw error;
59
+ }
60
+ // DATA-8
61
+ function cursorValues(token, fields) {
62
+ const cursor = decodeToken(token);
63
+ if (typeof cursor?.id !== 'string' || !Array.isArray(cursor.values) || cursor.values.length !== fields.length)
64
+ throw new Error('database/invalid-query: unknown page token');
65
+ return [...cursor.values, cursor.id];
66
+ }
67
+ // DATA-10
68
+ function pageAtLimit(scan, batch, documents) {
69
+ for (const [index, document] of batch.entries()) {
70
+ const snapshot = snapshotOf(scan.collection, document);
71
+ if (!matches(snapshot.data, scan.conditions))
72
+ continue;
73
+ documents.push(snapshot);
74
+ if (documents.length !== scan.limit)
75
+ continue;
76
+ const queryMayHaveMore = index < batch.length - 1 || batch.length === scan.limit;
77
+ return queryMayHaveMore ? { documents, next: encodeToken(cursorAfter(scan.fields, document, scan.collection)) } : { documents };
78
+ }
79
+ return undefined;
80
+ }
81
+ // DATA-10
82
+ async function pageOf(scan, firstToken) {
83
+ const documents = [];
84
+ let token = firstToken;
85
+ for (;;) {
86
+ const batch = await fetchBatch(batchQuery(scan, token));
87
+ const page = pageAtLimit(scan, batch, documents);
88
+ if (page !== undefined)
89
+ return page;
90
+ if (scan.limit === undefined || batch.length < scan.limit)
91
+ return { documents };
92
+ token = encodeToken(cursorAfter(scan.fields, batch[batch.length - 1], scan.collection));
93
+ }
94
+ }
95
+ async function requireExisting(document, reference) {
96
+ if (!(await document.get()).exists)
97
+ throw new DocumentNotFoundError(reference);
98
+ }
99
+ // DATA-3
100
+ function withoutKeyField(collection, data) {
101
+ const { [collection.primaryKey.key]: _key, ...rest } = data;
102
+ return rest;
103
+ }
104
+ // DATA-3
105
+ function withoutIgnoredKey(reference, data) {
106
+ const key = reference.collection.primaryKey.key;
107
+ if (data[key] !== undefined && data[key] !== reference.id)
108
+ throw new Error(`database/key-immutable: ${key}`);
109
+ return withoutKeyField(reference.collection, data);
110
+ }
111
+ // DATA-6
112
+ const updateArguments = (fields) => Object.entries(fields)
113
+ .filter(([, value]) => value !== undefined)
114
+ .flatMap(([field, value]) => [new FieldPath(field), asJson(value)]);
3
115
  /** One Firestore provider, with its own client and credential. */
4
116
  export default defineRuntime({
5
117
  create({ projectId, databaseId, credentials }) {
@@ -9,52 +121,65 @@ export default defineRuntime({
9
121
  ...(credentials === undefined ? {} : { credentials })
10
122
  });
11
123
  const createDocument = async (reference, data) => {
12
- const document = await firestore.collection(reference.name).add(data);
124
+ const given = withoutKeyField(reference, data);
125
+ checkValues(given);
126
+ const document = firestore.collection(reference.name).doc();
127
+ const stored = withKey(reference, document.id, given);
128
+ await document.set(asJson(stored));
13
129
  const documentReference = {
14
130
  collection: reference,
15
131
  id: document.id
16
132
  };
17
133
  return {
18
134
  reference: documentReference,
19
- data
135
+ data: stored
20
136
  };
21
137
  };
22
- const getCollection = async (reference) => {
23
- const collection = await firestore.collection(reference.name).get();
24
- const documents = [];
25
- collection.forEach(document => {
26
- documents.push({
27
- reference: {
28
- collection: reference,
29
- id: document.id
30
- },
31
- data: document.data()
32
- });
33
- });
34
- return documents;
138
+ const getCollection = async (reference, params = {}) => {
139
+ checkQuery(params);
140
+ const conditions = withoutVacuousConditions(reference, params.where ?? []);
141
+ const queried = sentToStore(reference, conditions);
142
+ const fields = inequalityFields(reference, queried);
143
+ const firstToken = params.pageToken;
144
+ if (firstToken !== undefined)
145
+ cursorValues(firstToken, fields);
146
+ if (matchesNothing(reference, conditions))
147
+ return { documents: [] };
148
+ const base = orderedQuery(filteredQuery(firestore.collection(reference.name), reference, queried), fields);
149
+ return await pageOf({ base, collection: reference, conditions, fields, limit: params.limit }, firstToken);
35
150
  };
36
151
  const getDocument = async ({ collection, id }) => {
152
+ if (!isStorableId(id))
153
+ return undefined;
37
154
  const document = await firestore.collection(collection.name).doc(id).get();
38
155
  if (!document.exists)
39
156
  return undefined;
40
- const documentReference = {
41
- collection,
42
- id
43
- };
44
- const documentSnapshot = {
45
- reference: documentReference,
46
- data: document.data()
47
- };
48
- return documentSnapshot;
157
+ return { reference: { collection, id }, data: withKey(collection, id, document.data()) };
49
158
  };
50
- const updateDocument = async (reference, document) => {
51
- await firestore.collection(reference.collection.name).doc(reference.id).update(document);
52
- return {
53
- reference,
54
- data: document
55
- };
159
+ const updateDocument = async (reference, data) => {
160
+ const given = withoutIgnoredKey(reference, data);
161
+ checkValues(given);
162
+ if (!isStorableId(reference.id))
163
+ throw new DocumentNotFoundError(reference);
164
+ const [field, value, ...rest] = updateArguments(given);
165
+ const document = firestore.collection(reference.collection.name).doc(reference.id);
166
+ try {
167
+ if (field === undefined)
168
+ await requireExisting(document, reference);
169
+ else
170
+ await document.update(field, value, ...rest);
171
+ }
172
+ catch (error) {
173
+ if (errorCode(error) === NOT_FOUND)
174
+ throw new DocumentNotFoundError(reference);
175
+ throw error;
176
+ }
177
+ const snapshot = { reference, data };
178
+ return snapshot;
56
179
  };
57
180
  const deleteDocument = async (reference) => {
181
+ if (!isStorableId(reference.id))
182
+ return;
58
183
  await firestore.collection(reference.collection.name).doc(reference.id).delete();
59
184
  };
60
185
  return {
@@ -1,18 +1,35 @@
1
1
  import { defineRuntime } from '@genoacms/contracts';
2
- import { PreconditionFailedError } from '@genoacms/contracts/storage';
2
+ import { PreconditionFailedError, ObjectNotFoundError, NotADirectoryError, isDirectoryName } from '@genoacms/contracts/storage';
3
3
  import { Storage } from '@google-cloud/storage';
4
4
  const HTTP_PRECONDITION_FAILED = 412;
5
+ const HTTP_NOT_FOUND = 404;
5
6
  const DELETE_CONCURRENCY = 10;
6
- // STO-9, GF21
7
- function requestedResults(limit, startAfter) {
8
- return limit !== undefined && startAfter !== undefined ? limit + 1 : limit;
7
+ const hasStatus = (error, status) => error?.code === status;
8
+ // STO-4, STO-7, STOR-16
9
+ async function rejectingMissing(reference, call) {
10
+ try {
11
+ return await call();
12
+ }
13
+ catch (error) {
14
+ if (hasStatus(error, HTTP_NOT_FOUND))
15
+ throw new ObjectNotFoundError(reference);
16
+ throw error;
17
+ }
9
18
  }
10
19
  // STO-9
11
- const byUtf8Bytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
12
- // STO-9
13
- function firstByName(names, limit) {
14
- const sorted = [...names].sort(byUtf8Bytes);
15
- return new Set(limit === undefined ? sorted : sorted.slice(0, limit));
20
+ function listingQuery(name, { limit, startAfter, pageToken }) {
21
+ return {
22
+ prefix: name,
23
+ delimiter: '/',
24
+ autoPaginate: false,
25
+ ...(limit === undefined ? {} : { maxResults: limit }),
26
+ ...(startAfter === undefined ? {} : { startOffset: startAfter }),
27
+ ...(pageToken === undefined ? {} : { pageToken })
28
+ };
29
+ }
30
+ // STO-11, GF38
31
+ function everyDepthPage(prefix, pageToken) {
32
+ return pageToken === undefined ? { prefix, autoPaginate: false } : { prefix, autoPaginate: false, pageToken };
16
33
  }
17
34
  // STO-11, GF29
18
35
  async function deleteAtMost(concurrency, files) {
@@ -46,6 +63,16 @@ export default defineRuntime({
46
63
  throw new Error('bucket-unregistered');
47
64
  return storage.bucket(name);
48
65
  };
66
+ // STO-3, STOR-3
67
+ const requireDirectoryName = (reference, { allowRoot }) => {
68
+ if (!isDirectoryName(reference.name) || (!allowRoot && reference.name === ''))
69
+ throw new NotADirectoryError(reference);
70
+ };
71
+ const getDirectoryBucket = (reference, options) => {
72
+ const bucketInstance = getBucket(reference.bucket);
73
+ requireDirectoryName(reference, options);
74
+ return bucketInstance;
75
+ };
49
76
  // STO-4
50
77
  const getObject = async ({ bucket, name }) => {
51
78
  const bucketInstance = getBucket(bucket);
@@ -55,7 +82,9 @@ export default defineRuntime({
55
82
  const [metadata] = await file.getMetadata();
56
83
  version = metadata.generation === undefined ? undefined : String(metadata.generation);
57
84
  }
58
- catch {
85
+ catch (error) {
86
+ if (hasStatus(error, HTTP_NOT_FOUND))
87
+ throw new ObjectNotFoundError({ bucket, name });
59
88
  version = undefined;
60
89
  }
61
90
  return {
@@ -80,16 +109,16 @@ export default defineRuntime({
80
109
  const uploadObject = async ({ bucket, name }, stream, options) => {
81
110
  const bucketInstance = getBucket(bucket);
82
111
  const file = bucketInstance.file(name);
83
- const { ifVersion, ifAbsent, ...saveOptions } = options ?? {};
112
+ const { ifVersion, ifAbsent } = options ?? {};
84
113
  // STO-6
85
114
  const generation = ifAbsent === true ? 0 : ifVersion === undefined ? undefined : Number(ifVersion);
86
115
  try {
87
116
  await file.save(stream, generation === undefined
88
- ? saveOptions
89
- : { ...saveOptions, preconditionOpts: { ifGenerationMatch: generation } });
117
+ ? {}
118
+ : { preconditionOpts: { ifGenerationMatch: generation } });
90
119
  }
91
120
  catch (error) {
92
- if (error.code === HTTP_PRECONDITION_FAILED) {
121
+ if (hasStatus(error, HTTP_PRECONDITION_FAILED)) {
93
122
  throw new PreconditionFailedError({ bucket, name }, ifAbsent === true
94
123
  ? 'object already exists'
95
124
  : 'object changed since it was read');
@@ -105,26 +134,22 @@ export default defineRuntime({
105
134
  const deleteObject = async ({ bucket, name }) => {
106
135
  const bucketInstance = getBucket(bucket);
107
136
  const file = bucketInstance.file(name);
108
- await file.delete();
137
+ await rejectingMissing({ bucket, name }, async () => await file.delete());
109
138
  };
110
- const listDirectory = async ({ bucket, name }, listingParams = {}) => {
111
- const bucketInstance = getBucket(bucket);
112
- const options = {
113
- autoPaginate: false,
114
- prefix: name,
115
- maxResults: requestedResults(listingParams?.limit, listingParams?.startAfter),
116
- startOffset: listingParams?.startAfter,
117
- delimiter: '/'
118
- };
119
- let [files, , apiResponse] = (await bucketInstance.getFiles(options));
120
- files = files.filter((file) => !file.name.endsWith('.folderPlaceholder'));
121
- // STO-9, GF21
122
- const skipped = (itemName) => itemName === name || itemName === listingParams?.startAfter;
123
- files = files.filter(f => !skipped(f.name));
124
- const prefixes = (apiResponse?.prefixes ?? []).filter((item) => !skipped(item));
125
- const kept = firstByName([...files.map(f => f.name), ...prefixes], listingParams?.limit);
139
+ // STO-9, GF21
140
+ const listDirectory = async (reference, listingParams = {}) => {
141
+ const bucketInstance = getDirectoryBucket(reference, { allowRoot: true });
142
+ const { bucket, name } = reference;
143
+ if (listingParams.limit === 0)
144
+ return { files: [], directories: [] };
145
+ const [listed, nextQuery, apiResponse] = (await bucketInstance.getFiles(listingQuery(name, listingParams)));
146
+ const skipped = (itemName) => itemName === name || itemName === listingParams.startAfter;
147
+ const files = listed.filter(file => !file.name.endsWith('.folderPlaceholder') && !skipped(file.name));
148
+ const prefixes = (apiResponse?.prefixes ?? []).filter(item => !skipped(item));
149
+ const next = nextQuery?.pageToken;
126
150
  return {
127
- files: files.filter(f => kept.has(f.name)).map((file) => {
151
+ ...(next === undefined ? {} : { next }),
152
+ files: files.map((file) => {
128
153
  return {
129
154
  name: file.name,
130
155
  // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
@@ -132,7 +157,7 @@ export default defineRuntime({
132
157
  lastModified: new Date(file.metadata.updated)
133
158
  };
134
159
  }),
135
- directories: prefixes.filter((item) => kept.has(item)).map(i => {
160
+ directories: prefixes.map(i => {
136
161
  const object = {
137
162
  bucket,
138
163
  name: i
@@ -141,24 +166,28 @@ export default defineRuntime({
141
166
  })
142
167
  };
143
168
  };
144
- const createDirectory = async ({ bucket, name }) => {
145
- const bucketInstance = getBucket(bucket);
146
- const file = bucketInstance.file(`${name}/.folderPlaceholder`);
169
+ // STO-10, CD10
170
+ const createDirectory = async (reference) => {
171
+ const bucketInstance = getDirectoryBucket(reference, { allowRoot: false });
172
+ const file = bucketInstance.file(`${reference.name}.folderPlaceholder`);
147
173
  await file.save('');
148
174
  };
149
175
  // STO-11, GD7, GF29
150
- const deleteDirectory = async ({ bucket, name }) => {
151
- const bucketInstance = getBucket(bucket);
152
- let query = { prefix: name, autoPaginate: false };
153
- while (query !== undefined) {
154
- const [files, nextQuery] = await bucketInstance.getFiles(query);
176
+ const deleteDirectory = async (reference) => {
177
+ const bucketInstance = getDirectoryBucket(reference, { allowRoot: false });
178
+ let pageToken;
179
+ do {
180
+ const [files, nextQuery] = await bucketInstance.getFiles(everyDepthPage(reference.name, pageToken));
155
181
  await deleteAtMost(DELETE_CONCURRENCY, files);
156
- query = nextQuery ?? undefined;
157
- }
182
+ pageToken = nextQuery?.pageToken;
183
+ } while (pageToken !== undefined);
158
184
  };
159
185
  // STO-12, GD7, GF22
160
- const moveDirectory = async ({ bucket, name }, newName) => {
161
- const [files] = await getBucket(bucket).getFiles({ prefix: name });
186
+ const moveDirectory = async (reference, newName) => {
187
+ const bucketInstance = getDirectoryBucket(reference, { allowRoot: false });
188
+ requireDirectoryName({ bucket: reference.bucket, name: newName }, { allowRoot: false });
189
+ const { name } = reference;
190
+ const [files] = await bucketInstance.getFiles({ prefix: name });
162
191
  for (const file of files)
163
192
  await file.move(newName + file.name.slice(name.length));
164
193
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genoacms/adapter-gcp",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Implementation of abstraction layer of GenoaCMS for GCP",
6
6
  "repository": {
@@ -12,7 +12,7 @@
12
12
  "name": "Filip Holčík",
13
13
  "email": "filip.holcik.official@gmail.com"
14
14
  },
15
- "license": "ISC",
15
+ "license": "MIT",
16
16
  "bugs": {
17
17
  "url": "https://github.com/GenoaCMS/genoacms/issues"
18
18
  },
@@ -27,7 +27,7 @@
27
27
  "@google-cloud/storage": "^7.7.0",
28
28
  "archiver": "^7.0.0",
29
29
  "google-auth-library": "^9.15.1",
30
- "@genoacms/contracts": "^0.0.2",
30
+ "@genoacms/contracts": "^0.1.0",
31
31
  "@genoacms/sveltekit-adapter-cloud-run-functions": "^1.0.1"
32
32
  },
33
33
  "devDependencies": {
@@ -41,7 +41,7 @@
41
41
  "rimraf": "^5.0.5",
42
42
  "typescript": "^5.2.2",
43
43
  "vitest": "^3.2.7",
44
- "@genoacms/conformance": "^0.0.2"
44
+ "@genoacms/conformance": "^0.1.0"
45
45
  },
46
46
  "files": [
47
47
  "dist"