@engineers/gcloud-storage 0.0.8-temp → 2.0.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) 2021 Dibo
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.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # @engineers/gcloud-storage
2
+
3
+ google cloud storage
4
+
5
+ ## install
6
+
7
+ install the package and it's peer dependencies:
8
+
9
+ <!-- todo: peerDependencies.toString() -->
10
+
11
+ ```
12
+ npm i @engineers/gcloud-storage
13
+ ```
14
+
15
+ you can build this package and any of our packages yourself from [source](https://github.com/its-dibo/dibo/tree/main/packages)
16
+
17
+ ## contributing
18
+
19
+ contributing with us are very welcome.
20
+
21
+ read our [contributing guide](https://github.com/its-dibo/dibo/blob/main/CONTRIBUTING.md)
22
+
23
+ ## support us
24
+
25
+ - [paypal](https://paypal.me/group99001)
26
+
27
+ - [patreon](https://www.patreon.com/GoogleDev)
28
+
29
+ ## apps by `@engineers`
30
+
31
+ - [ngx-cms](https://github.com/its-dibo/dibo/tree/main/projects/ngx-cms)
32
+
33
+ - [social-control](https://github.com/its-dibo/dibo/tree/main/projects/social-control)
34
+
35
+ - [vscode](https://github.com/its-dibo/dibo/tree/main/projects/vscode)
36
+
37
+ ## useful packages by `@engineers`
38
+
39
+ - check out these useful packages that created by [@engineers organization](https://www.npmjs.com/org/engineers)
40
+
41
+ - [cache](https://www.npmjs.com/package/@engineers/cache)
42
+
43
+ - [databases](https://www.npmjs.com/package/@engineers/databases)
44
+
45
+ - [dom](https://www.npmjs.com/package/@engineers/dom)
46
+
47
+ - [express](https://www.npmjs.com/package/@engineers/express)
48
+
49
+ - [firebase-admin](https://www.npmjs.com/package/@engineers/firebase-admin)
50
+
51
+ - [gcloud-storage](https://www.npmjs.com/package/@engineers/gcloud-storage)
52
+
53
+ - [geo](https://www.npmjs.com/package/@engineers/geo)
54
+
55
+ - [graphics](https://www.npmjs.com/package/@engineers/graphics)
56
+
57
+ - [hookable](https://www.npmjs.com/package/@engineers/hookable)
58
+
59
+ - [javascript](https://www.npmjs.com/package/@engineers/javascript)
60
+
61
+ - [lazy-load](https://www.npmjs.com/package/@engineers/lazy-load)
62
+
63
+ - [mongoose](https://www.npmjs.com/package/@engineers/mongoose)
64
+
65
+ - [ngx-chat-firebase-mat](https://www.npmjs.com/package/@engineers/ngx-chat-firebase-mat)
66
+
67
+ - [ngx-content-core](https://www.npmjs.com/package/@engineers/ngx-content-core)
68
+
69
+ - [ngx-content-view-mat](https://www.npmjs.com/package/@engineers/ngx-content-view-mat)
70
+
71
+ - [ngx-formly](https://www.npmjs.com/package/@engineers/ngx-formly)
72
+
73
+ - [ngx-universal-express](https://www.npmjs.com/package/@engineers/ngx-universal-express)
74
+
75
+ - [ngx-utils](https://www.npmjs.com/package/@engineers/ngx-utils)
76
+
77
+ - [nodejs](https://www.npmjs.com/package/@engineers/nodejs)
78
+
79
+ - [rxjs](https://www.npmjs.com/package/@engineers/rxjs)
80
+
81
+ - [tmpl](https://www.npmjs.com/package/@engineers/tmpl)
82
+
83
+ - [updater](https://www.npmjs.com/package/@engineers/updater)
84
+
85
+ - [webpack](https://www.npmjs.com/package/@engineers/webpack)
package/index.d.ts CHANGED
@@ -1,48 +1,2 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import { Bucket, CreateBucketRequest, File, SaveOptions, Storage, UploadResponse, StorageOptions as _StorageOptions } from '@google-cloud/storage';
4
- import { PathLike } from 'node:fs';
5
- export interface StorageOptions extends _StorageOptions {
6
- bucket: string;
7
- rootDir?: string;
8
- }
9
- export interface UploadOptions {
10
- destination: string;
11
- }
12
- export interface DownloadOptions {
13
- destination?: string;
14
- encoding?: BufferEncoding | null;
15
- }
16
- export interface DeleteOptions {
17
- ignoreNotFound?: boolean;
18
- }
19
- export interface ExistsOptions {
20
- }
21
- export interface CreateBucketMeta extends CreateBucketRequest {
22
- labels?: {
23
- [key: string]: string;
24
- };
25
- }
26
- export default class {
27
- storage: Storage;
28
- bucket: Bucket;
29
- private baseDir;
30
- constructor(options: StorageOptions);
31
- upload(path: PathLike, options?: UploadOptions | string): Promise<UploadResponse | void>;
32
- download(file: PathLike | File, options?: DownloadOptions | string): Promise<Buffer | string | Array<any> | {
33
- [key: string]: any;
34
- } | void>;
35
- downloadAll(destination: PathLike, directory?: PathLike, filter?: RegExp | ((file: string) => boolean), options?: {
36
- start?: number;
37
- end?: number;
38
- }): Promise<{
39
- [key: string]: boolean;
40
- }>;
41
- write(path: PathLike, content?: any, options?: SaveOptions): Promise<any>;
42
- read(file: PathLike | File, options?: DownloadOptions | string): Promise<string | void | any[] | Buffer | {
43
- [key: string]: any;
44
- }>;
45
- delete(path: PathLike, options?: DeleteOptions): Promise<any>;
46
- exists(path: PathLike, options?: ExistsOptions): Promise<boolean>;
47
- create(metaData?: CreateBucketMeta): Promise<import("@google-cloud/storage").CreateBucketResponse>;
48
- }
1
+ export * from './src';
2
+ export { default as Storage } from './src';
package/index.js CHANGED
@@ -1,297 +1,5 @@
1
- // src/index.ts
2
- import {
3
- Storage
4
- } from "@google-cloud/storage";
5
- import { mkdirSync } from "node:fs";
6
- import { dirname, resolve } from "node:path";
7
- import stripJsonComments from "strip-json-comments";
8
- import { URL } from "node:url";
9
-
10
- // ../javascript/src/objects.ts
11
- function objectType(object) {
12
- return Object.prototype.toString.call(object).replace("[object ", "").replace("]", "").toLowerCase();
13
- }
14
-
15
- // ../javascript/src/string.ts
16
- function cleanString(value, options = {}) {
17
- let opts = {
18
- // remove '//' comments
19
- // it is better to disable this option to avoid removing comment-like strings by mistake
20
- // suc as `https://`
21
- removeComments: false,
22
- // remove break lines for multi-line string
23
- removeBreakLines: true,
24
- // trim each line of the multi-line string
25
- trim: false,
26
- ...options
27
- };
28
- if (opts.removeComments)
29
- value = value.replace(/\s*\/\/.*$/gm, "");
30
- if (opts.removeBreakLines)
31
- value = value.split("\n").map((line) => opts.trim ? line.trim() : line).join("");
32
- if (opts.trim)
33
- value = value.trim();
34
- return value;
35
- }
36
-
37
- // ../javascript/src/regex.ts
38
- function escape(value) {
39
- return value.replace(/[$()*+./?[\\\]^{|}]/g, "\\$&");
40
- }
41
- function clean(value, options = {}) {
42
- value = cleanString(value, options);
43
- return options.escape ? escape(value) : value;
44
- }
45
- function toRegExp(value, optionsOrFlags = {}) {
46
- let opts = {
47
- delimiter: "",
48
- ...typeof optionsOrFlags === "string" ? { flags: optionsOrFlags } : optionsOrFlags
49
- };
50
- if (typeof value === "string") {
51
- value = clean(value, opts);
52
- } else if (Array.isArray(value)) {
53
- value = value.map(
54
- (element) => (
55
- // we don't need to escape a RegExp pattern, only escape strings
56
- `(?:${element instanceof RegExp ? element.source : clean(element.toString(), opts)})`
57
- )
58
- ).join(opts.delimiter);
59
- } else if (value instanceof RegExp) {
60
- } else {
61
- throw new TypeError(`value ${value} must be of type Pattern`);
62
- }
63
- return new RegExp(value, opts.flags);
64
- }
65
-
66
- // ../javascript/src/patterns.ts
67
- var ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d)\.?){4}$/;
68
- var v6segment = "[a-fA-F\\d]{1,4}";
69
- var ipv6 = toRegExp(
70
- `(?:(?:${v6segment}:){7}(?:${v6segment}|:)|(?:${v6segment}:){6}(?:${ipv4}|:${v6segment}|:)|(?:${v6segment}:){5}(?::${ipv4}|(?::${v6segment}){1,2}|:)| (?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${ipv4}|(?::${v6segment}){1,3}|:)| (?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${ipv4}|(?::${v6segment}){1,4}|:)|(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${ipv4}|(?::${v6segment}){1,5}|:)|(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${ipv4}|(?::${v6segment}){1,6}|:)|(?::(?:(?::${v6segment}){0,5}:${ipv4}|(?::${v6segment}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?`,
71
- { removeComments: false }
72
- );
73
- var ip = toRegExp([ipv4, ipv6], { delimiter: "|" });
74
- var rootDomain = /^([\dA-Za-z][\dA-Za-z-]{2,62})\.(\w{2,3})(?:\.([A-Za-z]{2}))?$/;
75
- var domain = toRegExp(
76
- [
77
- // subdomain
78
- // todo: RegExp captures the latest group match only, instead of capturing all of the repeating patterns
79
- // https://stackoverflow.com/a/37004214/12577650
80
- /^((?:([\dA-Za-z][\dA-Za-z-]{0,62})+\.)*)/,
81
- // remove the first '^' from '^---' or '(?:^---)'
82
- rootDomain.source.replace("^", "")
83
- ],
84
- { delimiter: "" }
85
- );
86
- var email = toRegExp([/^([a-z]+\w+)@/, domain.source.replace("^", "")], {
87
- delimiter: ""
88
- });
89
- var unallowedUrlChars = ` "'\`
90
- <>[\\]`;
91
- var tdl = "com|net|org";
92
- var link = toRegExp(
93
- `((?:ftp|https?://[^${unallowedUrlChars}]+)|(?:[^${unallowedUrlChars}\\/]+\\.(?:${tdl})(?:\\.[a-z]{2}){0,1}))(?::d+)?(?:/[^${unallowedUrlChars}]+)*`,
94
- { flags: "gi" }
95
- );
96
- var plainLink = toRegExp(
97
- [
98
- link,
99
- // doesn't followed by '*</a>', i.e: doesn't exist inside <a> tag (plain links only)
100
- // https://stackoverflow.com/a/68188492/12577650
101
- `(?![^<]*</a>)`
102
- ],
103
- { delimiter: "" }
104
- );
105
-
106
- // src/index.ts
107
- var src_default = class {
108
- storage;
109
- bucket;
110
- baseDir;
111
- /**
112
- * creates a new bucket
113
- *
114
- * @function constructor
115
- * @param options
116
- * @param bucket
117
- */
118
- // todo: if(bucket instanceof admin.Bucket)this.bucket=bucket
119
- // constructor();
120
- constructor(options) {
121
- let opts = { ...options };
122
- if (!opts.keyFile && !opts.keyFilename && !opts.credentials && process.env.gcloud_service_account_storage) {
123
- opts.credentials = JSON.parse(process.env.gcloud_service_account_storage);
124
- }
125
- this.storage = new Storage(opts);
126
- if (opts.bucket.includes("/")) {
127
- let parts = opts.bucket.split("/");
128
- opts.bucket = parts.shift();
129
- this.baseDir = parts.join("/") + opts.rootDir ? "/" + opts.rootDir : "";
130
- }
131
- this.bucket = this.storage.bucket(opts.bucket);
132
- }
133
- /**
134
- * uploads a file to the current bucket
135
- *
136
- * @function upload
137
- * @param file file path
138
- * @param path
139
- * @param options UploadOptions object or destination path as string
140
- * @returns Promise<UploadResponse>; //UploadResponse=[File, API request]
141
- */
142
- // todo: upload / download a folder
143
- upload(path, options) {
144
- let opts = {
145
- ...typeof options === "string" ? { destination: options } : options || {}
146
- };
147
- if (this.baseDir && opts?.destination) {
148
- opts.destination = `${this.baseDir}/${opts.destination}`;
149
- }
150
- return this.bucket.upload(path.toString(), opts);
151
- }
152
- /**
153
- * downloads a file
154
- *
155
- * @function download
156
- * @param file file path
157
- * @param options DownloadOptions object or destination as string
158
- * @returns Promise that resolves to:
159
- * - void: if options.destination used
160
- * - Buffer: if options.encoding is undefined
161
- * - Array or plain object: if the file is json
162
- * - string: otherwise
163
- */
164
- // todo: if(!options.destination)return th content as Promise<Buffer | ...>
165
- // otherwise write the content into a local destination and return boolean
166
- download(file, options) {
167
- if (typeof file === "string" || file instanceof Buffer || file instanceof URL) {
168
- file = this.bucket.file(
169
- this.baseDir ? `${this.baseDir}/${file.toString()}` : file.toString()
170
- );
171
- }
172
- let opts = Object.assign(
173
- { encoding: null },
174
- typeof options === "string" ? { destination: options } : options || {}
175
- );
176
- if (opts.destination) {
177
- mkdirSync(dirname(opts.destination), { recursive: true });
178
- }
179
- return file.download({ ...opts }).then((result) => {
180
- if (opts.destination) {
181
- return;
182
- }
183
- let data = result[0];
184
- if (opts.encoding === void 0) {
185
- return data;
186
- }
187
- let dataString = data.toString();
188
- try {
189
- return file.name.slice(-5) === ".json" ? JSON.parse(stripJsonComments(dataString)) : dataString;
190
- } catch {
191
- return dataString;
192
- }
193
- });
194
- }
195
- /**
196
- * download all files from a directory that match the provided filter
197
- *
198
- * @param destination the local path to download the files to
199
- * @param directory the directory to be downloaded
200
- * @param filter a pattern or function to filter the files to be downloaded
201
- * @param options
202
- * @param options.start download all files starting from the specified one (paginating behavior) (default is the first file)
203
- * @param options.end download all files until the specified file (default is the last file)
204
- * @returns a map of {file: result}
205
- */
206
- downloadAll(destination, directory, filter, options = {}) {
207
- options = Object.assign({ start: 0, end: void 0 }, options || {});
208
- let results = {};
209
- if (!filter) {
210
- filter = (file) => true;
211
- } else if (filter instanceof RegExp) {
212
- filter = (file) => filter.test(file);
213
- }
214
- if (this.baseDir) {
215
- directory = `${this.baseDir}/${directory}`;
216
- }
217
- return this.bucket.getFiles({ prefix: directory?.toString() }).then((files) => files[0].filter((file) => filter(file.name))).then(
218
- (files) => Promise.all(
219
- files.slice(options.start, options.end).map(
220
- (file) => this.download(file, {
221
- destination: resolve(`${destination.toString()}/${file.name}`)
222
- }).then((result) => {
223
- results[file.name] = true;
224
- }).catch((error) => {
225
- results[file.name] = false;
226
- })
227
- )
228
- ).then(() => results)
229
- );
230
- }
231
- /**
232
- * writes a content to a file in the bucket
233
- *
234
- * @param path bucket path
235
- * @param content the content to be written. if no content provided, an empty file is created
236
- * @param options
237
- * @returns the original content
238
- */
239
- write(path, content = "", options) {
240
- if (this.baseDir) {
241
- path = `${this.baseDir}/${path}`;
242
- }
243
- return this.bucket.file(path.toString()).save(
244
- ["array", "object"].includes(objectType(content)) ? JSON.stringify(content) : content,
245
- options
246
- ).then(() => content);
247
- }
248
- /** an alias to download() to be compatible with node:fs functions */
249
- read(file, options) {
250
- return this.download(file, options);
251
- }
252
- // eslint-disable-next-line no-secrets/no-secrets
253
- // https://stackoverflow.com/a/64539948/12577650
254
- delete(path, options) {
255
- if (this.baseDir) {
256
- path = `${this.baseDir}/${path}`;
257
- }
258
- return this.bucket.file(path.toString()).delete(options);
259
- }
260
- /**
261
- * check if a file exists in the bucket
262
- * this method works with files only, not folders
263
- * folders doesn't actually exist
264
- * https://cloud.google.com/storage/docs/folders
265
- *
266
- * @param path file path
267
- * @param options
268
- * @returns boolean
269
- */
270
- exists(path, options) {
271
- if (this.baseDir) {
272
- path = `/${this.baseDir}/${path}`;
273
- }
274
- return this.bucket.file(path.toString()).exists(options).then((result) => result[0]);
275
- }
276
- /**
277
- * create a new bucket, and optionally add labels to it
278
- * add the desired labels as key-value pairs to metaData.labels
279
- * https://cloud.google.com/storage/docs/using-bucket-labels#storage-modify-bucket-label-nodejs
280
- *
281
- * @param metaData
282
- * @returns
283
- */
284
- create(metaData) {
285
- let bucketName = this.bucket.name;
286
- let { labels, ...meta } = metaData || {};
287
- return this.storage.createBucket(bucketName, meta).then((result) => {
288
- this.bucket.name = bucketName;
289
- return labels ? this.bucket.setLabels(labels).then(() => result) : result;
290
- });
291
- }
292
- // todo: read(file:string):Buffer
293
- // todo: delete folder
294
- };
1
+ export * from "./src";
2
+ import { default as default2 } from "./src";
295
3
  export {
296
- src_default as default
4
+ default2 as Storage
297
5
  };
package/nx.json ADDED
@@ -0,0 +1,177 @@
1
+ {
2
+ "$schema": "./node_modules/nx/schemas/nx-schema.json",
3
+ "targetDefaults": {
4
+ "build": {
5
+ "executor": "@engineers/nx-manager:universal-builder",
6
+ "dependsOn": ["typecheck", "prebuild", "^build"],
7
+ "cache": true,
8
+ "inputs": ["default", "^default"],
9
+ "outputs": ["{projectRoot}/dist"],
10
+ "options": {
11
+ "forceRnDefaultPostBuild": true
12
+ }
13
+ },
14
+ "serve": {
15
+ "executor": "nx:run-commands",
16
+ "dependsOn": ["build", "preserve"],
17
+ "continuous": true,
18
+ "options": {
19
+ "cwd": "{projectRoot}",
20
+ "command": "NODE_ENV=development pnpm tsx --env-file-if-exists=.env --env-file-if-exists=.env.local dist/main.js"
21
+ },
22
+ "configurations": {
23
+ "production": {
24
+ "command": "NODE_ENV=production pnpm tsx --env-file-if-exists=.env --env-file-if-exists=.env.local --env-file-if-exists=.env.production --env-file-if-exists=.env.production.local dist/main.js"
25
+ }
26
+ }
27
+ },
28
+ "nx-release-publish": {
29
+ "options": {
30
+ "packageRoot": "{projectRoot}/dist"
31
+ }
32
+ },
33
+ "semantic-release": {
34
+ "executor": "nx:run-commands",
35
+ "dependsOn": ["build", "prerelease"],
36
+ "options": {
37
+ "cwd": "{projectRoot}",
38
+ "command": "pnpm tsx node_modules/semantic-release/bin/semantic-release.js"
39
+ },
40
+ "configurations": {
41
+ "local": {
42
+ "command": "DOTENV_CONFIG_PATH=../../.env pnpm run release --no-ci"
43
+ },
44
+ "dry": {
45
+ "command": "DOTENV_CONFIG_PATH=../../.env pnpm run release --no-ci --dry-run"
46
+ }
47
+ }
48
+ },
49
+ "test": {
50
+ "inputs": ["test"],
51
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
52
+ "dependsOn": ["^build", "pretest"],
53
+ "configurations": {
54
+ "unit": {
55
+ "args": [
56
+ "--testPathIgnorePatterns '.*\\.e2e\\.spec\\.ts$'",
57
+ "--testPathIgnorePatterns '/.*-e2e/'",
58
+ "--testPathIgnorePatterns '/.*-e2e/'"
59
+ ]
60
+ },
61
+ "e2e": {
62
+ "args": [
63
+ "--testMatch '**/*-e2e/**/*.{spec,test}.[mc]?[jt]s?(x)'",
64
+ "--testMatch '**/e2e/**/*.{spec,test}.[mc]?[jt]s?(x)'",
65
+ "--testMatch '**/*.e2e.(spec|test).?([mc])[jt]s?(x)'"
66
+ ]
67
+ }
68
+ }
69
+ },
70
+ "@angular/build:application": {
71
+ "cache": true,
72
+ "dependsOn": ["prebuild", "^build"],
73
+ "inputs": ["default", "^default"]
74
+ },
75
+ "@nx/angular:package": {
76
+ "cache": true,
77
+ "dependsOn": ["^build"],
78
+ "inputs": ["default", "^default"],
79
+ "outputs": ["{projectRoot}/dist"],
80
+ "options": {
81
+ "project": "{projectRoot}/ng-package.json",
82
+ "tsConfig": "{projectRoot}/tsconfig.lib.json"
83
+ }
84
+ },
85
+ "@nx/js:tsc": {
86
+ "cache": true,
87
+ "dependsOn": ["^build"],
88
+ "inputs": ["default", "^default"]
89
+ }
90
+ },
91
+ "namedInputs": {
92
+ "default": [
93
+ "{projectRoot}/src/**/*",
94
+ "!{projectRoot}/**/*.(spec|test)(.e2e)?.[tj]sx?",
95
+ "!{projectRoot}/**/e2e/**/*",
96
+ "{projectRoot}/.env(.*)?",
97
+ "{workspaceRoot}/tasks/(post-)?build.ts",
98
+ "{projectRoot}/(project|package|tsconfig)(.+)?.json",
99
+ "{workspaceRoot}/tsconfig.base.json",
100
+ {
101
+ "runtime": "node --version"
102
+ },
103
+ {
104
+ "env": "NODE_ENV"
105
+ }
106
+ ],
107
+ "test": [
108
+ "default",
109
+ "{projectRoot}/tsconfig.spec.json",
110
+ "{projectRoot}/jest.config.[jt]s",
111
+ "{workspaceRoot}/jest.config.[jt]s",
112
+ "{projectRoot}/**/*.(spec|test)(.e2e)?.[jt]sx?",
113
+ "{projectRoot}/**/e2e/**/*.[jt]sx?",
114
+ {
115
+ "externalDependencies": ["jest"]
116
+ }
117
+ ]
118
+ },
119
+ "plugins": [
120
+ {
121
+ "plugin": "@nx/js/typescript",
122
+ "options": {
123
+ "typecheck": {
124
+ "targetName": "typecheck"
125
+ },
126
+ "build": false
127
+ }
128
+ },
129
+ {
130
+ "plugin": "@nx/jest/plugin",
131
+ "options": {
132
+ "targetName": "test",
133
+ "ciTargetName": "test-ci"
134
+ }
135
+ }
136
+ ],
137
+ "tasksRunnerOptions": {
138
+ "default": {
139
+ "options": {
140
+ "useDaemonProcess": false
141
+ }
142
+ }
143
+ },
144
+ "generators": {
145
+ "@nx/angular:library": {
146
+ "linter": "eslint",
147
+ "unitTestRunner": "jest"
148
+ },
149
+ "@nx/angular:component": {
150
+ "style": "scss"
151
+ }
152
+ },
153
+ "release": {
154
+ "projectsRelationship": "independent",
155
+ "version": {
156
+ "conventionalCommits": true,
157
+ "updateDependents": "always",
158
+ "preVersionCommand": "pnpm nx run-many -t build",
159
+ "manifestRootsToUpdate": [
160
+ "{projectRoot}",
161
+ {
162
+ "path": "{projectRoot}/dist",
163
+ "preserveLocalDependencyProtocols": false
164
+ }
165
+ ]
166
+ },
167
+ "releaseTag": {
168
+ "pattern": "{projectName}@{version}"
169
+ },
170
+ "changelog": {
171
+ "projectChangelogs": true
172
+ }
173
+ },
174
+ "sync": {
175
+ "applyChanges": false
176
+ }
177
+ }
package/package.json CHANGED
@@ -1,14 +1,66 @@
1
1
  {
2
2
  "name": "@engineers/gcloud-storage",
3
- "version": "0.0.8-temp",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
- "private": false,
6
5
  "description": "google cloud storage",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
7
10
  "dependencies": {
8
- "@google-cloud/storage": "^6.10.1",
9
- "strip-json-comments": "^5.0.1"
11
+ "@google-cloud/storage": "^7.18.0"
12
+ },
13
+ "nx": {
14
+ "projectType": "library",
15
+ "targets": {
16
+ "build": {},
17
+ "semantic-release": {}
18
+ }
10
19
  },
11
20
  "imports": {
12
- "#*": "./*"
13
- }
14
- }
21
+ "#*": "./src/*.js"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./index.d.js",
26
+ "default": "./index.js"
27
+ },
28
+ "./package.json": {
29
+ "default": "./package.json"
30
+ },
31
+ "./*": "./src/*"
32
+ },
33
+ "devDependencies": {
34
+ "@engineers/javascript": "2.0.2",
35
+ "@engineers/nodejs": "2.0.1",
36
+ "semantic-release": "^25.0.2",
37
+ "semantic-release-monorepo": "^8.0.2",
38
+ "tsx": "^4.21.0"
39
+ },
40
+ "engines": {
41
+ "node": "^18.19.1 || ^20.11.1 || >=22.0.0"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/its-dibo/dibo.git"
46
+ },
47
+ "author": "Sherif Eldeeb <sh.eldeeb.2010+github@gmail.com> (https://github.com/its-dibo)",
48
+ "homepage": "https://github.com/its-dibo/dibo#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/its-dibo/dibo/issues",
51
+ "email": "sh.eldeeb.2010+github@gmail.com"
52
+ },
53
+ "license": "MIT",
54
+ "contributors": [],
55
+ "funding": [
56
+ {
57
+ "type": "paypal",
58
+ "url": "https://paypal.me/group99001"
59
+ },
60
+ {
61
+ "type": "patreon",
62
+ "url": "https://www.patreon.com/GoogleDev"
63
+ }
64
+ ],
65
+ "scripts": {}
66
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { Bucket, type CreateBucketRequest, File, type SaveOptions, Storage, type UploadResponse, type StorageOptions as _StorageOptions } from '@google-cloud/storage';
2
+ import { type PathLike } from 'node:fs';
3
+ export interface StorageOptions extends _StorageOptions {
4
+ bucket: string;
5
+ rootDir?: string;
6
+ }
7
+ export interface UploadOptions {
8
+ destination: string;
9
+ }
10
+ export interface DownloadOptions {
11
+ destination?: string;
12
+ encoding?: BufferEncoding | null;
13
+ }
14
+ export interface DeleteOptions {
15
+ ignoreNotFound?: boolean;
16
+ }
17
+ export interface ExistsOptions {
18
+ }
19
+ export interface CreateBucketMeta extends CreateBucketRequest {
20
+ labels?: {
21
+ [key: string]: string;
22
+ };
23
+ }
24
+ export default class {
25
+ storage: Storage;
26
+ bucket: Bucket;
27
+ private baseDir;
28
+ constructor(options: StorageOptions);
29
+ upload(path: PathLike, options?: UploadOptions | string): Promise<UploadResponse | void>;
30
+ download(file: PathLike | File, options?: DownloadOptions | string): Promise<Buffer | string | Array<any> | {
31
+ [key: string]: any;
32
+ } | void>;
33
+ downloadAll(destination: PathLike, directory?: PathLike, filter?: RegExp | ((file: string) => boolean), options?: {
34
+ start?: number;
35
+ end?: number;
36
+ }): Promise<{
37
+ [key: string]: boolean;
38
+ }>;
39
+ write(path: PathLike, content?: any, options?: SaveOptions): Promise<any>;
40
+ read(file: PathLike | File, options?: DownloadOptions | string): Promise<string | void | any[] | Buffer<ArrayBufferLike> | {
41
+ [key: string]: any;
42
+ }>;
43
+ delete(path: PathLike, options?: DeleteOptions): Promise<any>;
44
+ exists(path: PathLike, options?: ExistsOptions): Promise<boolean>;
45
+ create(metaData?: CreateBucketMeta): Promise<import("@google-cloud/storage").CreateBucketResponse>;
46
+ }
package/src/index.js ADDED
@@ -0,0 +1,200 @@
1
+ import {
2
+ Storage
3
+ } from "@google-cloud/storage";
4
+ import { mkdirSync } from "node:fs";
5
+ import { dirname, resolve } from "node:path";
6
+ import { cleanJson, objectType } from "@engineers/javascript";
7
+ import { URL } from "node:url";
8
+ class src_default {
9
+ storage;
10
+ bucket;
11
+ baseDir;
12
+ /**
13
+ * creates a new bucket
14
+ *
15
+ * @function constructor
16
+ * @param options
17
+ * @param bucket
18
+ */
19
+ // todo: if(bucket instanceof admin.Bucket)this.bucket=bucket
20
+ // constructor();
21
+ constructor(options) {
22
+ let opts = { ...options };
23
+ if (!opts.keyFile && !opts.keyFilename && !opts.credentials && process.env.gcloud_service_account_storage) {
24
+ opts.credentials = JSON.parse(process.env.gcloud_service_account_storage);
25
+ }
26
+ this.storage = new Storage(opts);
27
+ if (opts.bucket.includes("/")) {
28
+ let parts = opts.bucket.split("/");
29
+ opts.bucket = parts.shift();
30
+ this.baseDir = parts.join("/") + opts.rootDir ? "/" + opts.rootDir : "";
31
+ }
32
+ this.bucket = this.storage.bucket(opts.bucket);
33
+ }
34
+ /**
35
+ * uploads a file to the current bucket
36
+ *
37
+ * @function upload
38
+ * @param file file path
39
+ * @param path
40
+ * @param options UploadOptions object or destination path as string
41
+ * @returns Promise<UploadResponse>; //UploadResponse=[File, API request]
42
+ */
43
+ // todo: upload / download a folder
44
+ upload(path, options) {
45
+ let opts = {
46
+ ...typeof options === "string" ? { destination: options } : options || {}
47
+ };
48
+ if (this.baseDir && opts?.destination) {
49
+ opts.destination = `${this.baseDir}/${opts.destination}`;
50
+ }
51
+ return this.bucket.upload(path.toString(), opts);
52
+ }
53
+ /**
54
+ * downloads a file
55
+ *
56
+ * @function download
57
+ * @param file file path
58
+ * @param options DownloadOptions object or destination as string
59
+ * @returns Promise that resolves to:
60
+ * - void: if options.destination used
61
+ * - Buffer: if options.encoding is undefined
62
+ * - Array or plain object: if the file is json
63
+ * - string: otherwise
64
+ */
65
+ // todo: if(!options.destination)return th content as Promise<Buffer | ...>
66
+ // otherwise write the content into a local destination and return boolean
67
+ download(file, options) {
68
+ if (typeof file === "string" || // note: TS doesn't narrow down the type `Buffer<ArrayBufferLike>`
69
+ // so, it'll still see the type of file as `File | Buffer<ArrayBufferLike>`
70
+ // you may need to explicitly use `<File>file`
71
+ file instanceof Buffer || file instanceof URL) {
72
+ file = this.bucket.file(
73
+ this.baseDir ? `${this.baseDir}/${file.toString()}` : file.toString()
74
+ );
75
+ }
76
+ let opts = Object.assign(
77
+ { encoding: null },
78
+ typeof options === "string" ? { destination: options } : options || {}
79
+ );
80
+ if (opts.destination) {
81
+ mkdirSync(dirname(opts.destination), { recursive: true });
82
+ }
83
+ return file.download({ ...opts }).then((result) => {
84
+ if (opts.destination) {
85
+ return;
86
+ }
87
+ let data = result[0];
88
+ if (opts.encoding === void 0) {
89
+ return data;
90
+ }
91
+ let dataString = data.toString();
92
+ try {
93
+ return file.name.slice(-5) === ".json" ? JSON.parse(cleanJson(dataString)) : dataString;
94
+ } catch {
95
+ return dataString;
96
+ }
97
+ });
98
+ }
99
+ /**
100
+ * download all files from a directory that match the provided filter
101
+ *
102
+ * @param destination the local path to download the files to
103
+ * @param directory the directory to be downloaded
104
+ * @param filter a pattern or function to filter the files to be downloaded
105
+ * @param options
106
+ * @param options.start download all files starting from the specified one (paginating behavior) (default is the first file)
107
+ * @param options.end download all files until the specified file (default is the last file)
108
+ * @returns a map of {file: result}
109
+ */
110
+ downloadAll(destination, directory, filter, options = {}) {
111
+ options = Object.assign({ start: 0, end: void 0 }, options || {});
112
+ let results = {};
113
+ if (!filter) {
114
+ filter = (_file) => true;
115
+ } else if (filter instanceof RegExp) {
116
+ filter = (file) => filter.test(file);
117
+ }
118
+ if (this.baseDir) {
119
+ directory = `${this.baseDir}/${directory}`;
120
+ }
121
+ return this.bucket.getFiles({ prefix: directory?.toString() }).then((files) => files[0].filter((file) => filter(file.name))).then(
122
+ (files) => Promise.all(
123
+ files.slice(options.start, options.end).map(
124
+ (file) => this.download(file, {
125
+ destination: resolve(`${destination.toString()}/${file.name}`)
126
+ }).then((_result) => {
127
+ results[file.name] = true;
128
+ }).catch((_error) => {
129
+ results[file.name] = false;
130
+ })
131
+ )
132
+ ).then(() => results)
133
+ );
134
+ }
135
+ /**
136
+ * writes a content to a file in the bucket
137
+ *
138
+ * @param path bucket path
139
+ * @param content the content to be written. if no content provided, an empty file is created
140
+ * @param options
141
+ * @returns the original content
142
+ */
143
+ write(path, content = "", options) {
144
+ if (this.baseDir) {
145
+ path = `${this.baseDir}/${path}`;
146
+ }
147
+ return this.bucket.file(path.toString()).save(
148
+ ["array", "object"].includes(objectType(content)) ? JSON.stringify(content) : content,
149
+ options
150
+ ).then(() => content);
151
+ }
152
+ /** an alias to download() to be compatible with node:fs functions */
153
+ read(file, options) {
154
+ return this.download(file, options);
155
+ }
156
+ // https://stackoverflow.com/a/64539948/12577650
157
+ delete(path, options) {
158
+ if (this.baseDir) {
159
+ path = `${this.baseDir}/${path}`;
160
+ }
161
+ return this.bucket.file(path.toString()).delete(options);
162
+ }
163
+ /**
164
+ * check if a file exists in the bucket
165
+ * this method works with files only, not folders
166
+ * folders doesn't actually exist
167
+ * https://cloud.google.com/storage/docs/folders
168
+ *
169
+ * @param path file path
170
+ * @param options
171
+ * @returns boolean
172
+ */
173
+ exists(path, options) {
174
+ if (this.baseDir) {
175
+ path = `/${this.baseDir}/${path}`;
176
+ }
177
+ return this.bucket.file(path.toString()).exists(options).then((result) => result[0]);
178
+ }
179
+ /**
180
+ * create a new bucket, and optionally add labels to it
181
+ * add the desired labels as key-value pairs to metaData.labels
182
+ * https://cloud.google.com/storage/docs/using-bucket-labels#storage-modify-bucket-label-nodejs
183
+ *
184
+ * @param metaData
185
+ * @returns
186
+ */
187
+ create(metaData) {
188
+ let bucketName = this.bucket.name;
189
+ let { labels, ...meta } = metaData || {};
190
+ return this.storage.createBucket(bucketName, meta).then((result) => {
191
+ this.bucket.name = bucketName;
192
+ return labels ? this.bucket.setLabels(labels).then(() => result) : result;
193
+ });
194
+ }
195
+ // todo: read(file:string):Buffer
196
+ // todo: delete folder
197
+ }
198
+ export {
199
+ src_default as default
200
+ };
@@ -0,0 +1,72 @@
1
+ import { afterAll, expect, test } from "@jest/globals";
2
+ import Storage from "./index";
3
+ import { read, remove, resolve, writeSync } from "@engineers/nodejs";
4
+ import { existsSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ let serviceAccount = resolve(__dirname, "./gcloud-service-account!!.json");
9
+ if (existsSync(serviceAccount)) {
10
+ let bucket = `dibo-testing/test!!/gcloud-storage`;
11
+ let storage = new Storage({ bucket, keyFilename: serviceAccount });
12
+ writeSync(__dirname + "/test~~/file.json", { ok: 1 });
13
+ afterAll(() => {
14
+ return Promise.all(
15
+ ["file.json"].map((file) => storage.delete(`${file}`))
16
+ ).then(() => remove(__dirname + "/test~~"));
17
+ });
18
+ test("upload", () => {
19
+ return storage.upload(__dirname + "/test~~/file.json", `file.json`).then((result) => {
20
+ let metadata = result[1];
21
+ expect(metadata.kind).toEqual("storage#object");
22
+ expect(metadata.name).toEqual(`test!!/gcloud-storage/file.json`);
23
+ expect(metadata.size).toEqual(8);
24
+ });
25
+ });
26
+ test("write", () => {
27
+ return expect(storage.write(`note.txt`, "ok")).resolves.not.toThrow();
28
+ });
29
+ test("download to a destination", () => {
30
+ let destination = __dirname + "/test~~/file.json";
31
+ return expect(
32
+ storage.download(`file.json`, destination)
33
+ ).resolves.not.toThrow();
34
+ });
35
+ test("download as Buffer", () => {
36
+ return storage.download(`file.json`).then((result) => {
37
+ expect(result).toMatchObject({ ok: 1 });
38
+ });
39
+ });
40
+ test("download non-existing file", () => {
41
+ return expect(storage.download(`non-existing.txt`)).rejects.toThrow(
42
+ "No such object"
43
+ );
44
+ });
45
+ test("download to a non-existing directory", () => {
46
+ let destination = __dirname + "/test~~/non-existing/file.json";
47
+ return storage.download(`file.json`, destination).then(() => read(destination)).then((result) => {
48
+ expect(result).toMatchObject({ ok: 1 });
49
+ });
50
+ return expect(
51
+ storage.download(`file.json`, destination)
52
+ ).resolves.not.toThrow();
53
+ });
54
+ test("delete", () => {
55
+ return storage.delete(`note.txt`).then((result) => {
56
+ expect(result).toBeTruthy();
57
+ });
58
+ });
59
+ test("delete non-existing file", () => {
60
+ return expect(storage.delete(`none-existing.txt`)).rejects.toThrow(
61
+ "No such object"
62
+ );
63
+ });
64
+ } else {
65
+ console.warn(
66
+ `testing for gcloud-storage skipped because the service account file does'nt exist
67
+ to run the test create "gcloud-service-account!!.json" contains your own service account
68
+ note that files that end with "!!" or "~~" don't be committed to the remote repository for security`
69
+ );
70
+ test("skip", () => {
71
+ });
72
+ }
package/index.spec.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};