@helloao/cli 0.0.6 → 0.0.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.
package/s3.js DELETED
@@ -1,169 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.askForAccessKeyProvider = exports.S3Uploader = void 0;
4
- exports.parseS3Url = parseS3Url;
5
- exports.getHttpUrl = getHttpUrl;
6
- exports.providerChain = providerChain;
7
- exports.defaultProviderForOptions = defaultProviderForOptions;
8
- const client_s3_1 = require("@aws-sdk/client-s3");
9
- const credential_providers_1 = require("@aws-sdk/credential-providers"); // ES6 import
10
- const prompts_1 = require("@inquirer/prompts");
11
- class S3Uploader {
12
- _client;
13
- _bucketName;
14
- _keyPrefix;
15
- get idealBatchSize() {
16
- return 50;
17
- }
18
- constructor(bucketName, keyPrefix, profile) {
19
- this._bucketName = bucketName;
20
- this._keyPrefix = keyPrefix;
21
- this._client = new client_s3_1.S3Client({
22
- credentials: !profile || typeof profile === 'string'
23
- ? (0, credential_providers_1.fromNodeProviderChain)({ profile: profile ?? undefined })
24
- : profile,
25
- });
26
- }
27
- async upload(file, overwrite) {
28
- const path = file.path.startsWith('/')
29
- ? file.path.substring(1)
30
- : file.path;
31
- const key = this._keyPrefix ? `${this._keyPrefix}/${path}` : path;
32
- const hash = file.sha256?.();
33
- const head = new client_s3_1.HeadObjectCommand({
34
- Bucket: this._bucketName,
35
- Key: key,
36
- ChecksumMode: 'ENABLED',
37
- });
38
- if (hash || !overwrite) {
39
- try {
40
- const existingFile = await this._client.send(head);
41
- let matches = true;
42
- if (hash && existingFile.ChecksumSHA256) {
43
- if (hash.localeCompare(existingFile?.ChecksumSHA256 ?? '', undefined, {
44
- sensitivity: 'base',
45
- }) === 0) {
46
- // File is already uploaded and matches the checksum.
47
- return false;
48
- }
49
- else {
50
- // File is already uploaded but the checksums don't match.
51
- matches = false;
52
- }
53
- }
54
- else {
55
- // File is already uploaded but the checksum is not available.
56
- console.log(`[s3] Checksum not available: ${key}`);
57
- }
58
- if (matches && !overwrite) {
59
- return false;
60
- }
61
- }
62
- catch (err) {
63
- if (err instanceof client_s3_1.NotFound) {
64
- // not found, so we can try to write the file.
65
- }
66
- else {
67
- throw err;
68
- }
69
- }
70
- }
71
- const command = new client_s3_1.PutObjectCommand({
72
- Bucket: this._bucketName,
73
- Key: key,
74
- Body: file.content,
75
- ContentType: 'application/json',
76
- ChecksumSHA256: hash,
77
- ChecksumAlgorithm: 'SHA256',
78
- });
79
- await this._client.send(command);
80
- return true;
81
- }
82
- }
83
- exports.S3Uploader = S3Uploader;
84
- /**
85
- * Parses the given S3 URL into its bucket name and object key.
86
- * @param url The URL to parse.
87
- */
88
- function parseS3Url(url) {
89
- const regex = /^s3:\/\/([a-z0-9.\-]+)(\/[^${}]*)?$/;
90
- const matched = url.match(regex);
91
- if (matched) {
92
- const arr = [...matched];
93
- let key = arr[2] ?? '';
94
- if (key.startsWith('/')) {
95
- key = key.substring(1);
96
- }
97
- return {
98
- bucketName: arr[1],
99
- objectKey: key,
100
- };
101
- }
102
- return undefined;
103
- }
104
- /**
105
- * Gets the HTTP URL for the given S3 URL.
106
- * @param s3Url The S3 URL to convert.
107
- */
108
- function getHttpUrl(s3Url) {
109
- const parsed = parseS3Url(s3Url);
110
- if (!parsed) {
111
- return undefined;
112
- }
113
- const { bucketName, objectKey } = parsed;
114
- if (objectKey) {
115
- return `https://${bucketName}.s3.amazonaws.com/${objectKey}`;
116
- }
117
- else {
118
- return `https://${bucketName}.s3.amazonaws.com`;
119
- }
120
- }
121
- /**
122
- * A provider that gets the credentials directly from the user input.
123
- */
124
- const askForAccessKeyProvider = async () => {
125
- const accessKeyId = await (0, prompts_1.input)({
126
- message: 'Enter your AWS Access Key ID',
127
- });
128
- const secretAccessKey = await (0, prompts_1.password)({
129
- message: 'Enter your AWS Secret Access Key',
130
- });
131
- return {
132
- accessKeyId,
133
- secretAccessKey,
134
- };
135
- };
136
- exports.askForAccessKeyProvider = askForAccessKeyProvider;
137
- /**
138
- * Defines a provider that tries to get the credentials from the given list of providers.
139
- * @param providers The providers to try.
140
- */
141
- function providerChain(...providers) {
142
- return async () => {
143
- for (const provider of providers) {
144
- const creds = await provider();
145
- if (creds?.accessKeyId && creds?.secretAccessKey) {
146
- return creds;
147
- }
148
- }
149
- return {
150
- accessKeyId: '',
151
- secretAccessKey: '',
152
- };
153
- };
154
- }
155
- /**
156
- * Gets the default provider for the given options.
157
- *
158
- * Defaults first to using the provided access key and secret access key, then to using the given profile, then finally to asking the user for the access key.
159
- * @param options
160
- */
161
- function defaultProviderForOptions(options) {
162
- if (options.accessKeyId && options.secretAccessKey) {
163
- return {
164
- accessKeyId: options.accessKeyId,
165
- secretAccessKey: options.secretAccessKey,
166
- };
167
- }
168
- return providerChain((0, credential_providers_1.fromNodeProviderChain)({ profile: options.profile }), exports.askForAccessKeyProvider);
169
- }
package/uploads.d.ts DELETED
@@ -1,83 +0,0 @@
1
- import { SerializedFile } from './db';
2
- import { Uploader } from './files';
3
- import { DatasetOutput } from '@helloao/tools/generation/dataset';
4
- import { PrismaClient } from './prisma-gen';
5
- import { GenerateApiOptions } from '@helloao/tools/generation/api';
6
- export interface UploadApiFromDatabaseOptions extends UploadApiOptions, GenerateApiOptions {
7
- /**
8
- * The number of files to upload in each batch.
9
- */
10
- batchSize: string | number;
11
- }
12
- export interface UploadApiOptions {
13
- /**
14
- * Whether to overwrite existing files.
15
- */
16
- overwrite?: boolean;
17
- /**
18
- * Whether to only overwrite common files.
19
- * "Common files" are files that are similar between translations, like the books.json endpoint, or individual chapter endpoints.
20
- */
21
- overwriteCommonFiles?: boolean;
22
- /**
23
- * The file pattern regex that should be used to filter the files that are uploaded.
24
- */
25
- filePattern?: string;
26
- /**
27
- * The translations to generate API files for.
28
- */
29
- translations?: string[];
30
- /**
31
- * The AWS profile to use for uploading to S3.
32
- */
33
- profile?: string;
34
- /**
35
- * The AWS access key ID to use for uploading to S3.
36
- */
37
- accessKeyId?: string;
38
- /**
39
- * The AWS secret access key to use for uploading to S3.
40
- */
41
- secretAccessKey?: string;
42
- /**
43
- * Whether to generate API files that use the common name instead of book IDs.
44
- */
45
- useCommonName?: boolean;
46
- /**
47
- * Whether to generate audio files for the API.
48
- */
49
- generateAudioFiles?: boolean;
50
- /**
51
- * Whether to generate pretty-printed JSON files.
52
- */
53
- pretty?: boolean;
54
- }
55
- /**
56
- * Loads and generates the API files from the database and uploads them to the specified destination.
57
- * @param db The database that the datasets should be loaded from.
58
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
59
- * @param options The options to use for the upload.
60
- */
61
- export declare function uploadApiFilesFromDatabase(db: PrismaClient, dest: string, options: UploadApiFromDatabaseOptions): Promise<void>;
62
- /**
63
- * Generates the API files from the given datasets and uploads them to the specified destination.
64
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
65
- * @param options The options to use for the upload.
66
- * @param datasets The datasets to generate the API files from.
67
- */
68
- export declare function serializeAndUploadDatasets(dest: string, datasets: AsyncIterable<DatasetOutput>, options?: UploadApiOptions & GenerateApiOptions): Promise<void>;
69
- /**
70
- * Uploads the given serialized files to the specified destination.
71
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
72
- * @param options The options to use for the upload.
73
- * @param datasets The datasets to generate the API files from.
74
- */
75
- export declare function uploadFiles(dest: string, options: UploadApiOptions, serializedFiles: AsyncIterable<SerializedFile[]>): Promise<void>;
76
- /**
77
- * Uploads the given serialized files using the given uploader.
78
- * @param uploader The uploader to use.
79
- * @param options The options to use for the upload.
80
- * @param datasets The datasets to generate the API files from.
81
- */
82
- export declare function uploadFilesUsingUploader(uploader: Uploader, options: UploadApiOptions, serializedFiles: AsyncIterable<SerializedFile[]>): Promise<void>;
83
- //# sourceMappingURL=uploads.d.ts.map
package/uploads.js DELETED
@@ -1,180 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.uploadApiFilesFromDatabase = uploadApiFilesFromDatabase;
4
- exports.serializeAndUploadDatasets = serializeAndUploadDatasets;
5
- exports.uploadFiles = uploadFiles;
6
- exports.uploadFilesUsingUploader = uploadFilesUsingUploader;
7
- const db_1 = require("./db");
8
- const s3_1 = require("./s3");
9
- const path_1 = require("path");
10
- const files_1 = require("./files");
11
- const node_stream_1 = require("node:stream");
12
- /**
13
- * Loads and generates the API files from the database and uploads them to the specified destination.
14
- * @param db The database that the datasets should be loaded from.
15
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
16
- * @param options The options to use for the upload.
17
- */
18
- async function uploadApiFilesFromDatabase(db, dest, options) {
19
- if (options.overwrite) {
20
- console.log('Overwriting existing files');
21
- }
22
- if (options.overwriteCommonFiles) {
23
- console.log('Overwriting only common files');
24
- }
25
- if (!!options.filePattern) {
26
- console.log('Using file pattern:', options.filePattern);
27
- }
28
- if (options.translations) {
29
- console.log('Generating for specific translations:', options.translations);
30
- }
31
- else {
32
- console.log('Generating for all translations');
33
- }
34
- if (options.pretty) {
35
- console.log('Generating pretty-printed JSON files');
36
- }
37
- const pageSize = typeof options.batchSize === 'number'
38
- ? options.batchSize
39
- : parseInt(options.batchSize);
40
- await serializeAndUploadDatasets(dest, (0, db_1.loadDatasets)(db, pageSize, options.translations), options);
41
- }
42
- /**
43
- * Generates the API files from the given datasets and uploads them to the specified destination.
44
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
45
- * @param options The options to use for the upload.
46
- * @param datasets The datasets to generate the API files from.
47
- */
48
- async function serializeAndUploadDatasets(dest, datasets, options = {}) {
49
- const overwrite = !!options.overwrite;
50
- if (overwrite) {
51
- console.log('Overwriting existing files');
52
- }
53
- const overwriteCommonFiles = !!options.overwriteCommonFiles;
54
- if (overwriteCommonFiles) {
55
- console.log('Overwriting only common files');
56
- }
57
- let filePattern;
58
- if (!!options.filePattern) {
59
- filePattern = new RegExp(options.filePattern, 'g');
60
- console.log('Using file pattern:', filePattern);
61
- }
62
- if (options.translations) {
63
- console.log('Generating for specific translations:', options.translations);
64
- }
65
- else {
66
- console.log('Generating for all translations');
67
- }
68
- if (options.pretty) {
69
- console.log('Generating pretty-printed JSON files');
70
- }
71
- const files = (0, db_1.serializeDatasets)(datasets, {
72
- ...options,
73
- });
74
- await uploadFiles(dest, options, files);
75
- }
76
- /**
77
- * Uploads the given serialized files to the specified destination.
78
- * @param dest The destination to upload the API files to. Supported destinations are S3, zip files, and local directories.
79
- * @param options The options to use for the upload.
80
- * @param datasets The datasets to generate the API files from.
81
- */
82
- async function uploadFiles(dest, options, serializedFiles) {
83
- let uploader;
84
- if (dest.startsWith('s3://')) {
85
- console.log('Uploading to S3');
86
- // Upload to S3
87
- const url = dest;
88
- const s3Url = (0, s3_1.parseS3Url)(url);
89
- if (!s3Url) {
90
- throw new Error(`Invalid S3 URL: ${url}`);
91
- }
92
- if (!s3Url.bucketName) {
93
- throw new Error(`Invalid S3 URL: ${url}\nUnable to determine bucket name`);
94
- }
95
- uploader = new s3_1.S3Uploader(s3Url.bucketName, s3Url.objectKey, (0, s3_1.defaultProviderForOptions)(options));
96
- }
97
- else if (dest.startsWith('console://')) {
98
- console.log('Uploading to console');
99
- uploader = {
100
- idealBatchSize: 50,
101
- async upload(file, _overwrite) {
102
- console.log(file.path);
103
- console.log(file.content);
104
- return true;
105
- },
106
- };
107
- }
108
- else if ((0, path_1.extname)(dest) === '.zip') {
109
- console.log('Writing to zip file:', dest);
110
- uploader = new files_1.ZipUploader(dest);
111
- }
112
- else if (dest) {
113
- console.log('Writing to local directory:', dest);
114
- uploader = new files_1.FilesUploader(dest);
115
- }
116
- else {
117
- console.error('Unsupported destination:', dest);
118
- process.exit(1);
119
- }
120
- try {
121
- await uploadFilesUsingUploader(uploader, options, serializedFiles);
122
- }
123
- finally {
124
- if (uploader && uploader.dispose) {
125
- await uploader.dispose();
126
- }
127
- }
128
- }
129
- /**
130
- * Uploads the given serialized files using the given uploader.
131
- * @param uploader The uploader to use.
132
- * @param options The options to use for the upload.
133
- * @param datasets The datasets to generate the API files from.
134
- */
135
- async function uploadFilesUsingUploader(uploader, options, serializedFiles) {
136
- const overwrite = !!options.overwrite;
137
- const overwriteCommonFiles = !!options.overwriteCommonFiles;
138
- let filePattern;
139
- if (!!options.filePattern) {
140
- filePattern = new RegExp(options.filePattern, 'g');
141
- }
142
- for await (let files of serializedFiles) {
143
- const batchSize = uploader.idealBatchSize ?? files.length;
144
- const totalBatches = Math.ceil(files.length / batchSize);
145
- console.log('Uploading', files.length, 'total files');
146
- console.log('Uploading in batches of', batchSize);
147
- let offset = 0;
148
- let batchNumber = 1;
149
- let batch = files.slice(offset, offset + batchSize);
150
- while (batch.length > 0) {
151
- console.log('Uploading batch', batchNumber, 'of', totalBatches);
152
- let writtenFiles = 0;
153
- const promises = batch.map(async (file) => {
154
- if (filePattern) {
155
- if (!filePattern.test(file.path)) {
156
- console.log('Skipping file:', file.path);
157
- return;
158
- }
159
- }
160
- const isAvailableTranslations = file.path.endsWith('available_translations.json');
161
- const isCommonFile = !isAvailableTranslations;
162
- if (await uploader.upload(file, overwrite || (overwriteCommonFiles && isCommonFile))) {
163
- writtenFiles++;
164
- }
165
- else {
166
- console.warn('File already exists:', file.path);
167
- console.warn('Skipping file');
168
- }
169
- if (file.content instanceof node_stream_1.Readable) {
170
- file.content.destroy();
171
- }
172
- });
173
- await Promise.all(promises);
174
- console.log('Wrote', writtenFiles, 'files');
175
- batchNumber++;
176
- offset += batchSize;
177
- batch = files.slice(offset, offset + batchSize);
178
- }
179
- }
180
- }