Update @actions/cache to 4.0.2

Version 3 of `@actions/cache` is now deprecated, and can cause runs to
fail; see https://github.com/actions/toolkit/blob/main/packages/cache/README.md.

I have no fucking clue why this was considered a major release; it's
explicitly documented as being entirely backwards-compatible. SemVer be
damned, amirite?
This commit is contained in:
mlugg
2025-03-10 17:01:15 +00:00
parent 0f2d1f2660
commit 0a889b2ab1
504 changed files with 921540 additions and 76 deletions
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../@protobuf-ts/protoc/protoc.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../@protobuf-ts/plugin/bin/protoc-gen-dump
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../@protobuf-ts/plugin/bin/protoc-gen-ts
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsc
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsserver
+68 -4
View File
@@ -5,10 +5,9 @@
"requires": true,
"packages": {
"node_modules/@actions/cache": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/@actions/cache/-/cache-3.3.0.tgz",
"integrity": "sha512-+eCsMTIZUEm+QA9GqjollOhCdvRrZ1JV8d9Rp34zVNizBkYITO8dhKczP5Xps1dFzc5n59p7vYVtZrGt18bb5Q==",
"deprecated": "Please upgrade to v4 or higher. See https://github.com/actions/toolkit/discussions/1890 for more details.",
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@actions/cache/-/cache-4.0.2.tgz",
"integrity": "sha512-cBr7JL1q+JKjbBd3w3SZN5OQ1Xg+/D8QLMcE7MpgpghZlL4biBO0ZEeraoTxCZyfN0YY0dxXlLgsgGv/sT5BTg==",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.11.1",
@@ -19,6 +18,7 @@
"@azure/abort-controller": "^1.1.0",
"@azure/ms-rest-js": "^2.6.0",
"@azure/storage-blob": "^12.13.0",
"@protobuf-ts/plugin": "^2.9.4",
"semver": "^6.3.1"
}
},
@@ -543,6 +543,57 @@
"@octokit/openapi-types": "^23.0.1"
}
},
"node_modules/@protobuf-ts/plugin": {
"version": "2.9.5",
"resolved": "https://registry.npmjs.org/@protobuf-ts/plugin/-/plugin-2.9.5.tgz",
"integrity": "sha512-KCzNRTFye837XdfPjS85gGzxgPGVDR3W8Px2G3etXuouNog9W+Cr+U0IBTFADrRWXC2x+OSNjXxrdZEiw+H5Cw==",
"license": "Apache-2.0",
"dependencies": {
"@protobuf-ts/plugin-framework": "^2.9.5",
"@protobuf-ts/protoc": "^2.9.5",
"@protobuf-ts/runtime": "^2.9.5",
"@protobuf-ts/runtime-rpc": "^2.9.5",
"typescript": "^3.9"
},
"bin": {
"protoc-gen-dump": "bin/protoc-gen-dump",
"protoc-gen-ts": "bin/protoc-gen-ts"
}
},
"node_modules/@protobuf-ts/plugin-framework": {
"version": "2.9.5",
"resolved": "https://registry.npmjs.org/@protobuf-ts/plugin-framework/-/plugin-framework-2.9.5.tgz",
"integrity": "sha512-DYNQ8Ga3xwPZMfaZGRCnDOcEdQZK9MorTXngVoFLnHWEE8zLhUjFVtdkChZtTih6rl8Z6akyA7hRgj/GrJF58Q==",
"license": "(Apache-2.0 AND BSD-3-Clause)",
"dependencies": {
"@protobuf-ts/runtime": "^2.9.5",
"typescript": "^3.9"
}
},
"node_modules/@protobuf-ts/protoc": {
"version": "2.9.5",
"resolved": "https://registry.npmjs.org/@protobuf-ts/protoc/-/protoc-2.9.5.tgz",
"integrity": "sha512-n6a7OHfr/Ubw483L6kNJB0wBCe/Ops0A652zB6J6nR2x1o+pjVFrMCeeQQsqxkYpQwQ8FCIETSxrMpfOBKTIvQ==",
"license": "Apache-2.0",
"bin": {
"protoc": "protoc.js"
}
},
"node_modules/@protobuf-ts/runtime": {
"version": "2.9.5",
"resolved": "https://registry.npmjs.org/@protobuf-ts/runtime/-/runtime-2.9.5.tgz",
"integrity": "sha512-SsumigRe3IqNTCQvVZUqDQExsKF72eyAMiWlYb5Jwj3eU4z8UH7JLlSfb/Wjidz4b/chTN6zh5AXBSKl0Asm3A==",
"license": "(Apache-2.0 AND BSD-3-Clause)"
},
"node_modules/@protobuf-ts/runtime-rpc": {
"version": "2.9.5",
"resolved": "https://registry.npmjs.org/@protobuf-ts/runtime-rpc/-/runtime-rpc-2.9.5.tgz",
"integrity": "sha512-NWAb1TaV4CR+BknZr1WRVT5Ws2AupVwGgRNes4oPAFrgLNXQotDFl2E6pmsjPwME8sAgJVzeSr7bUqQVyoAK2A==",
"license": "Apache-2.0",
"dependencies": {
"@protobuf-ts/runtime": "^2.9.5"
}
},
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
@@ -1124,6 +1175,19 @@
"node": ">=0.6.11 <=0.7.0 || >=0.7.3"
}
},
"node_modules/typescript": {
"version": "3.9.10",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.10.tgz",
"integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==",
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
}
},
"node_modules/undici": {
"version": "5.28.5",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.28.5.tgz",
+14 -2
View File
@@ -6,6 +6,20 @@ See ["Caching dependencies to speed up workflows"](https://docs.github.com/en/ac
Note that GitHub will remove any cache entries that have not been accessed in over 7 days. There is no limit on the number of caches you can store, but the total size of all caches in a repository is limited to 10 GB. If you exceed this limit, GitHub will save your cache but will begin evicting caches until the total size is less than 10 GB.
## ⚠️ Important changes
The cache backend service has been rewritten from the ground up for improved performance and reliability. The [@actions/cache](https://github.com/actions/toolkit/tree/main/packages/cache) package now integrates with the new cache service (v2) APIs.
The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in this release are **fully backward compatible**.
**All previous versions of this package will be deprecated**. We recommend upgrading to version `4.0.0` as soon as possible before **February 1st, 2025.**
If you do not upgrade, all workflow runs using any of the deprecated [@actions/cache](https://github.com/actions/toolkit/tree/main/packages/cache) packages will fail.
Upgrading to the recommended version should not break or require any changes to your workflows beyond updating your `package.json` to version `4.0.0`.
Read more about the change & access the migration guide: [reference to the announcement](https://github.com/actions/toolkit/discussions/1890).
## Usage
This package is used by the v2+ versions of our first party cache action. You can find an example implementation in the cache repo [here](https://github.com/actions/cache).
@@ -47,5 +61,3 @@ const cacheKey = await cache.restoreCache(paths, key, restoreKeys)
A cache gets downloaded in multiple segments of fixed sizes (now `128MB` to fail-fast, previously `1GB` for a `32-bit` runner and `2GB` for a `64-bit` runner were used). Sometimes, a segment download gets stuck which causes the workflow job to be stuck forever and fail. Version `v3.0.4` of cache package introduces a segment download timeout. The segment download timeout will allow the segment download to get aborted and hence allow the job to proceed with a cache miss.
Default value of this timeout is 10 minutes (starting `v3.2.1` and higher, previously 60 minutes in versions between `v.3.0.4` and `v3.2.0`, both included) and can be customized by specifying an [environment variable](https://docs.github.com/en/actions/learn-github-actions/environment-variables) named `SEGMENT_DOWNLOAD_TIMEOUT_MINS` with timeout value in minutes.
+2 -2
View File
@@ -15,8 +15,8 @@ export declare function isFeatureAvailable(): boolean;
* Restores cache from keys
*
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key
* @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching.
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
* @param downloadOptions cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
+230 -7
View File
@@ -37,7 +37,10 @@ const core = __importStar(require("@actions/core"));
const path = __importStar(require("path"));
const utils = __importStar(require("./internal/cacheUtils"));
const cacheHttpClient = __importStar(require("./internal/cacheHttpClient"));
const cacheTwirpClient = __importStar(require("./internal/shared/cacheTwirpClient"));
const config_1 = require("./internal/config");
const tar_1 = require("./internal/tar");
const constants_1 = require("./internal/constants");
class ValidationError extends Error {
constructor(message) {
super(message);
@@ -81,15 +84,39 @@ exports.isFeatureAvailable = isFeatureAvailable;
* Restores cache from keys
*
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key
* @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching.
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
* @param downloadOptions cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
function restoreCache(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
return __awaiter(this, void 0, void 0, function* () {
const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
core.debug(`Cache service version: ${cacheServiceVersion}`);
checkPaths(paths);
switch (cacheServiceVersion) {
case 'v2':
return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
case 'v1':
default:
return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive);
}
});
}
exports.restoreCache = restoreCache;
/**
* Restores cache using the legacy Cache Service
*
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching.
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
* @param options cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on Windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
return __awaiter(this, void 0, void 0, function* () {
restoreKeys = restoreKeys || [];
const keys = [primaryKey, ...restoreKeys];
core.debug('Resolved Keys:');
@@ -151,7 +178,85 @@ function restoreCache(paths, primaryKey, restoreKeys, options, enableCrossOsArch
return undefined;
});
}
exports.restoreCache = restoreCache;
/**
* Restores cache using Cache Service v2
*
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
* @param downloadOptions cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
return __awaiter(this, void 0, void 0, function* () {
// Override UploadOptions to force the use of Azure
options = Object.assign(Object.assign({}, options), { useAzureSdk: true });
restoreKeys = restoreKeys || [];
const keys = [primaryKey, ...restoreKeys];
core.debug('Resolved Keys:');
core.debug(JSON.stringify(keys));
if (keys.length > 10) {
throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`);
}
for (const key of keys) {
checkKey(key);
}
let archivePath = '';
try {
const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
const compressionMethod = yield utils.getCompressionMethod();
const request = {
key: primaryKey,
restoreKeys,
version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive)
};
const response = yield twirpClient.GetCacheEntryDownloadURL(request);
if (!response.ok) {
core.debug(`Cache not found for keys: ${keys.join(', ')}`);
return undefined;
}
core.info(`Cache hit for: ${request.key}`);
if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
core.info('Lookup only - skipping download');
return response.matchedKey;
}
archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
core.debug(`Archive path: ${archivePath}`);
core.debug(`Starting download of archive to: ${archivePath}`);
yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options);
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
if (core.isDebug()) {
yield (0, tar_1.listTar)(archivePath, compressionMethod);
}
yield (0, tar_1.extractTar)(archivePath, compressionMethod);
core.info('Cache restored successfully');
return response.matchedKey;
}
catch (error) {
const typedError = error;
if (typedError.name === ValidationError.name) {
throw error;
}
else {
// Supress all non-validation cache related errors because caching should be optional
core.warning(`Failed to restore: ${error.message}`);
}
}
finally {
try {
if (archivePath) {
yield utils.unlinkFile(archivePath);
}
}
catch (error) {
core.debug(`Failed to delete archive: ${error}`);
}
}
return undefined;
});
}
/**
* Saves a list of files with the specified key
*
@@ -162,10 +267,33 @@ exports.restoreCache = restoreCache;
* @returns number returns cacheId if the cache was saved successfully and throws an error if save fails
*/
function saveCache(paths, key, options, enableCrossOsArchive = false) {
var _a, _b, _c, _d, _e;
return __awaiter(this, void 0, void 0, function* () {
const cacheServiceVersion = (0, config_1.getCacheServiceVersion)();
core.debug(`Cache service version: ${cacheServiceVersion}`);
checkPaths(paths);
checkKey(key);
switch (cacheServiceVersion) {
case 'v2':
return yield saveCacheV2(paths, key, options, enableCrossOsArchive);
case 'v1':
default:
return yield saveCacheV1(paths, key, options, enableCrossOsArchive);
}
});
}
exports.saveCache = saveCache;
/**
* Save cache using the legacy Cache Service
*
* @param paths
* @param key
* @param options
* @param enableCrossOsArchive
* @returns
*/
function saveCacheV1(paths, key, options, enableCrossOsArchive = false) {
var _a, _b, _c, _d, _e;
return __awaiter(this, void 0, void 0, function* () {
const compressionMethod = yield utils.getCompressionMethod();
let cacheId = -1;
const cachePaths = yield utils.resolvePaths(paths);
@@ -186,7 +314,7 @@ function saveCache(paths, key, options, enableCrossOsArchive = false) {
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
core.debug(`File Size: ${archiveFileSize}`);
// For GHES, this check will take place in ReserveCache API with enterprise file size limit
if (archiveFileSize > fileSizeLimit && !utils.isGhes()) {
if (archiveFileSize > fileSizeLimit && !(0, config_1.isGhes)()) {
throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
}
core.debug('Reserving Cache');
@@ -205,7 +333,103 @@ function saveCache(paths, key, options, enableCrossOsArchive = false) {
throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`);
}
core.debug(`Saving Cache (ID: ${cacheId})`);
yield cacheHttpClient.saveCache(cacheId, archivePath, options);
yield cacheHttpClient.saveCache(cacheId, archivePath, '', options);
}
catch (error) {
const typedError = error;
if (typedError.name === ValidationError.name) {
throw error;
}
else if (typedError.name === ReserveCacheError.name) {
core.info(`Failed to save: ${typedError.message}`);
}
else {
core.warning(`Failed to save: ${typedError.message}`);
}
}
finally {
// Try to delete the archive to save space
try {
yield utils.unlinkFile(archivePath);
}
catch (error) {
core.debug(`Failed to delete archive: ${error}`);
}
}
return cacheId;
});
}
/**
* Save cache using Cache Service v2
*
* @param paths a list of file paths to restore from the cache
* @param key an explicit key for restoring the cache
* @param options cache upload options
* @param enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform
* @returns
*/
function saveCacheV2(paths, key, options, enableCrossOsArchive = false) {
return __awaiter(this, void 0, void 0, function* () {
// Override UploadOptions to force the use of Azure
// ...options goes first because we want to override the default values
// set in UploadOptions with these specific figures
options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true });
const compressionMethod = yield utils.getCompressionMethod();
const twirpClient = cacheTwirpClient.internalCacheTwirpClient();
let cacheId = -1;
const cachePaths = yield utils.resolvePaths(paths);
core.debug('Cache Paths:');
core.debug(`${JSON.stringify(cachePaths)}`);
if (cachePaths.length === 0) {
throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);
}
const archiveFolder = yield utils.createTempDirectory();
const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod));
core.debug(`Archive Path: ${archivePath}`);
try {
yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
if (core.isDebug()) {
yield (0, tar_1.listTar)(archivePath, compressionMethod);
}
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
core.debug(`File Size: ${archiveFileSize}`);
// For GHES, this check will take place in ReserveCache API with enterprise file size limit
if (archiveFileSize > constants_1.CacheFileSizeLimit && !(0, config_1.isGhes)()) {
throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`);
}
// Set the archive size in the options, will be used to display the upload progress
options.archiveSizeBytes = archiveFileSize;
core.debug('Reserving Cache');
const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive);
const request = {
key,
version
};
let signedUploadUrl;
try {
const response = yield twirpClient.CreateCacheEntry(request);
if (!response.ok) {
throw new Error('Response was not ok');
}
signedUploadUrl = response.signedUploadUrl;
}
catch (error) {
core.debug(`Failed to reserve cache: ${error}`);
throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`);
}
core.debug(`Attempting to upload cache located at: ${archivePath}`);
yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options);
const finalizeRequest = {
key,
version,
sizeBytes: `${archiveFileSize}`
};
const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest);
core.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`);
if (!finalizeResponse.ok) {
throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`);
}
cacheId = parseInt(finalizeResponse.entryId);
}
catch (error) {
const typedError = error;
@@ -231,5 +455,4 @@ function saveCache(paths, key, options, enableCrossOsArchive = false) {
return cacheId;
});
}
exports.saveCache = saveCache;
//# sourceMappingURL=cache.js.map
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,158 @@
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import type { JsonValue } from "@protobuf-ts/runtime";
import type { JsonReadOptions } from "@protobuf-ts/runtime";
import type { JsonWriteOptions } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
*
* @generated from protobuf message google.protobuf.Timestamp
*/
export interface Timestamp {
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*
* @generated from protobuf field: int64 seconds = 1;
*/
seconds: string;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*
* @generated from protobuf field: int32 nanos = 2;
*/
nanos: number;
}
declare class Timestamp$Type extends MessageType<Timestamp> {
constructor();
/**
* Creates a new `Timestamp` for the current time.
*/
now(): Timestamp;
/**
* Converts a `Timestamp` to a JavaScript Date.
*/
toDate(message: Timestamp): Date;
/**
* Converts a JavaScript Date to a `Timestamp`.
*/
fromDate(date: Date): Timestamp;
/**
* In JSON format, the `Timestamp` type is encoded as a string
* in the RFC 3339 format.
*/
internalJsonWrite(message: Timestamp, options: JsonWriteOptions): JsonValue;
/**
* In JSON format, the `Timestamp` type is encoded as a string
* in the RFC 3339 format.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: Timestamp): Timestamp;
create(value?: PartialMessage<Timestamp>): Timestamp;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Timestamp): Timestamp;
internalBinaryWrite(message: Timestamp, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.Timestamp
*/
export declare const Timestamp: Timestamp$Type;
export {};
+136
View File
@@ -0,0 +1,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const runtime_6 = require("@protobuf-ts/runtime");
const runtime_7 = require("@protobuf-ts/runtime");
// @generated message type with reflection information, may provide speed optimized methods
class Timestamp$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.Timestamp", [
{ no: 1, name: "seconds", kind: "scalar", T: 3 /*ScalarType.INT64*/ },
{ no: 2, name: "nanos", kind: "scalar", T: 5 /*ScalarType.INT32*/ }
]);
}
/**
* Creates a new `Timestamp` for the current time.
*/
now() {
const msg = this.create();
const ms = Date.now();
msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString();
msg.nanos = (ms % 1000) * 1000000;
return msg;
}
/**
* Converts a `Timestamp` to a JavaScript Date.
*/
toDate(message) {
return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1000 + Math.ceil(message.nanos / 1000000));
}
/**
* Converts a JavaScript Date to a `Timestamp`.
*/
fromDate(date) {
const msg = this.create();
const ms = date.getTime();
msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString();
msg.nanos = (ms % 1000) * 1000000;
return msg;
}
/**
* In JSON format, the `Timestamp` type is encoded as a string
* in the RFC 3339 format.
*/
internalJsonWrite(message, options) {
let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1000;
if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z"))
throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");
if (message.nanos < 0)
throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");
let z = "Z";
if (message.nanos > 0) {
let nanosStr = (message.nanos + 1000000000).toString().substring(1);
if (nanosStr.substring(3) === "000000")
z = "." + nanosStr.substring(0, 3) + "Z";
else if (nanosStr.substring(6) === "000")
z = "." + nanosStr.substring(0, 6) + "Z";
else
z = "." + nanosStr + "Z";
}
return new Date(ms).toISOString().replace(".000Z", z);
}
/**
* In JSON format, the `Timestamp` type is encoded as a string
* in the RFC 3339 format.
*/
internalJsonRead(json, options, target) {
if (typeof json !== "string")
throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json) + ".");
let matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
if (!matches)
throw new Error("Unable to parse Timestamp from JSON. Invalid format.");
let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
if (Number.isNaN(ms))
throw new Error("Unable to parse Timestamp from JSON. Invalid value.");
if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z"))
throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");
if (!target)
target = this.create();
target.seconds = runtime_6.PbLong.from(ms / 1000).toString();
target.nanos = 0;
if (matches[7])
target.nanos = (parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1000000000);
return target;
}
create(value) {
const message = { seconds: "0", nanos: 0 };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* int64 seconds */ 1:
message.seconds = reader.int64().toString();
break;
case /* int32 nanos */ 2:
message.nanos = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* int64 seconds = 1; */
if (message.seconds !== "0")
writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds);
/* int32 nanos = 2; */
if (message.nanos !== 0)
writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.Timestamp
*/
exports.Timestamp = new Timestamp$Type();
//# sourceMappingURL=timestamp.js.map
File diff suppressed because one or more lines are too long
+307
View File
@@ -0,0 +1,307 @@
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import type { JsonValue } from "@protobuf-ts/runtime";
import type { JsonReadOptions } from "@protobuf-ts/runtime";
import type { JsonWriteOptions } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* @generated from protobuf message google.protobuf.DoubleValue
*/
export interface DoubleValue {
/**
* The double value.
*
* @generated from protobuf field: double value = 1;
*/
value: number;
}
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* @generated from protobuf message google.protobuf.FloatValue
*/
export interface FloatValue {
/**
* The float value.
*
* @generated from protobuf field: float value = 1;
*/
value: number;
}
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* @generated from protobuf message google.protobuf.Int64Value
*/
export interface Int64Value {
/**
* The int64 value.
*
* @generated from protobuf field: int64 value = 1;
*/
value: string;
}
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* @generated from protobuf message google.protobuf.UInt64Value
*/
export interface UInt64Value {
/**
* The uint64 value.
*
* @generated from protobuf field: uint64 value = 1;
*/
value: string;
}
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* @generated from protobuf message google.protobuf.Int32Value
*/
export interface Int32Value {
/**
* The int32 value.
*
* @generated from protobuf field: int32 value = 1;
*/
value: number;
}
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* @generated from protobuf message google.protobuf.UInt32Value
*/
export interface UInt32Value {
/**
* The uint32 value.
*
* @generated from protobuf field: uint32 value = 1;
*/
value: number;
}
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* @generated from protobuf message google.protobuf.BoolValue
*/
export interface BoolValue {
/**
* The bool value.
*
* @generated from protobuf field: bool value = 1;
*/
value: boolean;
}
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* @generated from protobuf message google.protobuf.StringValue
*/
export interface StringValue {
/**
* The string value.
*
* @generated from protobuf field: string value = 1;
*/
value: string;
}
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* @generated from protobuf message google.protobuf.BytesValue
*/
export interface BytesValue {
/**
* The bytes value.
*
* @generated from protobuf field: bytes value = 1;
*/
value: Uint8Array;
}
declare class DoubleValue$Type extends MessageType<DoubleValue> {
constructor();
/**
* Encode `DoubleValue` to JSON number.
*/
internalJsonWrite(message: DoubleValue, options: JsonWriteOptions): JsonValue;
/**
* Decode `DoubleValue` from JSON number.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: DoubleValue): DoubleValue;
create(value?: PartialMessage<DoubleValue>): DoubleValue;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DoubleValue): DoubleValue;
internalBinaryWrite(message: DoubleValue, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.DoubleValue
*/
export declare const DoubleValue: DoubleValue$Type;
declare class FloatValue$Type extends MessageType<FloatValue> {
constructor();
/**
* Encode `FloatValue` to JSON number.
*/
internalJsonWrite(message: FloatValue, options: JsonWriteOptions): JsonValue;
/**
* Decode `FloatValue` from JSON number.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: FloatValue): FloatValue;
create(value?: PartialMessage<FloatValue>): FloatValue;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FloatValue): FloatValue;
internalBinaryWrite(message: FloatValue, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.FloatValue
*/
export declare const FloatValue: FloatValue$Type;
declare class Int64Value$Type extends MessageType<Int64Value> {
constructor();
/**
* Encode `Int64Value` to JSON string.
*/
internalJsonWrite(message: Int64Value, options: JsonWriteOptions): JsonValue;
/**
* Decode `Int64Value` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: Int64Value): Int64Value;
create(value?: PartialMessage<Int64Value>): Int64Value;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Int64Value): Int64Value;
internalBinaryWrite(message: Int64Value, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.Int64Value
*/
export declare const Int64Value: Int64Value$Type;
declare class UInt64Value$Type extends MessageType<UInt64Value> {
constructor();
/**
* Encode `UInt64Value` to JSON string.
*/
internalJsonWrite(message: UInt64Value, options: JsonWriteOptions): JsonValue;
/**
* Decode `UInt64Value` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: UInt64Value): UInt64Value;
create(value?: PartialMessage<UInt64Value>): UInt64Value;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UInt64Value): UInt64Value;
internalBinaryWrite(message: UInt64Value, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.UInt64Value
*/
export declare const UInt64Value: UInt64Value$Type;
declare class Int32Value$Type extends MessageType<Int32Value> {
constructor();
/**
* Encode `Int32Value` to JSON string.
*/
internalJsonWrite(message: Int32Value, options: JsonWriteOptions): JsonValue;
/**
* Decode `Int32Value` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: Int32Value): Int32Value;
create(value?: PartialMessage<Int32Value>): Int32Value;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Int32Value): Int32Value;
internalBinaryWrite(message: Int32Value, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.Int32Value
*/
export declare const Int32Value: Int32Value$Type;
declare class UInt32Value$Type extends MessageType<UInt32Value> {
constructor();
/**
* Encode `UInt32Value` to JSON string.
*/
internalJsonWrite(message: UInt32Value, options: JsonWriteOptions): JsonValue;
/**
* Decode `UInt32Value` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: UInt32Value): UInt32Value;
create(value?: PartialMessage<UInt32Value>): UInt32Value;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UInt32Value): UInt32Value;
internalBinaryWrite(message: UInt32Value, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.UInt32Value
*/
export declare const UInt32Value: UInt32Value$Type;
declare class BoolValue$Type extends MessageType<BoolValue> {
constructor();
/**
* Encode `BoolValue` to JSON bool.
*/
internalJsonWrite(message: BoolValue, options: JsonWriteOptions): JsonValue;
/**
* Decode `BoolValue` from JSON bool.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: BoolValue): BoolValue;
create(value?: PartialMessage<BoolValue>): BoolValue;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: BoolValue): BoolValue;
internalBinaryWrite(message: BoolValue, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.BoolValue
*/
export declare const BoolValue: BoolValue$Type;
declare class StringValue$Type extends MessageType<StringValue> {
constructor();
/**
* Encode `StringValue` to JSON string.
*/
internalJsonWrite(message: StringValue, options: JsonWriteOptions): JsonValue;
/**
* Decode `StringValue` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: StringValue): StringValue;
create(value?: PartialMessage<StringValue>): StringValue;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: StringValue): StringValue;
internalBinaryWrite(message: StringValue, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.StringValue
*/
export declare const StringValue: StringValue$Type;
declare class BytesValue$Type extends MessageType<BytesValue> {
constructor();
/**
* Encode `BytesValue` to JSON string.
*/
internalJsonWrite(message: BytesValue, options: JsonWriteOptions): JsonValue;
/**
* Decode `BytesValue` from JSON string.
*/
internalJsonRead(json: JsonValue, options: JsonReadOptions, target?: BytesValue): BytesValue;
create(value?: PartialMessage<BytesValue>): BytesValue;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: BytesValue): BytesValue;
internalBinaryWrite(message: BytesValue, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message google.protobuf.BytesValue
*/
export declare const BytesValue: BytesValue$Type;
export {};
+614
View File
@@ -0,0 +1,614 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesValue = exports.StringValue = exports.BoolValue = exports.UInt32Value = exports.Int32Value = exports.UInt64Value = exports.Int64Value = exports.FloatValue = exports.DoubleValue = void 0;
// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies
// @generated from protobuf file "google/protobuf/wrappers.proto" (package "google.protobuf", syntax proto3)
// tslint:disable
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Wrappers for primitive (non-message) types. These types are useful
// for embedding primitives in the `google.protobuf.Any` type and for places
// where we need to distinguish between the absence of a primitive
// typed field and its default value.
//
// These wrappers have no meaningful use within repeated fields as they lack
// the ability to detect presence on individual elements.
// These wrappers have no meaningful use within a map or a oneof since
// individual entries of a map or fields of a oneof can already detect presence.
//
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const runtime_6 = require("@protobuf-ts/runtime");
const runtime_7 = require("@protobuf-ts/runtime");
// @generated message type with reflection information, may provide speed optimized methods
class DoubleValue$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.DoubleValue", [
{ no: 1, name: "value", kind: "scalar", T: 1 /*ScalarType.DOUBLE*/ }
]);
}
/**
* Encode `DoubleValue` to JSON number.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(2, message.value, "value", false, true);
}
/**
* Decode `DoubleValue` from JSON number.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 1, undefined, "value");
return target;
}
create(value) {
const message = { value: 0 };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* double value */ 1:
message.value = reader.double();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* double value = 1; */
if (message.value !== 0)
writer.tag(1, runtime_3.WireType.Bit64).double(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.DoubleValue
*/
exports.DoubleValue = new DoubleValue$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FloatValue$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.FloatValue", [
{ no: 1, name: "value", kind: "scalar", T: 2 /*ScalarType.FLOAT*/ }
]);
}
/**
* Encode `FloatValue` to JSON number.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(1, message.value, "value", false, true);
}
/**
* Decode `FloatValue` from JSON number.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 1, undefined, "value");
return target;
}
create(value) {
const message = { value: 0 };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* float value */ 1:
message.value = reader.float();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* float value = 1; */
if (message.value !== 0)
writer.tag(1, runtime_3.WireType.Bit32).float(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FloatValue
*/
exports.FloatValue = new FloatValue$Type();
// @generated message type with reflection information, may provide speed optimized methods
class Int64Value$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.Int64Value", [
{ no: 1, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/ }
]);
}
/**
* Encode `Int64Value` to JSON string.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true);
}
/**
* Decode `Int64Value` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value");
return target;
}
create(value) {
const message = { value: "0" };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* int64 value */ 1:
message.value = reader.int64().toString();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* int64 value = 1; */
if (message.value !== "0")
writer.tag(1, runtime_3.WireType.Varint).int64(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.Int64Value
*/
exports.Int64Value = new Int64Value$Type();
// @generated message type with reflection information, may provide speed optimized methods
class UInt64Value$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.UInt64Value", [
{ no: 1, name: "value", kind: "scalar", T: 4 /*ScalarType.UINT64*/ }
]);
}
/**
* Encode `UInt64Value` to JSON string.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true);
}
/**
* Decode `UInt64Value` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value");
return target;
}
create(value) {
const message = { value: "0" };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* uint64 value */ 1:
message.value = reader.uint64().toString();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* uint64 value = 1; */
if (message.value !== "0")
writer.tag(1, runtime_3.WireType.Varint).uint64(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.UInt64Value
*/
exports.UInt64Value = new UInt64Value$Type();
// @generated message type with reflection information, may provide speed optimized methods
class Int32Value$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.Int32Value", [
{ no: 1, name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ }
]);
}
/**
* Encode `Int32Value` to JSON string.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(5, message.value, "value", false, true);
}
/**
* Decode `Int32Value` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 5, undefined, "value");
return target;
}
create(value) {
const message = { value: 0 };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* int32 value */ 1:
message.value = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* int32 value = 1; */
if (message.value !== 0)
writer.tag(1, runtime_3.WireType.Varint).int32(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.Int32Value
*/
exports.Int32Value = new Int32Value$Type();
// @generated message type with reflection information, may provide speed optimized methods
class UInt32Value$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.UInt32Value", [
{ no: 1, name: "value", kind: "scalar", T: 13 /*ScalarType.UINT32*/ }
]);
}
/**
* Encode `UInt32Value` to JSON string.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(13, message.value, "value", false, true);
}
/**
* Decode `UInt32Value` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 13, undefined, "value");
return target;
}
create(value) {
const message = { value: 0 };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* uint32 value */ 1:
message.value = reader.uint32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* uint32 value = 1; */
if (message.value !== 0)
writer.tag(1, runtime_3.WireType.Varint).uint32(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.UInt32Value
*/
exports.UInt32Value = new UInt32Value$Type();
// @generated message type with reflection information, may provide speed optimized methods
class BoolValue$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.BoolValue", [
{ no: 1, name: "value", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }
]);
}
/**
* Encode `BoolValue` to JSON bool.
*/
internalJsonWrite(message, options) {
return message.value;
}
/**
* Decode `BoolValue` from JSON bool.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 8, undefined, "value");
return target;
}
create(value) {
const message = { value: false };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool value */ 1:
message.value = reader.bool();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool value = 1; */
if (message.value !== false)
writer.tag(1, runtime_3.WireType.Varint).bool(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.BoolValue
*/
exports.BoolValue = new BoolValue$Type();
// @generated message type with reflection information, may provide speed optimized methods
class StringValue$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.StringValue", [
{ no: 1, name: "value", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
/**
* Encode `StringValue` to JSON string.
*/
internalJsonWrite(message, options) {
return message.value;
}
/**
* Decode `StringValue` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 9, undefined, "value");
return target;
}
create(value) {
const message = { value: "" };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* string value */ 1:
message.value = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* string value = 1; */
if (message.value !== "")
writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.StringValue
*/
exports.StringValue = new StringValue$Type();
// @generated message type with reflection information, may provide speed optimized methods
class BytesValue$Type extends runtime_7.MessageType {
constructor() {
super("google.protobuf.BytesValue", [
{ no: 1, name: "value", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
]);
}
/**
* Encode `BytesValue` to JSON string.
*/
internalJsonWrite(message, options) {
return this.refJsonWriter.scalar(12, message.value, "value", false, true);
}
/**
* Decode `BytesValue` from JSON string.
*/
internalJsonRead(json, options, target) {
if (!target)
target = this.create();
target.value = this.refJsonReader.scalar(json, 12, undefined, "value");
return target;
}
create(value) {
const message = { value: new Uint8Array(0) };
globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_5.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bytes value */ 1:
message.value = reader.bytes();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bytes value = 1; */
if (message.value.length)
writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.BytesValue
*/
exports.BytesValue = new BytesValue$Type();
//# sourceMappingURL=wrappers.js.map
File diff suppressed because one or more lines are too long
+205
View File
@@ -0,0 +1,205 @@
import { ServiceType } from "@protobuf-ts/runtime-rpc";
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { CacheMetadata } from "../../entities/v1/cachemetadata";
/**
* @generated from protobuf message github.actions.results.api.v1.CreateCacheEntryRequest
*/
export interface CreateCacheEntryRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
/**
* Hash of the compression tool, runner OS and paths cached
*
* @generated from protobuf field: string version = 3;
*/
version: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.CreateCacheEntryResponse
*/
export interface CreateCacheEntryResponse {
/**
* @generated from protobuf field: bool ok = 1;
*/
ok: boolean;
/**
* SAS URL to upload the cache archive
*
* @generated from protobuf field: string signed_upload_url = 2;
*/
signedUploadUrl: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadRequest
*/
export interface FinalizeCacheEntryUploadRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
/**
* Size of the cache archive in Bytes
*
* @generated from protobuf field: int64 size_bytes = 3;
*/
sizeBytes: string;
/**
* Hash of the compression tool, runner OS and paths cached
*
* @generated from protobuf field: string version = 4;
*/
version: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadResponse
*/
export interface FinalizeCacheEntryUploadResponse {
/**
* @generated from protobuf field: bool ok = 1;
*/
ok: boolean;
/**
* Cache entry database ID
*
* @generated from protobuf field: int64 entry_id = 2;
*/
entryId: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLRequest
*/
export interface GetCacheEntryDownloadURLRequest {
/**
* Scope and other metadata for the cache entry
*
* @generated from protobuf field: github.actions.results.entities.v1.CacheMetadata metadata = 1;
*/
metadata?: CacheMetadata;
/**
* An explicit key for a cache entry
*
* @generated from protobuf field: string key = 2;
*/
key: string;
/**
* Restore keys used for prefix searching
*
* @generated from protobuf field: repeated string restore_keys = 3;
*/
restoreKeys: string[];
/**
* Hash of the compression tool, runner OS and paths cached
*
* @generated from protobuf field: string version = 4;
*/
version: string;
}
/**
* @generated from protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse
*/
export interface GetCacheEntryDownloadURLResponse {
/**
* @generated from protobuf field: bool ok = 1;
*/
ok: boolean;
/**
* SAS URL to download the cache archive
*
* @generated from protobuf field: string signed_download_url = 2;
*/
signedDownloadUrl: string;
/**
* Key or restore key that matches the lookup
*
* @generated from protobuf field: string matched_key = 3;
*/
matchedKey: string;
}
declare class CreateCacheEntryRequest$Type extends MessageType<CreateCacheEntryRequest> {
constructor();
create(value?: PartialMessage<CreateCacheEntryRequest>): CreateCacheEntryRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CreateCacheEntryRequest): CreateCacheEntryRequest;
internalBinaryWrite(message: CreateCacheEntryRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryRequest
*/
export declare const CreateCacheEntryRequest: CreateCacheEntryRequest$Type;
declare class CreateCacheEntryResponse$Type extends MessageType<CreateCacheEntryResponse> {
constructor();
create(value?: PartialMessage<CreateCacheEntryResponse>): CreateCacheEntryResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CreateCacheEntryResponse): CreateCacheEntryResponse;
internalBinaryWrite(message: CreateCacheEntryResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryResponse
*/
export declare const CreateCacheEntryResponse: CreateCacheEntryResponse$Type;
declare class FinalizeCacheEntryUploadRequest$Type extends MessageType<FinalizeCacheEntryUploadRequest> {
constructor();
create(value?: PartialMessage<FinalizeCacheEntryUploadRequest>): FinalizeCacheEntryUploadRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FinalizeCacheEntryUploadRequest): FinalizeCacheEntryUploadRequest;
internalBinaryWrite(message: FinalizeCacheEntryUploadRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadRequest
*/
export declare const FinalizeCacheEntryUploadRequest: FinalizeCacheEntryUploadRequest$Type;
declare class FinalizeCacheEntryUploadResponse$Type extends MessageType<FinalizeCacheEntryUploadResponse> {
constructor();
create(value?: PartialMessage<FinalizeCacheEntryUploadResponse>): FinalizeCacheEntryUploadResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FinalizeCacheEntryUploadResponse): FinalizeCacheEntryUploadResponse;
internalBinaryWrite(message: FinalizeCacheEntryUploadResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadResponse
*/
export declare const FinalizeCacheEntryUploadResponse: FinalizeCacheEntryUploadResponse$Type;
declare class GetCacheEntryDownloadURLRequest$Type extends MessageType<GetCacheEntryDownloadURLRequest> {
constructor();
create(value?: PartialMessage<GetCacheEntryDownloadURLRequest>): GetCacheEntryDownloadURLRequest;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: GetCacheEntryDownloadURLRequest): GetCacheEntryDownloadURLRequest;
internalBinaryWrite(message: GetCacheEntryDownloadURLRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLRequest
*/
export declare const GetCacheEntryDownloadURLRequest: GetCacheEntryDownloadURLRequest$Type;
declare class GetCacheEntryDownloadURLResponse$Type extends MessageType<GetCacheEntryDownloadURLResponse> {
constructor();
create(value?: PartialMessage<GetCacheEntryDownloadURLResponse>): GetCacheEntryDownloadURLResponse;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: GetCacheEntryDownloadURLResponse): GetCacheEntryDownloadURLResponse;
internalBinaryWrite(message: GetCacheEntryDownloadURLResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse
*/
export declare const GetCacheEntryDownloadURLResponse: GetCacheEntryDownloadURLResponse$Type;
/**
* @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService
*/
export declare const CacheService: ServiceType;
export {};
+388
View File
@@ -0,0 +1,388 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheService = exports.GetCacheEntryDownloadURLResponse = exports.GetCacheEntryDownloadURLRequest = exports.FinalizeCacheEntryUploadResponse = exports.FinalizeCacheEntryUploadRequest = exports.CreateCacheEntryResponse = exports.CreateCacheEntryRequest = void 0;
// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies
// @generated from protobuf file "results/api/v1/cache.proto" (package "github.actions.results.api.v1", syntax proto3)
// tslint:disable
const runtime_rpc_1 = require("@protobuf-ts/runtime-rpc");
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const cachemetadata_1 = require("../../entities/v1/cachemetadata");
// @generated message type with reflection information, may provide speed optimized methods
class CreateCacheEntryRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.CreateCacheEntryRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "", version: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
case /* string version */ 3:
message.version = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
/* string version = 3; */
if (message.version !== "")
writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryRequest
*/
exports.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class CreateCacheEntryResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.CreateCacheEntryResponse", [
{ no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "signed_upload_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { ok: false, signedUploadUrl: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool ok */ 1:
message.ok = reader.bool();
break;
case /* string signed_upload_url */ 2:
message.signedUploadUrl = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool ok = 1; */
if (message.ok !== false)
writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
/* string signed_upload_url = 2; */
if (message.signedUploadUrl !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryResponse
*/
exports.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FinalizeCacheEntryUploadRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "size_bytes", kind: "scalar", T: 3 /*ScalarType.INT64*/ },
{ no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "", sizeBytes: "0", version: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
case /* int64 size_bytes */ 3:
message.sizeBytes = reader.int64().toString();
break;
case /* string version */ 4:
message.version = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
/* int64 size_bytes = 3; */
if (message.sizeBytes !== "0")
writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes);
/* string version = 4; */
if (message.version !== "")
writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadRequest
*/
exports.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FinalizeCacheEntryUploadResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [
{ no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "entry_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }
]);
}
create(value) {
const message = { ok: false, entryId: "0" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool ok */ 1:
message.ok = reader.bool();
break;
case /* int64 entry_id */ 2:
message.entryId = reader.int64().toString();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool ok = 1; */
if (message.ok !== false)
writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
/* int64 entry_id = 2; */
if (message.entryId !== "0")
writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeCacheEntryUploadResponse
*/
exports.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class GetCacheEntryDownloadURLRequest$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [
{ no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata },
{ no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "restore_keys", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { key: "", restoreKeys: [], version: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* github.actions.results.entities.v1.CacheMetadata metadata */ 1:
message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata);
break;
case /* string key */ 2:
message.key = reader.string();
break;
case /* repeated string restore_keys */ 3:
message.restoreKeys.push(reader.string());
break;
case /* string version */ 4:
message.version = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* github.actions.results.entities.v1.CacheMetadata metadata = 1; */
if (message.metadata)
cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join();
/* string key = 2; */
if (message.key !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key);
/* repeated string restore_keys = 3; */
for (let i = 0; i < message.restoreKeys.length; i++)
writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]);
/* string version = 4; */
if (message.version !== "")
writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLRequest
*/
exports.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class GetCacheEntryDownloadURLResponse$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [
{ no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "signed_download_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "matched_key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
]);
}
create(value) {
const message = { ok: false, signedDownloadUrl: "", matchedKey: "" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* bool ok */ 1:
message.ok = reader.bool();
break;
case /* string signed_download_url */ 2:
message.signedDownloadUrl = reader.string();
break;
case /* string matched_key */ 3:
message.matchedKey = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* bool ok = 1; */
if (message.ok !== false)
writer.tag(1, runtime_1.WireType.Varint).bool(message.ok);
/* string signed_download_url = 2; */
if (message.signedDownloadUrl !== "")
writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl);
/* string matched_key = 3; */
if (message.matchedKey !== "")
writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.api.v1.GetCacheEntryDownloadURLResponse
*/
exports.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type();
/**
* @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService
*/
exports.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [
{ name: "CreateCacheEntry", options: {}, I: exports.CreateCacheEntryRequest, O: exports.CreateCacheEntryResponse },
{ name: "FinalizeCacheEntryUpload", options: {}, I: exports.FinalizeCacheEntryUploadRequest, O: exports.FinalizeCacheEntryUploadResponse },
{ name: "GetCacheEntryDownloadURL", options: {}, I: exports.GetCacheEntryDownloadURLRequest, O: exports.GetCacheEntryDownloadURLResponse }
]);
//# sourceMappingURL=cache.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,24 @@
import { CreateCacheEntryRequest, CreateCacheEntryResponse, FinalizeCacheEntryUploadRequest, FinalizeCacheEntryUploadResponse, GetCacheEntryDownloadURLRequest, GetCacheEntryDownloadURLResponse } from "./cache";
interface Rpc {
request(service: string, method: string, contentType: "application/json" | "application/protobuf", data: object | Uint8Array): Promise<object | Uint8Array>;
}
export interface CacheServiceClient {
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export declare class CacheServiceClientJSON implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export declare class CacheServiceClientProtobuf implements CacheServiceClient {
private readonly rpc;
constructor(rpc: Rpc);
CreateCacheEntry(request: CreateCacheEntryRequest): Promise<CreateCacheEntryResponse>;
FinalizeCacheEntryUpload(request: FinalizeCacheEntryUploadRequest): Promise<FinalizeCacheEntryUploadResponse>;
GetCacheEntryDownloadURL(request: GetCacheEntryDownloadURLRequest): Promise<GetCacheEntryDownloadURLResponse>;
}
export {};
@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheServiceClientProtobuf = exports.CacheServiceClientJSON = void 0;
const cache_1 = require("./cache");
class CacheServiceClientJSON {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, {
useProtoFieldName: true,
emitDefaultValues: false,
});
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data, {
ignoreUnknownFields: true,
}));
}
}
exports.CacheServiceClientJSON = CacheServiceClientJSON;
class CacheServiceClientProtobuf {
constructor(rpc) {
this.rpc = rpc;
this.CreateCacheEntry.bind(this);
this.FinalizeCacheEntryUpload.bind(this);
this.GetCacheEntryDownloadURL.bind(this);
}
CreateCacheEntry(request) {
const data = cache_1.CreateCacheEntryRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data);
return promise.then((data) => cache_1.CreateCacheEntryResponse.fromBinary(data));
}
FinalizeCacheEntryUpload(request) {
const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data);
return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data));
}
GetCacheEntryDownloadURL(request) {
const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request);
const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data);
return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data));
}
}
exports.CacheServiceClientProtobuf = CacheServiceClientProtobuf;
//# sourceMappingURL=cache.twirp-client.js.map
@@ -0,0 +1 @@
{"version":3,"file":"cache.twirp-client.js","sourceRoot":"","sources":["../../../../../src/generated/results/api/v1/cache.twirp-client.ts"],"names":[],"mappings":";;;AAAA,mCAOmB;AA2BjB,MAAa,sBAAsB;IAEjC,YAAY,GAAQ;QAClB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC;IACD,gBAAgB,CACd,OAAgC;QAEhC,MAAM,IAAI,GAAG,+BAAuB,CAAC,MAAM,CAAC,OAAO,EAAE;YACnD,iBAAiB,EAAE,IAAI;YACvB,iBAAiB,EAAE,KAAK;SACzB,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,4CAA4C,EAC5C,kBAAkB,EAClB,kBAAkB,EAClB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
@@ -0,0 +1,35 @@
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { CacheScope } from "./cachescope";
/**
* @generated from protobuf message github.actions.results.entities.v1.CacheMetadata
*/
export interface CacheMetadata {
/**
* Backend repository id
*
* @generated from protobuf field: int64 repository_id = 1;
*/
repositoryId: string;
/**
* Scopes for the cache entry
*
* @generated from protobuf field: repeated github.actions.results.entities.v1.CacheScope scope = 2;
*/
scope: CacheScope[];
}
declare class CacheMetadata$Type extends MessageType<CacheMetadata> {
constructor();
create(value?: PartialMessage<CacheMetadata>): CacheMetadata;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CacheMetadata): CacheMetadata;
internalBinaryWrite(message: CacheMetadata, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheMetadata
*/
export declare const CacheMetadata: CacheMetadata$Type;
export {};
@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheMetadata = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
const cachescope_1 = require("./cachescope");
// @generated message type with reflection information, may provide speed optimized methods
class CacheMetadata$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.entities.v1.CacheMetadata", [
{ no: 1, name: "repository_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ },
{ no: 2, name: "scope", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => cachescope_1.CacheScope }
]);
}
create(value) {
const message = { repositoryId: "0", scope: [] };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* int64 repository_id */ 1:
message.repositoryId = reader.int64().toString();
break;
case /* repeated github.actions.results.entities.v1.CacheScope scope */ 2:
message.scope.push(cachescope_1.CacheScope.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* int64 repository_id = 1; */
if (message.repositoryId !== "0")
writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId);
/* repeated github.actions.results.entities.v1.CacheScope scope = 2; */
for (let i = 0; i < message.scope.length; i++)
cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, runtime_1.WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheMetadata
*/
exports.CacheMetadata = new CacheMetadata$Type();
//# sourceMappingURL=cachemetadata.js.map
@@ -0,0 +1 @@
{"version":3,"file":"cachemetadata.js","sourceRoot":"","sources":["../../../../../src/generated/results/entities/v1/cachemetadata.ts"],"names":[],"mappings":";;;AAKA,kDAAgD;AAGhD,kDAA2D;AAE3D,kDAA8D;AAC9D,kDAAoD;AACpD,kDAAmD;AACnD,6CAA0C;AAkB1C,2FAA2F;AAC3F,MAAM,kBAAmB,SAAQ,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AC,CAAC,IAAI,EAAE,CAAC;QACrH,IAAI,CAAC,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACnC,IAAI,CAAC,KAAK,KAAK;YACX,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,6BAAmB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAClF,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AACD;;GAEG;AACU,QAAA,aAAa,GAAG,IAAI,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,34 @@
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
/**
* @generated from protobuf message github.actions.results.entities.v1.CacheScope
*/
export interface CacheScope {
/**
* Determines the scope of the cache entry
*
* @generated from protobuf field: string scope = 1;
*/
scope: string;
/**
* None: 0 | Read: 1 | Write: 2 | All: (1|2)
*
* @generated from protobuf field: int64 permission = 2;
*/
permission: string;
}
declare class CacheScope$Type extends MessageType<CacheScope> {
constructor();
create(value?: PartialMessage<CacheScope>): CacheScope;
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CacheScope): CacheScope;
internalBinaryWrite(message: CacheScope, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter;
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheScope
*/
export declare const CacheScope: CacheScope$Type;
export {};
@@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheScope = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const runtime_4 = require("@protobuf-ts/runtime");
const runtime_5 = require("@protobuf-ts/runtime");
// @generated message type with reflection information, may provide speed optimized methods
class CacheScope$Type extends runtime_5.MessageType {
constructor() {
super("github.actions.results.entities.v1.CacheScope", [
{ no: 1, name: "scope", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "permission", kind: "scalar", T: 3 /*ScalarType.INT64*/ }
]);
}
create(value) {
const message = { scope: "", permission: "0" };
globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
(0, runtime_3.reflectionMergePartial)(this, message, value);
return message;
}
internalBinaryRead(reader, length, options, target) {
let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* string scope */ 1:
message.scope = reader.string();
break;
case /* int64 permission */ 2:
message.permission = reader.int64().toString();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message, writer, options) {
/* string scope = 1; */
if (message.scope !== "")
writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope);
/* int64 permission = 2; */
if (message.permission !== "0")
writer.tag(2, runtime_1.WireType.Varint).int64(message.permission);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message github.actions.results.entities.v1.CacheScope
*/
exports.CacheScope = new CacheScope$Type();
//# sourceMappingURL=cachescope.js.map
@@ -0,0 +1 @@
{"version":3,"file":"cachescope.js","sourceRoot":"","sources":["../../../../../src/generated/results/entities/v1/cachescope.ts"],"names":[],"mappings":";;;AAKA,kDAAgD;AAGhD,kDAA2D;AAE3D,kDAA8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AAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAClF,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AACD;;GAEG;AACU,QAAA,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC"}
+1 -3
View File
@@ -1,8 +1,6 @@
import { CompressionMethod } from './constants';
import { ArtifactCacheEntry, InternalCacheOptions, ReserveCacheResponse, ITypedResponseWithError } from './contracts';
import { DownloadOptions, UploadOptions } from '../options';
export declare function getCacheVersion(paths: string[], compressionMethod?: CompressionMethod, enableCrossOsArchive?: boolean): string;
export declare function getCacheEntry(keys: string[], paths: string[], options?: InternalCacheOptions): Promise<ArtifactCacheEntry | null>;
export declare function downloadCache(archiveLocation: string, archivePath: string, options?: DownloadOptions): Promise<void>;
export declare function reserveCache(key: string, paths: string[], options?: InternalCacheOptions): Promise<ITypedResponseWithError<ReserveCacheResponse>>;
export declare function saveCache(cacheId: number, archivePath: string, options?: UploadOptions): Promise<void>;
export declare function saveCache(cacheId: number, archivePath: string, signedUploadURL?: string, options?: UploadOptions): Promise<void>;
+30 -36
View File
@@ -32,20 +32,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = exports.getCacheVersion = void 0;
exports.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = void 0;
const core = __importStar(require("@actions/core"));
const http_client_1 = require("@actions/http-client");
const auth_1 = require("@actions/http-client/lib/auth");
const crypto = __importStar(require("crypto"));
const fs = __importStar(require("fs"));
const url_1 = require("url");
const utils = __importStar(require("./cacheUtils"));
const uploadUtils_1 = require("./uploadUtils");
const downloadUtils_1 = require("./downloadUtils");
const options_1 = require("../options");
const requestUtils_1 = require("./requestUtils");
const versionSalt = '1.0';
const config_1 = require("./config");
const user_agent_1 = require("./shared/user-agent");
function getCacheApiUrl(resource) {
const baseUrl = process.env['ACTIONS_CACHE_URL'] || '';
const baseUrl = (0, config_1.getCacheServiceURL)();
if (!baseUrl) {
throw new Error('Cache Service Url not found, unable to restore cache.');
}
@@ -67,29 +68,12 @@ function getRequestOptions() {
function createHttpClient() {
const token = process.env['ACTIONS_RUNTIME_TOKEN'] || '';
const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token);
return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions());
return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions());
}
function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
// don't pass changes upstream
const components = paths.slice();
// Add compression method to cache version to restore
// compressed cache as per compression method
if (compressionMethod) {
components.push(compressionMethod);
}
// Only check for windows platforms if enableCrossOsArchive is false
if (process.platform === 'win32' && !enableCrossOsArchive) {
components.push('windows-only');
}
// Add salt to cache version to support breaking changes in cache entry
components.push(versionSalt);
return crypto.createHash('sha256').update(components.join('|')).digest('hex');
}
exports.getCacheVersion = getCacheVersion;
function getCacheEntry(keys, paths, options) {
return __awaiter(this, void 0, void 0, function* () {
const httpClient = createHttpClient();
const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`;
const response = yield (0, requestUtils_1.retryTypedResponse)('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); }));
// Cache not found
@@ -160,7 +144,7 @@ exports.downloadCache = downloadCache;
function reserveCache(key, paths, options) {
return __awaiter(this, void 0, void 0, function* () {
const httpClient = createHttpClient();
const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const reserveCacheRequest = {
key,
version,
@@ -242,20 +226,30 @@ function commitCache(httpClient, cacheId, filesize) {
}));
});
}
function saveCache(cacheId, archivePath, options) {
function saveCache(cacheId, archivePath, signedUploadURL, options) {
return __awaiter(this, void 0, void 0, function* () {
const httpClient = createHttpClient();
core.debug('Upload cache');
yield uploadFile(httpClient, cacheId, archivePath, options);
// Commit Cache
core.debug('Commiting cache');
const cacheSize = utils.getArchiveFileSizeInBytes(archivePath);
core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`);
const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize);
if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) {
throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`);
const uploadOptions = (0, options_1.getUploadOptions)(options);
if (uploadOptions.useAzureSdk) {
// Use Azure storage SDK to upload caches directly to Azure
if (!signedUploadURL) {
throw new Error('Azure Storage SDK can only be used when a signed URL is provided.');
}
yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options);
}
else {
const httpClient = createHttpClient();
core.debug('Upload cache');
yield uploadFile(httpClient, cacheId, archivePath, options);
// Commit Cache
core.debug('Commiting cache');
const cacheSize = utils.getArchiveFileSizeInBytes(archivePath);
core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`);
const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize);
if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) {
throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`);
}
core.info('Cache saved successfully');
}
core.info('Cache saved successfully');
});
}
exports.saveCache = saveCache;
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -9,4 +9,5 @@ export declare function getCompressionMethod(): Promise<CompressionMethod>;
export declare function getCacheFileName(compressionMethod: CompressionMethod): string;
export declare function getGnuTarPathOnWindows(): Promise<string>;
export declare function assertDefined<T>(name: string, value?: T): T;
export declare function isGhes(): boolean;
export declare function getCacheVersion(paths: string[], compressionMethod?: CompressionMethod, enableCrossOsArchive?: boolean): string;
export declare function getRuntimeToken(): string;
+26 -8
View File
@@ -39,7 +39,7 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isGhes = exports.assertDefined = exports.getGnuTarPathOnWindows = exports.getCacheFileName = exports.getCompressionMethod = exports.unlinkFile = exports.resolvePaths = exports.getArchiveFileSizeInBytes = exports.createTempDirectory = void 0;
exports.getRuntimeToken = exports.getCacheVersion = exports.assertDefined = exports.getGnuTarPathOnWindows = exports.getCacheFileName = exports.getCompressionMethod = exports.unlinkFile = exports.resolvePaths = exports.getArchiveFileSizeInBytes = exports.createTempDirectory = void 0;
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const glob = __importStar(require("@actions/glob"));
@@ -50,6 +50,7 @@ const path = __importStar(require("path"));
const semver = __importStar(require("semver"));
const util = __importStar(require("util"));
const constants_1 = require("./constants");
const versionSalt = '1.0';
// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23
function createTempDirectory() {
return __awaiter(this, void 0, void 0, function* () {
@@ -187,12 +188,29 @@ function assertDefined(name, value) {
return value;
}
exports.assertDefined = assertDefined;
function isGhes() {
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
const isGitHubHost = hostname === 'GITHUB.COM';
const isGheHost = hostname.endsWith('.GHE.COM') || hostname.endsWith('.GHE.LOCALHOST');
return !isGitHubHost && !isGheHost;
function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
// don't pass changes upstream
const components = paths.slice();
// Add compression method to cache version to restore
// compressed cache as per compression method
if (compressionMethod) {
components.push(compressionMethod);
}
// Only check for windows platforms if enableCrossOsArchive is false
if (process.platform === 'win32' && !enableCrossOsArchive) {
components.push('windows-only');
}
// Add salt to cache version to support breaking changes in cache entry
components.push(versionSalt);
return crypto.createHash('sha256').update(components.join('|')).digest('hex');
}
exports.isGhes = isGhes;
exports.getCacheVersion = getCacheVersion;
function getRuntimeToken() {
const token = process.env['ACTIONS_RUNTIME_TOKEN'];
if (!token) {
throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable');
}
return token;
}
exports.getRuntimeToken = getRuntimeToken;
//# sourceMappingURL=cacheUtils.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"cacheUtils.js","sourceRoot":"","sources":["../../src/internal/cacheUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AACrC,oDAAqC;AACrC,oDAAqC;AACrC,gDAAiC;AACjC,+CAAgC;AAChC,uCAAwB;AACxB,2CAA4B;AAC5B,+CAAgC;AAChC,2CAA4B;AAC5B,2CAIoB;AAEpB,8FAA8F;AAC9F,SAAsB,mBAAmB;;QACvC,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;QAE/C,IAAI,aAAa,GAAW,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,CAAA;QAE5D,IAAI,CAAC,aAAa,EAAE;YAClB,IAAI,YAAoB,CAAA;YACxB,IAAI,UAAU,EAAE;gBACd,8CAA8C;gBAC9C,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,MAAM,CAAA;aACpD;iBAAM;gBACL,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE;oBACjC,YAAY,GAAG,QAAQ,CAAA;iBACxB;qBAAM;oBACL,YAAY,GAAG,OA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IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,oBAAoB,EAAE;QACzD,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;KAChC;IAED,uEAAuE;IACvE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAE5B,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/E,CAAC;AAvBD,0CAuBC;AAED,SAAgB,eAAe;IAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;KACxE;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAND,0CAMC"}
+3
View File
@@ -0,0 +1,3 @@
export declare function isGhes(): boolean;
export declare function getCacheServiceVersion(): string;
export declare function getCacheServiceURL(): string;
+37
View File
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCacheServiceURL = exports.getCacheServiceVersion = exports.isGhes = void 0;
function isGhes() {
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
const isGitHubHost = hostname === 'GITHUB.COM';
const isGheHost = hostname.endsWith('.GHE.COM');
const isLocalHost = hostname.endsWith('.LOCALHOST');
return !isGitHubHost && !isGheHost && !isLocalHost;
}
exports.isGhes = isGhes;
function getCacheServiceVersion() {
// Cache service v2 is not supported on GHES. We will default to
// cache service v1 even if the feature flag was enabled by user.
if (isGhes())
return 'v1';
return process.env['ACTIONS_CACHE_SERVICE_V2'] ? 'v2' : 'v1';
}
exports.getCacheServiceVersion = getCacheServiceVersion;
function getCacheServiceURL() {
const version = getCacheServiceVersion();
// Based on the version of the cache service, we will determine which
// URL to use.
switch (version) {
case 'v1':
return (process.env['ACTIONS_CACHE_URL'] ||
process.env['ACTIONS_RESULTS_URL'] ||
'');
case 'v2':
return process.env['ACTIONS_RESULTS_URL'] || '';
default:
throw new Error(`Unsupported cache service version: ${version}`);
}
}
exports.getCacheServiceURL = getCacheServiceURL;
//# sourceMappingURL=config.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/internal/config.ts"],"names":[],"mappings":";;;AAAA,SAAgB,MAAM;IACpB,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,IAAI,oBAAoB,CACzD,CAAA;IAED,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,WAAW,EAAE,CAAA;IACvD,MAAM,YAAY,GAAG,QAAQ,KAAK,YAAY,CAAA;IAC9C,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAA;IAC/C,MAAM,WAAW,GAAG,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAA;IAEnD,OAAO,CAAC,YAAY,IAAI,CAAC,SAAS,IAAI,CAAC,WAAW,CAAA;AACpD,CAAC;AAXD,wBAWC;AAED,SAAgB,sBAAsB;IACpC,gEAAgE;IAChE,iEAAiE;IACjE,IAAI,MAAM,EAAE;QAAE,OAAO,IAAI,CAAA;IAEzB,OAAO,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAA;AAC9D,CAAC;AAND,wDAMC;AAED,SAAgB,kBAAkB;IAChC,MAAM,OAAO,GAAG,sBAAsB,EAAE,CAAA;IAExC,qEAAqE;IACrE,cAAc;IACd,QAAQ,OAAO,EAAE;QACf,KAAK,IAAI;YACP,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;gBAChC,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;gBAClC,EAAE,CACH,CAAA;QACH,KAAK,IAAI;YACP,OAAO,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,IAAI,EAAE,CAAA;QACjD;YACE,MAAM,IAAI,KAAK,CAAC,sCAAsC,OAAO,EAAE,CAAC,CAAA;KACnE;AACH,CAAC;AAjBD,gDAiBC"}
+1
View File
@@ -18,3 +18,4 @@ export declare const GnuTarPathOnWindows: string;
export declare const SystemTarPathOnWindows: string;
export declare const TarFilename = "cache.tar";
export declare const ManifestFilename = "manifest.txt";
export declare const CacheFileSizeLimit: number;
+2 -1
View File
@@ -1,6 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManifestFilename = exports.TarFilename = exports.SystemTarPathOnWindows = exports.GnuTarPathOnWindows = exports.SocketTimeout = exports.DefaultRetryDelay = exports.DefaultRetryAttempts = exports.ArchiveToolType = exports.CompressionMethod = exports.CacheFilename = void 0;
exports.CacheFileSizeLimit = exports.ManifestFilename = exports.TarFilename = exports.SystemTarPathOnWindows = exports.GnuTarPathOnWindows = exports.SocketTimeout = exports.DefaultRetryDelay = exports.DefaultRetryAttempts = exports.ArchiveToolType = exports.CompressionMethod = exports.CacheFilename = void 0;
var CacheFilename;
(function (CacheFilename) {
CacheFilename["Gzip"] = "cache.tgz";
@@ -33,4 +33,5 @@ exports.GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\ta
exports.SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`;
exports.TarFilename = 'cache.tar';
exports.ManifestFilename = 'manifest.txt';
exports.CacheFileSizeLimit = 10 * Math.pow(1024, 3); // 10GiB per repository
//# sourceMappingURL=constants.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/internal/constants.ts"],"names":[],"mappings":";;;AAAA,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,m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IACzB,8BAAW,CAAA;IACX,8BAAW,CAAA;AACb,CAAC,EAHW,eAAe,+BAAf,eAAe,QAG1B;AAED,wCAAwC;AAC3B,QAAA,oBAAoB,GAAG,CAAC,CAAA;AAErC,4DAA4D;AAC/C,QAAA,iBAAiB,GAAG,IAAI,CAAA;AAErC,6EAA6E;AAC7E,+EAA+E;AAC/E,cAAc;AACD,QAAA,aAAa,GAAG,IAAI,CAAA;AAEjC,uDAAuD;AAC1C,QAAA,mBAAmB,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,0BAA0B,CAAA;AAE3F,uDAAuD;AAC1C,QAAA,sBAAsB,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,8BAA8B,CAAA;AAEpF,QAAA,WAAW,GAAG,WAAW,CAAA;AAEzB,QAAA,gBAAgB,GAAG,cAAc,CAAA;AAEjC,QAAA,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA,CAAC,uBAAuB"}
@@ -0,0 +1,6 @@
import { CacheServiceClientJSON } from '../../generated/results/api/v1/cache.twirp-client';
export declare function internalCacheTwirpClient(options?: {
maxAttempts?: number;
retryIntervalMs?: number;
retryMultiplier?: number;
}): CacheServiceClientJSON;
+160
View File
@@ -0,0 +1,160 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.internalCacheTwirpClient = void 0;
const core_1 = require("@actions/core");
const user_agent_1 = require("./user-agent");
const errors_1 = require("./errors");
const config_1 = require("../config");
const cacheUtils_1 = require("../cacheUtils");
const auth_1 = require("@actions/http-client/lib/auth");
const http_client_1 = require("@actions/http-client");
const cache_twirp_client_1 = require("../../generated/results/api/v1/cache.twirp-client");
/**
* This class is a wrapper around the CacheServiceClientJSON class generated by Twirp.
*
* It adds retry logic to the request method, which is not present in the generated client.
*
* This class is used to interact with cache service v2.
*/
class CacheServiceClient {
constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) {
this.maxAttempts = 5;
this.baseRetryIntervalMilliseconds = 3000;
this.retryMultiplier = 1.5;
const token = (0, cacheUtils_1.getRuntimeToken)();
this.baseUrl = (0, config_1.getCacheServiceURL)();
if (maxAttempts) {
this.maxAttempts = maxAttempts;
}
if (baseRetryIntervalMilliseconds) {
this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds;
}
if (retryMultiplier) {
this.retryMultiplier = retryMultiplier;
}
this.httpClient = new http_client_1.HttpClient(userAgent, [
new auth_1.BearerCredentialHandler(token)
]);
}
// This function satisfies the Rpc interface. It is compatible with the JSON
// JSON generated client.
request(service, method, contentType, data) {
return __awaiter(this, void 0, void 0, function* () {
const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href;
(0, core_1.debug)(`[Request] ${method} ${url}`);
const headers = {
'Content-Type': contentType
};
try {
const { body } = yield this.retryableRequest(() => __awaiter(this, void 0, void 0, function* () { return this.httpClient.post(url, JSON.stringify(data), headers); }));
return body;
}
catch (error) {
throw new Error(`Failed to ${method}: ${error.message}`);
}
});
}
retryableRequest(operation) {
return __awaiter(this, void 0, void 0, function* () {
let attempt = 0;
let errorMessage = '';
let rawBody = '';
while (attempt < this.maxAttempts) {
let isRetryable = false;
try {
const response = yield operation();
const statusCode = response.message.statusCode;
rawBody = yield response.readBody();
(0, core_1.debug)(`[Response] - ${response.message.statusCode}`);
(0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`);
const body = JSON.parse(rawBody);
(0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`);
if (this.isSuccessStatusCode(statusCode)) {
return { response, body };
}
isRetryable = this.isRetryableHttpStatusCode(statusCode);
errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`;
if (body.msg) {
if (errors_1.UsageError.isUsageErrorMessage(body.msg)) {
throw new errors_1.UsageError();
}
errorMessage = `${errorMessage}: ${body.msg}`;
}
}
catch (error) {
if (error instanceof SyntaxError) {
(0, core_1.debug)(`Raw Body: ${rawBody}`);
}
if (error instanceof errors_1.UsageError) {
throw error;
}
if (errors_1.NetworkError.isNetworkErrorCode(error === null || error === void 0 ? void 0 : error.code)) {
throw new errors_1.NetworkError(error === null || error === void 0 ? void 0 : error.code);
}
isRetryable = true;
errorMessage = error.message;
}
if (!isRetryable) {
throw new Error(`Received non-retryable error: ${errorMessage}`);
}
if (attempt + 1 === this.maxAttempts) {
throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`);
}
const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt);
(0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`);
yield this.sleep(retryTimeMilliseconds);
attempt++;
}
throw new Error(`Request failed`);
});
}
isSuccessStatusCode(statusCode) {
if (!statusCode)
return false;
return statusCode >= 200 && statusCode < 300;
}
isRetryableHttpStatusCode(statusCode) {
if (!statusCode)
return false;
const retryableStatusCodes = [
http_client_1.HttpCodes.BadGateway,
http_client_1.HttpCodes.GatewayTimeout,
http_client_1.HttpCodes.InternalServerError,
http_client_1.HttpCodes.ServiceUnavailable,
http_client_1.HttpCodes.TooManyRequests
];
return retryableStatusCodes.includes(statusCode);
}
sleep(milliseconds) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, milliseconds));
});
}
getExponentialRetryTimeMilliseconds(attempt) {
if (attempt < 0) {
throw new Error('attempt should be a positive integer');
}
if (attempt === 0) {
return this.baseRetryIntervalMilliseconds;
}
const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt);
const maxTime = minTime * this.retryMultiplier;
// returns a random number between minTime and maxTime (exclusive)
return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
}
}
function internalCacheTwirpClient(options) {
const client = new CacheServiceClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier);
return new cache_twirp_client_1.CacheServiceClientJSON(client);
}
exports.internalCacheTwirpClient = internalCacheTwirpClient;
//# sourceMappingURL=cacheTwirpClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"cacheTwirpClient.js","sourceRoot":"","sources":["../../../src/internal/shared/cacheTwirpClient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAyC;AACzC,6CAA+C;AAC/C,qCAAiD;AACjD,sCAA4C;AAC5C,8CAA6C;AAC7C,wDAAqE;AACrE,sDAA8E;AAC9E,0FAAwF;AAYxF;;;;;;GAMG;AACH,MAAM,kBAAkB;IAOtB,YACE,SAAiB,EACjB,WAAoB,EACpB,6BAAsC,EACtC,eAAwB;QARlB,gBAAW,GAAG,CAAC,CAAA;QACf,kCAA6B,GAAG,IAAI,CAAA;QACpC,oBAAe,GAAG,GAAG,CAAA;QAQ3B,MAAM,KAAK,GAAG,IAAA,4BAAe,GAAE,CAAA;QAC/B,IAAI,CAAC,OAAO,GAAG,IAAA,2BAAkB,GAAE,CAAA;QACnC,IAAI,WAAW,EAAE;YACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;SAC/B;QACD,IAAI,6BAA6B,EAAE;YACjC,IAAI,CAAC,6BAA6B,GAAG,6BAA6B,CAAA;SACnE;QACD,IAAI,eAAe,EAAE;YACnB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAA;SACvC;QAED,IAAI,CAAC,UAAU,GAAG,IAAI,wBA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OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAA;QAClE,CAAC;KAAA;IAED,mCAAmC,CAAC,OAAe;QACjD,IAAI,OAAO,GAAG,CAAC,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;SACxD;QAED,IAAI,OAAO,KAAK,CAAC,EAAE;YACjB,OAAO,IAAI,CAAC,6BAA6B,CAAA;SAC1C;QAED,MAAM,OAAO,GACX,IAAI,CAAC,6BAA6B,GAAG,SAAA,IAAI,CAAC,eAAe,EAAI,OAAO,CAAA,CAAA;QACtE,MAAM,OAAO,GAAG,OAAO,GAAG,IAAI,CAAC,eAAe,CAAA;QAE9C,kEAAkE;QAClE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,GAAG,OAAO,CAAC,GAAG,OAAO,CAAC,CAAA;IAClE,CAAC;CACF;AAED,SAAgB,wBAAwB,CAAC,OAIxC;IACC,MAAM,MAAM,GAAG,IAAI,kBAAkB,CACnC,IAAA,+BAAkB,GAAE,EACpB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,EACpB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,EACxB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,CACzB,CAAA;IACD,OAAO,IAAI,2CAAsB,CAAC,MAAM,CAAC,CAAA;AAC3C,CAAC;AAZD,4DAYC"}
+22
View File
@@ -0,0 +1,22 @@
export declare class FilesNotFoundError extends Error {
files: string[];
constructor(files?: string[]);
}
export declare class InvalidResponseError extends Error {
constructor(message: string);
}
export declare class CacheNotFoundError extends Error {
constructor(message?: string);
}
export declare class GHESNotSupportedError extends Error {
constructor(message?: string);
}
export declare class NetworkError extends Error {
code: string;
constructor(code: string);
static isNetworkErrorCode: (code?: string) => boolean;
}
export declare class UsageError extends Error {
constructor();
static isUsageErrorMessage: (msg?: string) => boolean;
}
+70
View File
@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UsageError = exports.NetworkError = exports.GHESNotSupportedError = exports.CacheNotFoundError = exports.InvalidResponseError = exports.FilesNotFoundError = void 0;
class FilesNotFoundError extends Error {
constructor(files = []) {
let message = 'No files were found to upload';
if (files.length > 0) {
message += `: ${files.join(', ')}`;
}
super(message);
this.files = files;
this.name = 'FilesNotFoundError';
}
}
exports.FilesNotFoundError = FilesNotFoundError;
class InvalidResponseError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidResponseError';
}
}
exports.InvalidResponseError = InvalidResponseError;
class CacheNotFoundError extends Error {
constructor(message = 'Cache not found') {
super(message);
this.name = 'CacheNotFoundError';
}
}
exports.CacheNotFoundError = CacheNotFoundError;
class GHESNotSupportedError extends Error {
constructor(message = '@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.') {
super(message);
this.name = 'GHESNotSupportedError';
}
}
exports.GHESNotSupportedError = GHESNotSupportedError;
class NetworkError extends Error {
constructor(code) {
const message = `Unable to make request: ${code}\nIf you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`;
super(message);
this.code = code;
this.name = 'NetworkError';
}
}
exports.NetworkError = NetworkError;
NetworkError.isNetworkErrorCode = (code) => {
if (!code)
return false;
return [
'ECONNRESET',
'ENOTFOUND',
'ETIMEDOUT',
'ECONNREFUSED',
'EHOSTUNREACH'
].includes(code);
};
class UsageError extends Error {
constructor() {
const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;
super(message);
this.name = 'UsageError';
}
}
exports.UsageError = UsageError;
UsageError.isUsageErrorMessage = (msg) => {
if (!msg)
return false;
return msg.includes('insufficient usage');
};
//# sourceMappingURL=errors.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/internal/shared/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,kBAAmB,SAAQ,KAAK;IAG3C,YAAY,QAAkB,EAAE;QAC9B,IAAI,OAAO,GAAG,+BAA+B,CAAA;QAC7C,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;YACpB,OAAO,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;SACnC;QAED,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAA;IAClC,CAAC;CACF;AAbD,gDAaC;AAED,MAAa,oBAAqB,SAAQ,KAAK;IAC7C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAA;IACpC,CAAC;CACF;AALD,oDAKC;AAED,MAAa,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,OAAO,GAAG,iBAAiB;QACrC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAA;IAClC,CAAC;CACF;AALD,gDAKC;AAED,MAAa,qBAAsB,SAAQ,KAAK;IAC9C,YACE,OAAO,GAAG,mHAAmH;QAE7H,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAA;IACrC,CAAC;CACF;AAPD,sDAOC;AAED,MAAa,YAAa,SAAQ,KAAK;IAGrC,YAAY,IAAY;QACtB,MAAM,OAAO,GAAG,2BAA2B,IAAI,kRAAkR,CAAA;QACjU,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;;AARH,oCAoBC;AAVQ,+BAAkB,GAAG,CAAC,IAAa,EAAW,EAAE;IACrD,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAA;IACvB,OAAO;QACL,YAAY;QACZ,WAAW;QACX,WAAW;QACX,cAAc;QACd,cAAc;KACf,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AAClB,CAAC,CAAA;AAGH,MAAa,UAAW,SAAQ,KAAK;IACnC;QACE,MAAM,OAAO,GAAG,iSAAiS,CAAA;QACjT,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,YAAY,CAAA;IAC1B,CAAC;;AALH,gCAWC;AAJQ,8BAAmB,GAAG,CAAC,GAAY,EAAW,EAAE;IACrD,IAAI,CAAC,GAAG;QAAE,OAAO,KAAK,CAAA;IACtB,OAAO,GAAG,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAA;AAC3C,CAAC,CAAA"}
+4
View File
@@ -0,0 +1,4 @@
/**
* Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package
*/
export declare function getUserAgentString(): string;
+13
View File
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserAgentString = void 0;
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const packageJson = require('../../../package.json');
/**
* Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package
*/
function getUserAgentString() {
return `@actions/cache-${packageJson.version}`;
}
exports.getUserAgentString = getUserAgentString;
//# sourceMappingURL=user-agent.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"user-agent.js","sourceRoot":"","sources":["../../../src/internal/shared/user-agent.ts"],"names":[],"mappings":";;;AAAA,qGAAqG;AACrG,MAAM,WAAW,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAA;AAEpD;;GAEG;AACH,SAAgB,kBAAkB;IAChC,OAAO,kBAAkB,WAAW,CAAC,OAAO,EAAE,CAAA;AAChD,CAAC;AAFD,gDAEC"}
+60
View File
@@ -0,0 +1,60 @@
import { BlobUploadCommonResponse } from '@azure/storage-blob';
import { TransferProgressEvent } from '@azure/ms-rest-js';
import { UploadOptions } from '../options';
/**
* Class for tracking the upload state and displaying stats.
*/
export declare class UploadProgress {
contentLength: number;
sentBytes: number;
startTime: number;
displayedComplete: boolean;
timeoutHandle?: ReturnType<typeof setTimeout>;
constructor(contentLength: number);
/**
* Sets the number of bytes sent
*
* @param sentBytes the number of bytes sent
*/
setSentBytes(sentBytes: number): void;
/**
* Returns the total number of bytes transferred.
*/
getTransferredBytes(): number;
/**
* Returns true if the upload is complete.
*/
isDone(): boolean;
/**
* Prints the current upload stats. Once the upload completes, this will print one
* last line and then stop.
*/
display(): void;
/**
* Returns a function used to handle TransferProgressEvents.
*/
onProgress(): (progress: TransferProgressEvent) => void;
/**
* Starts the timer that displays the stats.
*
* @param delayInMs the delay between each write
*/
startDisplayTimer(delayInMs?: number): void;
/**
* Stops the timer that displays the stats. As this typically indicates the upload
* is complete, this will display one last line, unless the last line has already
* been written.
*/
stopDisplayTimer(): void;
}
/**
* Uploads a cache archive directly to Azure Blob Storage using the Azure SDK.
* This function will display progress information to the console. Concurrency of the
* upload is determined by the calling functions.
*
* @param signedUploadURL
* @param archivePath
* @param options
* @returns
*/
export declare function uploadCacheArchiveSDK(signedUploadURL: string, archivePath: string, options?: UploadOptions): Promise<BlobUploadCommonResponse>;
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadCacheArchiveSDK = exports.UploadProgress = void 0;
const core = __importStar(require("@actions/core"));
const storage_blob_1 = require("@azure/storage-blob");
const errors_1 = require("./shared/errors");
/**
* Class for tracking the upload state and displaying stats.
*/
class UploadProgress {
constructor(contentLength) {
this.contentLength = contentLength;
this.sentBytes = 0;
this.displayedComplete = false;
this.startTime = Date.now();
}
/**
* Sets the number of bytes sent
*
* @param sentBytes the number of bytes sent
*/
setSentBytes(sentBytes) {
this.sentBytes = sentBytes;
}
/**
* Returns the total number of bytes transferred.
*/
getTransferredBytes() {
return this.sentBytes;
}
/**
* Returns true if the upload is complete.
*/
isDone() {
return this.getTransferredBytes() === this.contentLength;
}
/**
* Prints the current upload stats. Once the upload completes, this will print one
* last line and then stop.
*/
display() {
if (this.displayedComplete) {
return;
}
const transferredBytes = this.sentBytes;
const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1);
const elapsedTime = Date.now() - this.startTime;
const uploadSpeed = (transferredBytes /
(1024 * 1024) /
(elapsedTime / 1000)).toFixed(1);
core.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`);
if (this.isDone()) {
this.displayedComplete = true;
}
}
/**
* Returns a function used to handle TransferProgressEvents.
*/
onProgress() {
return (progress) => {
this.setSentBytes(progress.loadedBytes);
};
}
/**
* Starts the timer that displays the stats.
*
* @param delayInMs the delay between each write
*/
startDisplayTimer(delayInMs = 1000) {
const displayCallback = () => {
this.display();
if (!this.isDone()) {
this.timeoutHandle = setTimeout(displayCallback, delayInMs);
}
};
this.timeoutHandle = setTimeout(displayCallback, delayInMs);
}
/**
* Stops the timer that displays the stats. As this typically indicates the upload
* is complete, this will display one last line, unless the last line has already
* been written.
*/
stopDisplayTimer() {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle);
this.timeoutHandle = undefined;
}
this.display();
}
}
exports.UploadProgress = UploadProgress;
/**
* Uploads a cache archive directly to Azure Blob Storage using the Azure SDK.
* This function will display progress information to the console. Concurrency of the
* upload is determined by the calling functions.
*
* @param signedUploadURL
* @param archivePath
* @param options
* @returns
*/
function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const blobClient = new storage_blob_1.BlobClient(signedUploadURL);
const blockBlobClient = blobClient.getBlockBlobClient();
const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0);
// Specify data transfer options
const uploadOptions = {
blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize,
concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency,
maxSingleShotSize: 128 * 1024 * 1024,
onProgress: uploadProgress.onProgress()
};
try {
uploadProgress.startDisplayTimer();
core.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`);
const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions);
// TODO: better management of non-retryable errors
if (response._response.status >= 400) {
throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`);
}
return response;
}
catch (error) {
core.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error.message}`);
throw error;
}
finally {
uploadProgress.stopDisplayTimer();
}
});
}
exports.uploadCacheArchiveSDK = uploadCacheArchiveSDK;
//# sourceMappingURL=uploadUtils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uploadUtils.js","sourceRoot":"","sources":["../../src/internal/uploadUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AACrC,sDAK4B;AAE5B,4CAAoD;AAGpD;;GAEG;AACH,MAAa,cAAc;IAOzB,YAAY,aAAqB;QAC/B,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;QAClC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAA;QAClB,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAA;QAC9B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,YAAY,CAAC,SAAiB;QAC5B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED;;OAEG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,mBAAmB,EAAE,KAAK,IAAI,CAAC,aAAa,CAAA;IAC1D,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,IAAI,IAAI,CAAC,iBAAiB,EAAE;YAC1B,OAAM;SACP;QAED,MAAM,gBAAgB,GAAG,IAAI,CAAC,SAAS,CAAA;QACvC,MAAM,UAAU,GAAG,CAAC,GAAG,GAAG,CAAC,gBAAgB,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CACxE,CAAC,CACF,CAAA;QACD,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IA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I,yBAAU,CAAC,eAAe,CAAC,CAAA;QAC9D,MAAM,eAAe,GAAoB,UAAU,CAAC,kBAAkB,EAAE,CAAA;QACxE,MAAM,cAAc,GAAG,IAAI,cAAc,CAAC,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,gBAAgB,mCAAI,CAAC,CAAC,CAAA;QAEzE,gCAAgC;QAChC,MAAM,aAAa,GAAmC;YACpD,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe;YACnC,WAAW,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB;YACvC,iBAAiB,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI;YACpC,UAAU,EAAE,cAAc,CAAC,UAAU,EAAE;SACxC,CAAA;QAED,IAAI;YACF,cAAc,CAAC,iBAAiB,EAAE,CAAA;YAElC,IAAI,CAAC,KAAK,CACR,eAAe,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,WAAW,IAAI,UAAU,CAAC,aAAa,EAAE,CACvF,CAAA;YAED,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,UAAU,CAC/C,WAAW,EACX,aAAa,CACd,CAAA;YAED,kDAAkD;YAClD,IAAI,QAAQ,CAAC,SAAS,CAAC,MAAM,IAAI,GAAG,EAAE;gBACpC,MAAM,IAAI,6BAAoB,CAC5B,yDAAyD,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,CACrF,CAAA;aACF;YAED,OAAO,QAAQ,CAAA;SAChB;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,CAAC,OAAO,CACV,kEAAkE,KAAK,CAAC,OAAO,EAAE,CAClF,CAAA;YACD,MAAM,KAAK,CAAA;SACZ;gBAAS;YACR,cAAc,CAAC,gBAAgB,EAAE,CAAA;SAClC;;CACF;AA7CD,sDA6CC"}
+12
View File
@@ -2,6 +2,14 @@
* Options to control cache upload
*/
export interface UploadOptions {
/**
* Indicates whether to use the Azure Blob SDK to download caches
* that are stored on Azure Blob Storage to improve reliability and
* performance
*
* @default false
*/
useAzureSdk?: boolean;
/**
* Number of parallel cache upload
*
@@ -14,6 +22,10 @@ export interface UploadOptions {
* @default 32MB
*/
uploadChunkSize?: number;
/**
* Archive size in bytes
*/
archiveSizeBytes?: number;
}
/**
* Options to control cache download
+17
View File
@@ -31,11 +31,16 @@ const core = __importStar(require("@actions/core"));
* @param copy the original upload options
*/
function getUploadOptions(copy) {
// Defaults if not overriden
const result = {
useAzureSdk: false,
uploadConcurrency: 4,
uploadChunkSize: 32 * 1024 * 1024
};
if (copy) {
if (typeof copy.useAzureSdk === 'boolean') {
result.useAzureSdk = copy.useAzureSdk;
}
if (typeof copy.uploadConcurrency === 'number') {
result.uploadConcurrency = copy.uploadConcurrency;
}
@@ -43,6 +48,18 @@ function getUploadOptions(copy) {
result.uploadChunkSize = copy.uploadChunkSize;
}
}
/**
* Add env var overrides
*/
// Cap the uploadConcurrency at 32
result.uploadConcurrency = !isNaN(Number(process.env['CACHE_UPLOAD_CONCURRENCY']))
? Math.min(32, Number(process.env['CACHE_UPLOAD_CONCURRENCY']))
: result.uploadConcurrency;
// Cap the uploadChunkSize at 128MiB
result.uploadChunkSize = !isNaN(Number(process.env['CACHE_UPLOAD_CHUNK_SIZE']))
? Math.min(128 * 1024 * 1024, Number(process.env['CACHE_UPLOAD_CHUNK_SIZE']) * 1024 * 1024)
: result.uploadChunkSize;
core.debug(`Use Azure SDK: ${result.useAzureSdk}`);
core.debug(`Upload concurrency: ${result.uploadConcurrency}`);
core.debug(`Upload chunk size: ${result.uploadChunkSize}`);
return result;
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAwErC;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,IAAoB;IACnD,MAAM,MAAM,GAAkB;QAC5B,iBAAiB,EAAE,CAAC;QACpB,eAAe,EAAE,EAA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G,CAAC,+BAA+B,CAAC,CAAA;IAE9C,IACE,0BAA0B;QAC1B,CAAC,KAAK,CAAC,MAAM,CAAC,0BAA0B,CAAC,CAAC;QAC1C,QAAQ,CAAC,MAAM,CAAC,0BAA0B,CAAC,CAAC,EAC5C;QACA,MAAM,CAAC,kBAAkB,GAAG,MAAM,CAAC,0BAA0B,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA;KAC3E;IACD,IAAI,CAAC,KAAK,CAAC,kBAAkB,MAAM,CAAC,WAAW,EAAE,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,yBAAyB,MAAM,CAAC,mBAAmB,EAAE,CAAC,CAAA;IACjE,IAAI,CAAC,KAAK,CAAC,yBAAyB,MAAM,CAAC,WAAW,EAAE,CAAC,CAAA;IACzD,IAAI,CAAC,KAAK,CACR,gDAAgD,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,EAAE,CAC/F,CAAA;IACD,IAAI,CAAC,KAAK,CAAC,kCAAkC,MAAM,CAAC,kBAAkB,EAAE,CAAC,CAAA;IACzE,IAAI,CAAC,KAAK,CAAC,gBAAgB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAA;IAE/C,OAAO,MAAM,CAAA;AACf,CAAC;AAvDD,gDAuDC"}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@actions/cache",
"version": "3.3.0",
"version": "4.0.2",
"preview": true,
"description": "Actions cache lib",
"keywords": [
@@ -45,6 +45,7 @@
"@azure/abort-controller": "^1.1.0",
"@azure/ms-rest-js": "^2.6.0",
"@azure/storage-blob": "^12.13.0",
"@protobuf-ts/plugin": "^2.9.4",
"semver": "^6.3.1"
},
"devDependencies": {
+174
View File
@@ -0,0 +1,174 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
+61
View File
@@ -0,0 +1,61 @@
@protobuf-ts/plugin-framework
=============================
A framework to create protoc plugins in typescript.
The google protocol buffer compiler (protoc) has a plugin system. With a
protoc plugin, it is possible to generate code for .proto files in any
language, not just the ones supported directly by protoc.
A protoc plugin receives a `CodeGeneratorRequest` (a protobuf message)
via stdin and returns a `CodeGeneratorResponse` via stdout.
This framework aims to make it as easy as possible to write a protoc
plugin in typescript. It has special support for generating typescript
code, but can be used to generate code in other languages.
### Features
- provides a symbol table that can be used to track generated types
in any language
- has special support for generating typescript code using the
typescript compiler API. For example, it has a simple API to import
objects from a package, or from the symbol table.
- provides a base class for plugins that supports parameters, error
handling, supported features and easy setup.
- builds a tree of descriptors so that it is trivial to lookup the
parent of a nested message, for example.
- builds a lookup object to find the descriptor for a given type name
- provides a string format object that can print a message field like
it was typed by the user.
- provides a source code comment lookup that can be used to easily
find comments for a given element in a .proto
- provides convenience methods to check if a field was declared
optional or as a oneof member
### Getting started
- Check the types and comments of [descriptor.proto](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto)
and [plugin.proto](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/compiler/plugin.proto)
to get familiar with the plugin system of protoc.
- Take a look at `descriptor-registry.ts` to see the if it can help you work with the
descriptor protos that the compiler sends you.
- Take a look at `plugin-base.ts` for a base class that can help with some plumbing.
- Take a look at the source code of [protobuf-ts](https://github.com/timostamm/protobuf-ts/), which uses this framework.
### Copyright
- The files [plugin.ts](https://github.com/timostamm/protobuf-ts/blob/master/packages/plugin-framework/src/google/protobuf/compiler/plugin.ts) and [descriptor.ts](https://github.com/timostamm/protobuf-ts/blob/master/packages/plugin-framework/src/google/protobuf/descriptor.ts) are Copyright 2008 Google Inc., licensed under BSD-3-Clause
- All other files are licensed under Apache-2.0, see [LICENSE](https://github.com/timostamm/protobuf-ts/blob/master/packages/plugin-framework/LICENSE).
@@ -0,0 +1,334 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DescriptorInfo = exports.isAnyTypeDescriptorProto = void 0;
const descriptor_1 = require("./google/protobuf/descriptor");
const runtime_1 = require("@protobuf-ts/runtime");
const string_format_1 = require("./string-format");
/**
* Is this a first-class type?
*/
function isAnyTypeDescriptorProto(arg) {
return descriptor_1.DescriptorProto.is(arg) || descriptor_1.EnumDescriptorProto.is(arg) || descriptor_1.ServiceDescriptorProto.is(arg);
}
exports.isAnyTypeDescriptorProto = isAnyTypeDescriptorProto;
class DescriptorInfo {
constructor(tree, nameLookup) {
this.tree = tree;
this.nameLookup = nameLookup;
}
getAllExtensions() {
if (!this.allExtensions) {
this.allExtensions = [];
for (let file of this.tree.allFiles()) {
this.allExtensions.push(...file.extension);
for (let msg of file.messageType) {
this.allExtensions.push(...msg.extension);
}
}
}
return this.allExtensions;
}
isExtension(fieldDescriptor) {
if (fieldDescriptor.extendee === undefined) {
return false;
}
const parent = this.tree.parentOf(fieldDescriptor);
return parent.extension.includes(fieldDescriptor);
}
extensionsFor(descriptorOrTypeName) {
let extendeeTypeName;
if (typeof descriptorOrTypeName === "string") {
extendeeTypeName = this.nameLookup.makeTypeName(this.nameLookup.resolveTypeName(descriptorOrTypeName));
}
else {
extendeeTypeName = this.nameLookup.makeTypeName(descriptorOrTypeName);
}
return this.getAllExtensions().filter(ext => this.nameLookup.normalizeTypeName(ext.extendee) === extendeeTypeName);
}
getExtensionName(fieldDescriptor) {
runtime_1.assert(this.isExtension(fieldDescriptor), `${string_format_1.StringFormat.formatName(fieldDescriptor)} is not an extension. use isExtension() before getExtensionName()`);
runtime_1.assert(fieldDescriptor.name);
let extensionName;
let parent = this.tree.parentOf(fieldDescriptor);
if (descriptor_1.FileDescriptorProto.is(parent)) {
extensionName = parent.package
? `${parent.package}.${fieldDescriptor.name}`
: `${fieldDescriptor.name}`;
}
else {
extensionName = `${this.nameLookup.makeTypeName(parent)}.${fieldDescriptor.name}`;
}
return extensionName;
}
getFieldCustomJsonName(fieldDescriptor) {
const name = runtime_1.lowerCamelCase(fieldDescriptor.name);
const jsonName = fieldDescriptor.jsonName;
if (jsonName !== undefined && jsonName !== '' && jsonName !== name) {
return jsonName;
}
return undefined;
}
isEnumField(fieldDescriptor) {
return fieldDescriptor.type === descriptor_1.FieldDescriptorProto_Type.ENUM;
}
getEnumFieldEnum(fieldDescriptor) {
if (fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.ENUM) {
throw new Error(`${string_format_1.StringFormat.formatName(fieldDescriptor)} is not a enum field. use isEnumField() before getEnumFieldEnum().`);
}
runtime_1.assert(fieldDescriptor.typeName !== undefined, `Missing enum type name for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
let enumType = this.nameLookup.peekTypeName(fieldDescriptor.typeName);
runtime_1.assert(enumType !== undefined, `Missing enum type ${fieldDescriptor.typeName} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(descriptor_1.EnumDescriptorProto.is(enumType), `Invalid enum type for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
return enumType;
}
isMessageField(fieldDescriptor) {
let msg = fieldDescriptor.type === descriptor_1.FieldDescriptorProto_Type.MESSAGE;
if (!msg) {
return false;
}
if (fieldDescriptor.name === undefined) {
return false;
}
if (this.isMapField(fieldDescriptor)) {
return false;
}
return true;
}
isGroupField(fieldDescriptor) {
return fieldDescriptor.type === descriptor_1.FieldDescriptorProto_Type.GROUP;
}
getMessageFieldMessage(fieldDescriptor) {
if (!this.isMessageField(fieldDescriptor)) {
throw new Error(`${string_format_1.StringFormat.formatName(fieldDescriptor)} is not a message field. use isMessageField() before getMessageFieldMessage().`);
}
runtime_1.assert(fieldDescriptor.typeName !== undefined, `Missing message type name for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
let messageType = this.nameLookup.peekTypeName(fieldDescriptor.typeName);
runtime_1.assert(messageType !== undefined, `Missing message type ${fieldDescriptor.typeName} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(descriptor_1.DescriptorProto.is(messageType), `Invalid message type for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
return messageType;
}
isScalarField(fieldDescriptor) {
switch (fieldDescriptor.type) {
case descriptor_1.FieldDescriptorProto_Type.ENUM:
case descriptor_1.FieldDescriptorProto_Type.MESSAGE:
case descriptor_1.FieldDescriptorProto_Type.GROUP:
case descriptor_1.FieldDescriptorProto_Type.UNSPECIFIED$:
return false;
}
return true;
}
getScalarFieldType(fieldDescriptor) {
if (!this.isScalarField(fieldDescriptor)) {
throw new Error(`${string_format_1.StringFormat.formatName(fieldDescriptor)} is not a scalar field. use isScalarField() before getScalarFieldType().`);
}
runtime_1.assert(fieldDescriptor.type !== undefined);
runtime_1.assert(fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.ENUM);
runtime_1.assert(fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.MESSAGE);
runtime_1.assert(fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.GROUP);
runtime_1.assert(fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.UNSPECIFIED$);
return fieldDescriptor.type;
}
isMapField(fieldDescriptor) {
return this.getMapEntryMessage(fieldDescriptor) !== undefined;
}
getMapKeyType(fieldDescriptor) {
let entry = this.getMapEntryMessage(fieldDescriptor);
if (!entry) {
throw new Error(`${string_format_1.StringFormat.formatName(fieldDescriptor)} is not a map field. use isMapField() before getMapKeyType().`);
}
let keyField = entry.field.find(fd => fd.number === 1);
runtime_1.assert(keyField !== undefined, `Missing map entry key field 1 for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== undefined, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.UNSPECIFIED$, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.GROUP, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.MESSAGE, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.ENUM, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.FLOAT, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.DOUBLE, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
runtime_1.assert(keyField.type !== descriptor_1.FieldDescriptorProto_Type.BYTES, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
return keyField.type;
}
getMapValueType(fieldDescriptor) {
let entry = this.getMapEntryMessage(fieldDescriptor);
if (!entry) {
throw new Error(`${string_format_1.StringFormat.formatName(fieldDescriptor)} is not a map field. use isMapField() before getMapValueType().`);
}
let valueField = entry.field.find(fd => fd.number === 2);
runtime_1.assert(valueField !== undefined, `Missing map entry value field 2 for ${string_format_1.StringFormat.formatName(fieldDescriptor)}`);
if (this.isScalarField(valueField)) {
return this.getScalarFieldType(valueField);
}
if (this.isEnumField(valueField)) {
return this.getEnumFieldEnum(valueField);
}
return this.getMessageFieldMessage(valueField);
}
getMapEntryMessage(fieldDescriptor) {
var _a;
if (fieldDescriptor.type !== descriptor_1.FieldDescriptorProto_Type.MESSAGE) {
return undefined;
}
if (fieldDescriptor.typeName === undefined || fieldDescriptor.typeName === "") {
return undefined;
}
let typeDescriptor = this.nameLookup.resolveTypeName(fieldDescriptor.typeName);
if (!descriptor_1.DescriptorProto.is(typeDescriptor)) {
return undefined;
}
if (((_a = typeDescriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry) !== true) {
return undefined;
}
return typeDescriptor;
}
isExplicitlyDeclaredDeprecated(descriptor) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
if (descriptor_1.FileDescriptorProto.is(descriptor)) {
return (_b = (_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false;
}
if (descriptor_1.DescriptorProto.is(descriptor)) {
return (_d = (_c = descriptor.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false;
}
if (descriptor_1.FieldDescriptorProto.is(descriptor)) {
return (_f = (_e = descriptor.options) === null || _e === void 0 ? void 0 : _e.deprecated) !== null && _f !== void 0 ? _f : false;
}
if (descriptor_1.EnumDescriptorProto.is(descriptor)) {
return (_h = (_g = descriptor.options) === null || _g === void 0 ? void 0 : _g.deprecated) !== null && _h !== void 0 ? _h : false;
}
if (descriptor_1.EnumValueDescriptorProto.is(descriptor)) {
return (_k = (_j = descriptor.options) === null || _j === void 0 ? void 0 : _j.deprecated) !== null && _k !== void 0 ? _k : false;
}
if (descriptor_1.ServiceDescriptorProto.is(descriptor)) {
return (_m = (_l = descriptor.options) === null || _l === void 0 ? void 0 : _l.deprecated) !== null && _m !== void 0 ? _m : false;
}
if (descriptor_1.MethodDescriptorProto.is(descriptor)) {
return (_p = (_o = descriptor.options) === null || _o === void 0 ? void 0 : _o.deprecated) !== null && _p !== void 0 ? _p : false;
}
if (descriptor_1.OneofDescriptorProto.is(descriptor)) {
return false;
}
return false;
}
isSyntheticElement(descriptor) {
var _a;
if (descriptor_1.DescriptorProto.is(descriptor)) {
if ((_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry) {
return true;
}
if (descriptor.name && descriptor.name.startsWith("$synthetic.")) {
return true;
}
}
return false;
}
isUserDeclaredOneof(fieldDescriptor) {
if (fieldDescriptor.oneofIndex === undefined) {
return false;
}
return fieldDescriptor.proto3Optional !== true;
}
isUserDeclaredOptional(fieldDescriptor) {
if (this.isUserDeclaredOneof(fieldDescriptor)) {
return false;
}
if (fieldDescriptor.proto3Optional === true) {
return true;
}
if (fieldDescriptor.proto3Optional === false) {
return false;
}
const file = this.tree.fileOf(fieldDescriptor);
if (file.syntax === 'proto3') {
return false;
}
runtime_1.assert(file.syntax === undefined || file.syntax === 'proto2', `unsupported syntax "${file.syntax}"`);
return fieldDescriptor.label === descriptor_1.FieldDescriptorProto_Label.OPTIONAL;
}
isUserDeclaredRepeated(fieldDescriptor) {
var _a;
if (fieldDescriptor.label !== descriptor_1.FieldDescriptorProto_Label.REPEATED) {
return false;
}
const name = fieldDescriptor.typeName;
if (name === undefined || name === "") {
return true;
}
const typeDescriptor = this.nameLookup.resolveTypeName(name);
if (descriptor_1.DescriptorProto.is(typeDescriptor)) {
return !((_a = typeDescriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry);
}
return true;
}
shouldBePackedRepeated(fieldDescriptor) {
var _a;
let file = this.tree.fileOf(fieldDescriptor);
let standard, declared = (_a = fieldDescriptor.options) === null || _a === void 0 ? void 0 : _a.packed;
if (file.syntax === 'proto3') {
standard = true;
}
else {
runtime_1.assert(file.syntax === undefined || file.syntax === 'proto2', `unsupported syntax "${file.syntax}"`);
standard = false;
}
if (fieldDescriptor.type === descriptor_1.FieldDescriptorProto_Type.BYTES || fieldDescriptor.type === descriptor_1.FieldDescriptorProto_Type.STRING) {
runtime_1.assert(!declared, `repeated bytes | string cannot be packed. protoc should have caught this. probably unsupported protoc version.`);
standard = false;
}
return declared !== null && declared !== void 0 ? declared : standard;
}
findEnumSharedPrefix(enumDescriptor, enumLocalName) {
if (enumLocalName === undefined) {
enumLocalName = `${enumDescriptor.name}`;
}
// create possible prefix from local enum name
// for example, "MyEnum" => "MY_ENUM_"
let enumPrefix = enumLocalName;
enumPrefix = enumPrefix.replace(/[A-Z]/g, letter => "_" + letter.toLowerCase());
enumPrefix = (enumPrefix[0] === "_") ? enumPrefix.substring(1) : enumPrefix;
enumPrefix = enumPrefix.toUpperCase();
enumPrefix += '_';
// do all members share the prefix?
let names = enumDescriptor.value.map(enumValue => `${enumValue.name}`);
let allNamesSharePrefix = names.every(name => name.startsWith(enumPrefix));
// are the names with stripped prefix still valid?
// (start with uppercase letter, at least 2 chars long)
let strippedNames = names.map(name => name.substring(enumPrefix.length));
let strippedNamesAreValid = strippedNames.every(name => name.length > 0 && /^[A-Z].+/.test(name));
return (allNamesSharePrefix && strippedNamesAreValid) ? enumPrefix : undefined;
}
isFileUsed(file, inFiles) {
let used = false;
this.tree.visitTypes(file, typeDescriptor => {
if (used)
return;
if (this.isTypeUsed(typeDescriptor, inFiles)) {
used = true;
}
});
return used;
}
isTypeUsed(type, inFiles) {
const needle = this.nameLookup.makeTypeName(type);
let used = false;
for (let fd of inFiles) {
this.tree.visitTypes(fd, typeDescriptor => {
if (used)
return;
if (descriptor_1.DescriptorProto.is(typeDescriptor)) {
const usedInField = typeDescriptor.field.some(fd => fd.typeName !== undefined && this.nameLookup.normalizeTypeName(fd.typeName) === needle);
if (usedInField) {
used = true;
}
}
else if (descriptor_1.ServiceDescriptorProto.is(typeDescriptor)) {
const usedInMethodInput = typeDescriptor.method.some(md => md.inputType !== undefined && this.nameLookup.normalizeTypeName(md.inputType) === needle);
const usedInMethodOutput = typeDescriptor.method.some(md => md.outputType !== undefined && this.nameLookup.normalizeTypeName(md.outputType) === needle);
if (usedInMethodInput || usedInMethodOutput) {
used = true;
}
}
});
}
return used;
}
}
exports.DescriptorInfo = DescriptorInfo;
@@ -0,0 +1,154 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DescriptorRegistry = void 0;
const descriptor_1 = require("./google/protobuf/descriptor");
const plugin_1 = require("./google/protobuf/compiler/plugin");
const descriptor_info_1 = require("./descriptor-info");
const descriptor_tree_1 = require("./descriptor-tree");
const source_code_info_1 = require("./source-code-info");
const string_format_1 = require("./string-format");
const type_names_1 = require("./type-names");
class DescriptorRegistry {
constructor(tree, typeNames, sourceCode, stringFormat, descriptorInfo) {
this.tree = tree;
this.typeNames = typeNames;
this.sourceCode = sourceCode;
this.stringFormat = stringFormat;
this.descriptorInfo = descriptorInfo;
}
static createFrom(requestOrFile) {
const files = plugin_1.CodeGeneratorRequest.is(requestOrFile)
? requestOrFile.protoFile
: [requestOrFile], tree = descriptor_tree_1.DescriptorTree.from(...files), nameLookup = type_names_1.TypeNameLookup.from(tree), sourceCodeLookup = new source_code_info_1.SourceCodeInfoLookup(d => tree.parentOf(d)), descriptorInfo = new descriptor_info_1.DescriptorInfo(tree, nameLookup), stringFormat = new string_format_1.StringFormat(nameLookup, tree, sourceCodeLookup, descriptorInfo);
return new DescriptorRegistry(tree, nameLookup, sourceCodeLookup, stringFormat, descriptorInfo);
}
// ITypeNameLookup
normalizeTypeName(typeName) {
return this.typeNames.normalizeTypeName(typeName);
}
resolveTypeName(typeName) {
return this.typeNames.resolveTypeName(typeName);
}
peekTypeName(typeName) {
return this.typeNames.peekTypeName(typeName);
}
makeTypeName(descriptor) {
return this.typeNames.makeTypeName(descriptor);
}
// IDescriptorTree
ancestorsOf(descriptor) {
return this.tree.ancestorsOf(descriptor);
}
fileOf(descriptor) {
return this.tree.fileOf(descriptor);
}
allFiles() {
return this.tree.allFiles();
}
parentOf(descriptorOrOptions) {
return this.tree.parentOf(descriptorOrOptions);
}
visit(a, b) {
this.tree.visit(a, b);
}
visitTypes(a, b) {
this.tree.visitTypes(a, b);
}
// ISourceCodeInfoLookup
sourceCodeCursor(descriptor) {
return this.sourceCode.sourceCodeCursor(descriptor);
}
sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber) {
if (descriptor_1.FileDescriptorProto.is(descriptorOrFile) && fileDescriptorFieldNumber !== undefined) {
return this.sourceCode.sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber);
}
return this.sourceCode.sourceCodeComments(descriptorOrFile);
}
// IStringFormat
formatFieldDeclaration(descriptor) {
return this.stringFormat.formatFieldDeclaration(descriptor);
}
formatQualifiedName(descriptor, includeFileInfo = false) {
return this.stringFormat.formatQualifiedName(descriptor, includeFileInfo);
}
formatName(descriptor) {
return this.stringFormat.formatName(descriptor);
}
formatEnumValueDeclaration(descriptor) {
return this.stringFormat.formatEnumValueDeclaration(descriptor);
}
formatRpcDeclaration(descriptor) {
return this.stringFormat.formatRpcDeclaration(descriptor);
}
// IDescriptorInfo
isExtension(descriptor) {
return this.descriptorInfo.isExtension(descriptor);
}
extensionsFor(descriptorOrTypeName) {
return this.descriptorInfo.extensionsFor(descriptorOrTypeName);
}
getExtensionName(descriptor) {
return this.descriptorInfo.getExtensionName(descriptor);
}
getFieldCustomJsonName(descriptor) {
return this.descriptorInfo.getFieldCustomJsonName(descriptor);
}
isEnumField(fieldDescriptor) {
return this.descriptorInfo.isEnumField(fieldDescriptor);
}
getEnumFieldEnum(fieldDescriptor) {
return this.descriptorInfo.getEnumFieldEnum(fieldDescriptor);
}
isMessageField(fieldDescriptor) {
return this.descriptorInfo.isMessageField(fieldDescriptor);
}
isGroupField(fieldDescriptor) {
return this.descriptorInfo.isGroupField(fieldDescriptor);
}
getMessageFieldMessage(fieldDescriptor) {
return this.descriptorInfo.getMessageFieldMessage(fieldDescriptor);
}
isScalarField(fieldDescriptor) {
return this.descriptorInfo.isScalarField(fieldDescriptor);
}
getScalarFieldType(fieldDescriptor) {
return this.descriptorInfo.getScalarFieldType(fieldDescriptor);
}
isMapField(fieldDescriptor) {
return this.descriptorInfo.isMapField(fieldDescriptor);
}
getMapKeyType(fieldDescriptor) {
return this.descriptorInfo.getMapKeyType(fieldDescriptor);
}
getMapValueType(fieldDescriptor) {
return this.descriptorInfo.getMapValueType(fieldDescriptor);
}
isExplicitlyDeclaredDeprecated(descriptor) {
return this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor);
}
isSyntheticElement(descriptor) {
return this.descriptorInfo.isSyntheticElement(descriptor);
}
findEnumSharedPrefix(descriptor, enumLocalName) {
return this.descriptorInfo.findEnumSharedPrefix(descriptor, enumLocalName);
}
isUserDeclaredOneof(descriptor) {
return this.descriptorInfo.isUserDeclaredOneof(descriptor);
}
isUserDeclaredOptional(descriptor) {
return this.descriptorInfo.isUserDeclaredOptional(descriptor);
}
isUserDeclaredRepeated(descriptor) {
return this.descriptorInfo.isUserDeclaredRepeated(descriptor);
}
shouldBePackedRepeated(descriptor) {
return this.descriptorInfo.shouldBePackedRepeated(descriptor);
}
isFileUsed(file, inFiles) {
return this.descriptorInfo.isFileUsed(file, inFiles);
}
isTypeUsed(type, inFiles) {
return this.descriptorInfo.isTypeUsed(type, inFiles);
}
}
exports.DescriptorRegistry = DescriptorRegistry;
@@ -0,0 +1,180 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitDescriptorTree = exports.DescriptorTree = void 0;
const descriptor_1 = require("./google/protobuf/descriptor");
const descriptor_info_1 = require("./descriptor-info");
const runtime_1 = require("@protobuf-ts/runtime");
class DescriptorTree {
constructor(descriptors, options) {
const descriptorMap = new Map();
const optionMap = new Map();
const files = [];
for (const [descriptor, info] of descriptors) {
// infos
runtime_1.assert(!descriptorMap.has(descriptor));
descriptorMap.set(descriptor, info);
// files
if (descriptor_1.FileDescriptorProto.is(descriptor)) {
files.push(descriptor);
}
}
for (const [option, descriptor] of options) {
optionMap.set(option, descriptor);
}
this._files = files;
this._descriptors = descriptorMap;
this._options = optionMap;
}
/**
* Create the tree from a list of root files.
*/
static from(...files) {
const descriptors = [];
const options = [];
for (const file of files) {
visitDescriptorTree(file, (descriptor, ancestors) => {
descriptors.push([descriptor, { ancestors, file, parent: ancestors[ancestors.length - 1] }]);
if (descriptor.options) {
options.push([descriptor.options, descriptor]);
}
});
}
return new DescriptorTree(descriptors, options);
}
ancestorsOf(descriptor) {
const v = this._descriptors.get(descriptor);
runtime_1.assert(v !== undefined);
return v.ancestors.concat();
}
fileOf(descriptor) {
const v = this._descriptors.get(descriptor);
runtime_1.assert(v !== undefined);
return v.file;
}
allFiles() {
return this._files;
}
parentOf(descriptorOrOptions) {
const optionParent = this._options.get(descriptorOrOptions);
if (optionParent) {
return optionParent;
}
const descriptorEntry = this._descriptors.get(descriptorOrOptions);
if (descriptorEntry) {
return descriptorEntry.parent;
}
runtime_1.assert(descriptor_1.FileDescriptorProto.is(descriptorOrOptions));
return undefined;
}
visit(a, b) {
if (b === undefined) {
for (const file of this._files) {
visitDescriptorTree(file, a);
}
}
else {
const startingFrom = a;
visitDescriptorTree(startingFrom, descriptor => {
if (descriptor === a) {
return; // visitDescriptorTree invokes on starting element. ignore.
}
b(descriptor);
});
}
}
visitTypes(a, b) {
if (b === undefined) {
for (const file of this._files) {
visitDescriptorTree(file, descriptor => {
if (descriptor_info_1.isAnyTypeDescriptorProto(descriptor)) {
a(descriptor);
}
});
}
}
else {
visitDescriptorTree(a, descriptor => {
if (descriptor === a) {
return; // visitDescriptorTree invokes on starting element. ignore.
}
if (descriptor_info_1.isAnyTypeDescriptorProto(descriptor)) {
b(descriptor);
}
});
}
}
}
exports.DescriptorTree = DescriptorTree;
/**
* Visit all logical children of the given descriptor proto.
*
* The "visitor" function is called for each element,
* including the input. It receives two arguments:
* 1) the current descriptor proto
* 2) the ancestors of the current descriptor proto (an array of descriptors)
*/
function visitDescriptorTree(input, visitor) {
visitWithCarry(input, [], visitor);
}
exports.visitDescriptorTree = visitDescriptorTree;
function visitWithCarry(input, carry, visitor) {
visitor(input, carry);
carry = carry.concat(input);
// noinspection SuspiciousTypeOfGuard
if (descriptor_1.EnumDescriptorProto.is(input)) {
for (const val of input.value) {
visitWithCarry(val, carry, visitor);
}
}
else if (descriptor_1.DescriptorProto.is(input)) {
for (const oneof of input.oneofDecl) {
visitWithCarry(oneof, carry, visitor);
}
for (const field of input.field) {
visitWithCarry(field, carry, visitor);
}
for (const message of input.nestedType) {
visitWithCarry(message, carry, visitor);
}
for (const enu of input.enumType) {
visitWithCarry(enu, carry, visitor);
}
for (const extensionField of input.extension) {
visitWithCarry(extensionField, carry, visitor);
}
}
else if (descriptor_1.FileDescriptorProto.is(input)) {
for (const message of input.messageType) {
visitWithCarry(message, carry, visitor);
}
for (const enu of input.enumType) {
visitWithCarry(enu, carry, visitor);
}
for (const service of input.service) {
visitWithCarry(service, carry, visitor);
}
for (const extensionField of input.extension) {
visitWithCarry(extensionField, carry, visitor);
}
}
else if (descriptor_1.ServiceDescriptorProto.is(input)) {
for (const method of input.method) {
visitWithCarry(method, carry, visitor);
}
}
else if (descriptor_1.EnumValueDescriptorProto.is(input)) {
//
}
else if (descriptor_1.FieldDescriptorProto.is(input)) {
//
}
else if (descriptor_1.MethodDescriptorProto.is(input)) {
//
}
else if (descriptor_1.OneofDescriptorProto.is(input)) {
//
}
else {
runtime_1.assertNever(input);
}
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGeneratorResponse_File = exports.CodeGeneratorResponse = exports.CodeGeneratorRequest = exports.Version = exports.CodeGeneratorResponse_Feature = void 0;
// @generated by protobuf-ts 1.0.0-alpha.35 with parameters force_optimize_code_size,long_type_string
// @generated from protobuf file "google/protobuf/compiler/plugin.proto" (package "google.protobuf.compiler", syntax proto2)
// tslint:disable
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Author: [email protected] (Kenton Varda)
//
// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
// change.
//
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "protoc-gen-$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.
//
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
const descriptor_1 = require("../descriptor");
/**
* Sync with code_generator.h.
*
* @generated from protobuf enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
var CodeGeneratorResponse_Feature;
(function (CodeGeneratorResponse_Feature) {
/**
* @generated from protobuf enum value: FEATURE_NONE = 0;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["NONE"] = 0] = "NONE";
/**
* @generated from protobuf enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["PROTO3_OPTIONAL"] = 1] = "PROTO3_OPTIONAL";
})(CodeGeneratorResponse_Feature = exports.CodeGeneratorResponse_Feature || (exports.CodeGeneratorResponse_Feature = {}));
/**
* Type for protobuf message google.protobuf.compiler.Version
*/
class Version$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.compiler.Version", [
{ no: 1, name: "major", kind: "scalar", opt: true, T: runtime_2.ScalarType.INT32 },
{ no: 2, name: "minor", kind: "scalar", opt: true, T: runtime_2.ScalarType.INT32 },
{ no: 3, name: "patch", kind: "scalar", opt: true, T: runtime_2.ScalarType.INT32 },
{ no: 4, name: "suffix", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING }
]);
}
}
exports.Version = new Version$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorRequest
*/
class CodeGeneratorRequest$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorRequest", [
{ no: 1, name: "file_to_generate", kind: "scalar", repeat: runtime_1.RepeatType.UNPACKED, T: runtime_2.ScalarType.STRING },
{ no: 2, name: "parameter", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING },
{ no: 15, name: "proto_file", kind: "message", repeat: runtime_1.RepeatType.UNPACKED, T: () => descriptor_1.FileDescriptorProto },
{ no: 3, name: "compiler_version", kind: "message", T: () => exports.Version }
]);
}
}
exports.CodeGeneratorRequest = new CodeGeneratorRequest$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse
*/
class CodeGeneratorResponse$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorResponse", [
{ no: 1, name: "error", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING },
{ no: 2, name: "supported_features", kind: "scalar", opt: true, T: runtime_2.ScalarType.UINT64 },
{ no: 15, name: "file", kind: "message", repeat: runtime_1.RepeatType.UNPACKED, T: () => exports.CodeGeneratorResponse_File }
]);
}
}
exports.CodeGeneratorResponse = new CodeGeneratorResponse$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse.File
*/
class CodeGeneratorResponse_File$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorResponse.File", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING },
{ no: 2, name: "insertion_point", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING },
{ no: 15, name: "content", kind: "scalar", opt: true, T: runtime_2.ScalarType.STRING }
]);
}
}
exports.CodeGeneratorResponse_File = new CodeGeneratorResponse_File$Type();
@@ -0,0 +1,674 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneratedCodeInfo_Annotation = exports.GeneratedCodeInfo = exports.SourceCodeInfo_Location = exports.SourceCodeInfo = exports.UninterpretedOption_NamePart = exports.UninterpretedOption = exports.MethodOptions = exports.ServiceOptions = exports.EnumValueOptions = exports.EnumOptions = exports.OneofOptions = exports.FieldOptions = exports.MessageOptions = exports.FileOptions = exports.MethodDescriptorProto = exports.ServiceDescriptorProto = exports.EnumValueDescriptorProto = exports.EnumDescriptorProto_EnumReservedRange = exports.EnumDescriptorProto = exports.OneofDescriptorProto = exports.FieldDescriptorProto = exports.ExtensionRangeOptions = exports.DescriptorProto_ReservedRange = exports.DescriptorProto_ExtensionRange = exports.DescriptorProto = exports.FileDescriptorProto = exports.FileDescriptorSet = exports.MethodOptions_IdempotencyLevel = exports.FieldOptions_JSType = exports.FieldOptions_CType = exports.FileOptions_OptimizeMode = exports.FieldDescriptorProto_Label = exports.FieldDescriptorProto_Type = void 0;
// @generated by protobuf-ts 1.0.0-alpha.35 with parameters force_optimize_code_size,long_type_string
// @generated from protobuf file "google/protobuf/descriptor.proto" (package "google.protobuf", syntax proto2)
// tslint:disable
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
//
const runtime_1 = require("@protobuf-ts/runtime");
const runtime_2 = require("@protobuf-ts/runtime");
const runtime_3 = require("@protobuf-ts/runtime");
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Type
*/
var FieldDescriptorProto_Type;
(function (FieldDescriptorProto_Type) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* 0 is reserved for errors.
* Order is weird for historical reasons.
*
* @generated from protobuf enum value: TYPE_DOUBLE = 1;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["DOUBLE"] = 1] = "DOUBLE";
/**
* @generated from protobuf enum value: TYPE_FLOAT = 2;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FLOAT"] = 2] = "FLOAT";
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT64 = 3;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["INT64"] = 3] = "INT64";
/**
* @generated from protobuf enum value: TYPE_UINT64 = 4;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UINT64"] = 4] = "UINT64";
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT32 = 5;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["INT32"] = 5] = "INT32";
/**
* @generated from protobuf enum value: TYPE_FIXED64 = 6;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FIXED64"] = 6] = "FIXED64";
/**
* @generated from protobuf enum value: TYPE_FIXED32 = 7;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FIXED32"] = 7] = "FIXED32";
/**
* @generated from protobuf enum value: TYPE_BOOL = 8;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["BOOL"] = 8] = "BOOL";
/**
* @generated from protobuf enum value: TYPE_STRING = 9;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["STRING"] = 9] = "STRING";
/**
* Tag-delimited aggregate.
* Group type is deprecated and not supported in proto3. However, Proto3
* implementations should still be able to parse the group wire format and
* treat group fields as unknown fields.
*
* @generated from protobuf enum value: TYPE_GROUP = 10;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["GROUP"] = 10] = "GROUP";
/**
* Length-delimited aggregate.
*
* @generated from protobuf enum value: TYPE_MESSAGE = 11;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["MESSAGE"] = 11] = "MESSAGE";
/**
* New in version 2.
*
* @generated from protobuf enum value: TYPE_BYTES = 12;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["BYTES"] = 12] = "BYTES";
/**
* @generated from protobuf enum value: TYPE_UINT32 = 13;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UINT32"] = 13] = "UINT32";
/**
* @generated from protobuf enum value: TYPE_ENUM = 14;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["ENUM"] = 14] = "ENUM";
/**
* @generated from protobuf enum value: TYPE_SFIXED32 = 15;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SFIXED32"] = 15] = "SFIXED32";
/**
* @generated from protobuf enum value: TYPE_SFIXED64 = 16;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SFIXED64"] = 16] = "SFIXED64";
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT32 = 17;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SINT32"] = 17] = "SINT32";
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT64 = 18;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SINT64"] = 18] = "SINT64";
})(FieldDescriptorProto_Type = exports.FieldDescriptorProto_Type || (exports.FieldDescriptorProto_Type = {}));
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Label
*/
var FieldDescriptorProto_Label;
(function (FieldDescriptorProto_Label) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* 0 is reserved for errors
*
* @generated from protobuf enum value: LABEL_OPTIONAL = 1;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["OPTIONAL"] = 1] = "OPTIONAL";
/**
* @generated from protobuf enum value: LABEL_REQUIRED = 2;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["REQUIRED"] = 2] = "REQUIRED";
/**
* @generated from protobuf enum value: LABEL_REPEATED = 3;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["REPEATED"] = 3] = "REPEATED";
})(FieldDescriptorProto_Label = exports.FieldDescriptorProto_Label || (exports.FieldDescriptorProto_Label = {}));
/**
* Generated classes can be optimized for speed or code size.
*
* @generated from protobuf enum google.protobuf.FileOptions.OptimizeMode
*/
var FileOptions_OptimizeMode;
(function (FileOptions_OptimizeMode) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* Generate complete code for parsing, serialization,
*
* @generated from protobuf enum value: SPEED = 1;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["SPEED"] = 1] = "SPEED";
/**
* etc.
*
* Use ReflectionOps to implement these methods.
*
* @generated from protobuf enum value: CODE_SIZE = 2;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE";
/**
* Generate code using MessageLite and the lite runtime.
*
* @generated from protobuf enum value: LITE_RUNTIME = 3;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["LITE_RUNTIME"] = 3] = "LITE_RUNTIME";
})(FileOptions_OptimizeMode = exports.FileOptions_OptimizeMode || (exports.FileOptions_OptimizeMode = {}));
/**
* @generated from protobuf enum google.protobuf.FieldOptions.CType
*/
var FieldOptions_CType;
(function (FieldOptions_CType) {
/**
* Default mode.
*
* @generated from protobuf enum value: STRING = 0;
*/
FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING";
/**
* @generated from protobuf enum value: CORD = 1;
*/
FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD";
/**
* @generated from protobuf enum value: STRING_PIECE = 2;
*/
FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE";
})(FieldOptions_CType = exports.FieldOptions_CType || (exports.FieldOptions_CType = {}));
/**
* @generated from protobuf enum google.protobuf.FieldOptions.JSType
*/
var FieldOptions_JSType;
(function (FieldOptions_JSType) {
/**
* Use the default type.
*
* @generated from protobuf enum value: JS_NORMAL = 0;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_NORMAL"] = 0] = "JS_NORMAL";
/**
* Use JavaScript strings.
*
* @generated from protobuf enum value: JS_STRING = 1;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_STRING"] = 1] = "JS_STRING";
/**
* Use JavaScript numbers.
*
* @generated from protobuf enum value: JS_NUMBER = 2;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_NUMBER"] = 2] = "JS_NUMBER";
})(FieldOptions_JSType = exports.FieldOptions_JSType || (exports.FieldOptions_JSType = {}));
/**
* Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
* or neither? HTTP based RPC implementation may choose GET verb for safe
* methods, and PUT verb for idempotent methods instead of the default POST.
*
* @generated from protobuf enum google.protobuf.MethodOptions.IdempotencyLevel
*/
var MethodOptions_IdempotencyLevel;
(function (MethodOptions_IdempotencyLevel) {
/**
* @generated from protobuf enum value: IDEMPOTENCY_UNKNOWN = 0;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = 0] = "IDEMPOTENCY_UNKNOWN";
/**
* implies idempotent
*
* @generated from protobuf enum value: NO_SIDE_EFFECTS = 1;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["NO_SIDE_EFFECTS"] = 1] = "NO_SIDE_EFFECTS";
/**
* idempotent, but may have side effects
*
* @generated from protobuf enum value: IDEMPOTENT = 2;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENT"] = 2] = "IDEMPOTENT";
})(MethodOptions_IdempotencyLevel = exports.MethodOptions_IdempotencyLevel || (exports.MethodOptions_IdempotencyLevel = {}));
/**
* Type for protobuf message google.protobuf.FileDescriptorSet
*/
class FileDescriptorSet$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.FileDescriptorSet", [
{ no: 1, name: "file", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.FileDescriptorProto }
]);
}
}
exports.FileDescriptorSet = new FileDescriptorSet$Type();
/**
* Type for protobuf message google.protobuf.FileDescriptorProto
*/
class FileDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.FileDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "package", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 3, name: "dependency", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.STRING },
{ no: 10, name: "public_dependency", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.INT32 },
{ no: 11, name: "weak_dependency", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.INT32 },
{ no: 4, name: "message_type", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.DescriptorProto },
{ no: 5, name: "enum_type", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.EnumDescriptorProto },
{ no: 6, name: "service", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.ServiceDescriptorProto },
{ no: 7, name: "extension", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.FieldDescriptorProto },
{ no: 8, name: "options", kind: "message", T: () => exports.FileOptions },
{ no: 9, name: "source_code_info", kind: "message", T: () => exports.SourceCodeInfo },
{ no: 12, name: "syntax", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING }
]);
}
}
exports.FileDescriptorProto = new FileDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto
*/
class DescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.DescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "field", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.FieldDescriptorProto },
{ no: 6, name: "extension", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.FieldDescriptorProto },
{ no: 3, name: "nested_type", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.DescriptorProto },
{ no: 4, name: "enum_type", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.EnumDescriptorProto },
{ no: 5, name: "extension_range", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.DescriptorProto_ExtensionRange },
{ no: 8, name: "oneof_decl", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.OneofDescriptorProto },
{ no: 7, name: "options", kind: "message", T: () => exports.MessageOptions },
{ no: 9, name: "reserved_range", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.DescriptorProto_ReservedRange },
{ no: 10, name: "reserved_name", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.STRING }
]);
}
}
exports.DescriptorProto = new DescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto.ExtensionRange
*/
class DescriptorProto_ExtensionRange$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.DescriptorProto.ExtensionRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 3, name: "options", kind: "message", T: () => exports.ExtensionRangeOptions }
]);
}
}
exports.DescriptorProto_ExtensionRange = new DescriptorProto_ExtensionRange$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto.ReservedRange
*/
class DescriptorProto_ReservedRange$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.DescriptorProto.ReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 }
]);
}
}
exports.DescriptorProto_ReservedRange = new DescriptorProto_ReservedRange$Type();
/**
* Type for protobuf message google.protobuf.ExtensionRangeOptions
*/
class ExtensionRangeOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.ExtensionRangeOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.ExtensionRangeOptions = new ExtensionRangeOptions$Type();
/**
* Type for protobuf message google.protobuf.FieldDescriptorProto
*/
class FieldDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.FieldDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 3, name: "number", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 4, name: "label", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Label", FieldDescriptorProto_Label, "LABEL_"] },
{ no: 5, name: "type", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Type", FieldDescriptorProto_Type, "TYPE_"] },
{ no: 6, name: "type_name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "extendee", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 7, name: "default_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 9, name: "oneof_index", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 10, name: "json_name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 8, name: "options", kind: "message", T: () => exports.FieldOptions },
{ no: 17, name: "proto3_optional", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL }
]);
}
}
exports.FieldDescriptorProto = new FieldDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.OneofDescriptorProto
*/
class OneofDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.OneofDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "options", kind: "message", T: () => exports.OneofOptions }
]);
}
}
exports.OneofDescriptorProto = new OneofDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.EnumDescriptorProto
*/
class EnumDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.EnumDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "value", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.EnumValueDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => exports.EnumOptions },
{ no: 4, name: "reserved_range", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.EnumDescriptorProto_EnumReservedRange },
{ no: 5, name: "reserved_name", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.STRING }
]);
}
}
exports.EnumDescriptorProto = new EnumDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.EnumDescriptorProto.EnumReservedRange
*/
class EnumDescriptorProto_EnumReservedRange$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.EnumDescriptorProto.EnumReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 }
]);
}
}
exports.EnumDescriptorProto_EnumReservedRange = new EnumDescriptorProto_EnumReservedRange$Type();
/**
* Type for protobuf message google.protobuf.EnumValueDescriptorProto
*/
class EnumValueDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.EnumValueDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "number", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 3, name: "options", kind: "message", T: () => exports.EnumValueOptions }
]);
}
}
exports.EnumValueDescriptorProto = new EnumValueDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.ServiceDescriptorProto
*/
class ServiceDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.ServiceDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "method", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.MethodDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => exports.ServiceOptions }
]);
}
}
exports.ServiceDescriptorProto = new ServiceDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.MethodDescriptorProto
*/
class MethodDescriptorProto$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.MethodDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 2, name: "input_type", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 3, name: "output_type", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 4, name: "options", kind: "message", T: () => exports.MethodOptions },
{ no: 5, name: "client_streaming", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 6, name: "server_streaming", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL }
]);
}
}
exports.MethodDescriptorProto = new MethodDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.FileOptions
*/
class FileOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.FileOptions", [
{ no: 1, name: "java_package", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 8, name: "java_outer_classname", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 10, name: "java_multiple_files", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 20, name: "java_generate_equals_and_hash", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 27, name: "java_string_check_utf8", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 9, name: "optimize_for", kind: "enum", opt: true, T: () => ["google.protobuf.FileOptions.OptimizeMode", FileOptions_OptimizeMode] },
{ no: 11, name: "go_package", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 16, name: "cc_generic_services", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 17, name: "java_generic_services", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 18, name: "py_generic_services", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 42, name: "php_generic_services", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 23, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 31, name: "cc_enable_arenas", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 36, name: "objc_class_prefix", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 37, name: "csharp_namespace", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 39, name: "swift_prefix", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 40, name: "php_class_prefix", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 41, name: "php_namespace", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 44, name: "php_metadata_namespace", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 45, name: "ruby_package", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.FileOptions = new FileOptions$Type();
/**
* Type for protobuf message google.protobuf.MessageOptions
*/
class MessageOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.MessageOptions", [
{ no: 1, name: "message_set_wire_format", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 2, name: "no_standard_descriptor_accessor", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 7, name: "map_entry", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.MessageOptions = new MessageOptions$Type();
/**
* Type for protobuf message google.protobuf.FieldOptions
*/
class FieldOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.FieldOptions", [
{ no: 1, name: "ctype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.CType", FieldOptions_CType] },
{ no: 2, name: "packed", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 6, name: "jstype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.JSType", FieldOptions_JSType] },
{ no: 5, name: "lazy", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 10, name: "weak", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.FieldOptions = new FieldOptions$Type();
/**
* Type for protobuf message google.protobuf.OneofOptions
*/
class OneofOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.OneofOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.OneofOptions = new OneofOptions$Type();
/**
* Type for protobuf message google.protobuf.EnumOptions
*/
class EnumOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.EnumOptions", [
{ no: 2, name: "allow_alias", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.EnumOptions = new EnumOptions$Type();
/**
* Type for protobuf message google.protobuf.EnumValueOptions
*/
class EnumValueOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.EnumValueOptions", [
{ no: 1, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.EnumValueOptions = new EnumValueOptions$Type();
/**
* Type for protobuf message google.protobuf.ServiceOptions
*/
class ServiceOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.ServiceOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.ServiceOptions = new ServiceOptions$Type();
/**
* Type for protobuf message google.protobuf.MethodOptions
*/
class MethodOptions$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.MethodOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: runtime_1.ScalarType.BOOL },
{ no: 34, name: "idempotency_level", kind: "enum", opt: true, T: () => ["google.protobuf.MethodOptions.IdempotencyLevel", MethodOptions_IdempotencyLevel] },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption }
]);
}
}
exports.MethodOptions = new MethodOptions$Type();
/**
* Type for protobuf message google.protobuf.UninterpretedOption
*/
class UninterpretedOption$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.UninterpretedOption", [
{ no: 2, name: "name", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.UninterpretedOption_NamePart },
{ no: 3, name: "identifier_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 4, name: "positive_int_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.UINT64 },
{ no: 5, name: "negative_int_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT64 },
{ no: 6, name: "double_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.DOUBLE },
{ no: 7, name: "string_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.BYTES },
{ no: 8, name: "aggregate_value", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING }
]);
}
}
exports.UninterpretedOption = new UninterpretedOption$Type();
/**
* Type for protobuf message google.protobuf.UninterpretedOption.NamePart
*/
class UninterpretedOption_NamePart$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.UninterpretedOption.NamePart", [
{ no: 1, name: "name_part", kind: "scalar", T: runtime_1.ScalarType.STRING },
{ no: 2, name: "is_extension", kind: "scalar", T: runtime_1.ScalarType.BOOL }
]);
}
}
exports.UninterpretedOption_NamePart = new UninterpretedOption_NamePart$Type();
/**
* Type for protobuf message google.protobuf.SourceCodeInfo
*/
class SourceCodeInfo$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.SourceCodeInfo", [
{ no: 1, name: "location", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.SourceCodeInfo_Location }
]);
}
}
exports.SourceCodeInfo = new SourceCodeInfo$Type();
/**
* Type for protobuf message google.protobuf.SourceCodeInfo.Location
*/
class SourceCodeInfo_Location$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.SourceCodeInfo.Location", [
{ no: 1, name: "path", kind: "scalar", repeat: runtime_2.RepeatType.PACKED, T: runtime_1.ScalarType.INT32 },
{ no: 2, name: "span", kind: "scalar", repeat: runtime_2.RepeatType.PACKED, T: runtime_1.ScalarType.INT32 },
{ no: 3, name: "leading_comments", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 4, name: "trailing_comments", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 6, name: "leading_detached_comments", kind: "scalar", repeat: runtime_2.RepeatType.UNPACKED, T: runtime_1.ScalarType.STRING }
]);
}
}
exports.SourceCodeInfo_Location = new SourceCodeInfo_Location$Type();
/**
* Type for protobuf message google.protobuf.GeneratedCodeInfo
*/
class GeneratedCodeInfo$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.GeneratedCodeInfo", [
{ no: 1, name: "annotation", kind: "message", repeat: runtime_2.RepeatType.UNPACKED, T: () => exports.GeneratedCodeInfo_Annotation }
]);
}
}
exports.GeneratedCodeInfo = new GeneratedCodeInfo$Type();
/**
* Type for protobuf message google.protobuf.GeneratedCodeInfo.Annotation
*/
class GeneratedCodeInfo_Annotation$Type extends runtime_3.MessageType {
constructor() {
super("google.protobuf.GeneratedCodeInfo.Annotation", [
{ no: 1, name: "path", kind: "scalar", repeat: runtime_2.RepeatType.PACKED, T: runtime_1.ScalarType.INT32 },
{ no: 2, name: "source_file", kind: "scalar", opt: true, T: runtime_1.ScalarType.STRING },
{ no: 3, name: "begin", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 },
{ no: 4, name: "end", kind: "scalar", opt: true, T: runtime_1.ScalarType.INT32 }
]);
}
}
exports.GeneratedCodeInfo_Annotation = new GeneratedCodeInfo_Annotation$Type();
+31
View File
@@ -0,0 +1,31 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./descriptor-info"), exports);
__exportStar(require("./descriptor-registry"), exports);
__exportStar(require("./descriptor-tree"), exports);
__exportStar(require("./generated-file"), exports);
__exportStar(require("./plugin-base"), exports);
__exportStar(require("./source-code-info"), exports);
__exportStar(require("./string-format"), exports);
__exportStar(require("./symbol-table"), exports);
__exportStar(require("./type-names"), exports);
__exportStar(require("./google/protobuf/descriptor"), exports);
__exportStar(require("./google/protobuf/compiler/plugin"), exports);
__exportStar(require("./typescript-compile"), exports);
__exportStar(require("./typescript-comments"), exports);
__exportStar(require("./typescript-import-manager"), exports);
__exportStar(require("./typescript-method-from-text"), exports);
__exportStar(require("./typescript-literal-from-value"), exports);
__exportStar(require("./typescript-enum-builder"), exports);
__exportStar(require("./typescript-file"), exports);
__exportStar(require("./typescript-imports"), exports);
@@ -0,0 +1,203 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PluginBase = void 0;
const plugin_1 = require("./google/protobuf/compiler/plugin");
const util_1 = require("util");
const runtime_1 = require("@protobuf-ts/runtime");
/**
* Base class for a protobuf plugin.
*
* Implement the abstract `generate()` method to create a plugin.
* The method takes a `CodeGeneratorRequest` and returns an
* array of `GeneratedFile` or a promise thereof.
*
*
* Usage:
*
* #!/usr/bin/env node
* const {MyPlugin} = require( ... );
* new MyPlugin.run().catch(_ => {
* process.stderr.write('failed to run plugin');
* process.exit(1);
* });
*
* Reads a `CodeGeneratorRequest` created by `protoc` from stdin,
* passes it to the plugin-function and writes a
* `CodeGeneratorResponse` to stdout.
*
*
* Options:
*
* Use the `parseOptions()` method the parse the parameter
* of a `CodeGeneratorRequest` to a map of flags. Options are
* validated and usage is generated on error.
*
*
* Error handling:
*
* `generate()` may raise an error, reject it's promise or
* return an `GeneratedFile` with an attached error.
*
* Throwing `new Error("hello")` will result in the output:
*
* $ protoc --xx_out=/tmp -I protos protos/*
* --xx_out: Error: hello
* at /path/to/your-plugin.js:69
* ...
*
*
*/
class PluginBase {
run() {
return __awaiter(this, void 0, void 0, function* () {
try {
let response, bytes = yield this.readBytes(process.stdin), request = plugin_1.CodeGeneratorRequest.fromBinary(bytes);
try {
const files = yield this.generate(request);
response = this.createResponse(files);
}
catch (error) {
response = plugin_1.CodeGeneratorResponse.create({
error: this.errorToString(error)
});
}
this.setBlockingStdout();
process.stdout.write(plugin_1.CodeGeneratorResponse.toBinary(response));
}
catch (error) {
process.stderr.write('Plugin failed to read CodeGeneratorRequest from stdin or write CodeGeneratorResponse to stdout.\n');
process.stderr.write(this.errorToString(error));
process.stderr.write('\n');
process.exit(1);
}
});
}
getSupportedFeatures() {
return [];
}
parseOptions(spec, parameter) {
var _a, _b, _c, _d;
this.validateOptionsSpec(spec);
let given = parameter ? parameter.split(',') : [];
let known = Object.keys(spec);
let excess = given.filter(i => !known.includes(i));
if (excess.length > 0) {
this.throwOptionError(spec, `Option "${excess.join('", "')}" not recognized.`);
}
for (let [key, val] of Object.entries(spec)) {
if (given.includes(key)) {
let missing = (_b = (_a = val.requires) === null || _a === void 0 ? void 0 : _a.filter(i => !given.includes(i))) !== null && _b !== void 0 ? _b : [];
if (missing.length > 0) {
this.throwOptionError(spec, `Option "${key}" requires option "${missing.join('", "')}" to be set.`);
}
let excess = (_d = (_c = val.excludes) === null || _c === void 0 ? void 0 : _c.filter(i => given.includes(i))) !== null && _d !== void 0 ? _d : [];
if (excess.length > 0) {
this.throwOptionError(spec, `If option "${key}" is set, option "${excess.join('", "')}" cannot be set.`);
}
}
}
let resolved = {};
for (let key of Object.keys(spec)) {
resolved[key] = given.includes(key);
}
return resolved;
}
throwOptionError(spec, error) {
let text = '';
text += error + '\n';
text += `\n`;
text += `Available options:\n`;
text += `\n`;
for (let [key, val] of Object.entries(spec)) {
text += `- "${key}"\n`;
for (let l of val.description.split('\n')) {
text += ` ${l}\n`;
}
text += `\n`;
}
let err = new Error(text);
err.name = `ParameterError`;
throw err;
}
validateOptionsSpec(spec) {
var _a, _b;
let known = Object.keys(spec);
for (let [key, { excludes, requires }] of Object.entries(spec)) {
let r = (_a = requires === null || requires === void 0 ? void 0 : requires.filter(i => !known.includes(i))) !== null && _a !== void 0 ? _a : [];
if (r.length > 0) {
throw new Error(`Invalid parameter spec for parameter "${key}". "requires" points to unknown parameters: ${r.join(', ')}`);
}
let e = (_b = excludes === null || excludes === void 0 ? void 0 : excludes.filter(i => !known.includes(i))) !== null && _b !== void 0 ? _b : [];
if (e.length > 0) {
throw new Error(`Invalid parameter spec for parameter "${key}". "excludes" points to unknown parameters: ${e.join(', ')}`);
}
}
}
readBytes(stream) {
return new Promise(resolve => {
const chunks = [];
stream.on('data', chunk => chunks.push(chunk));
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
});
}
createResponse(files) {
// we have to respond with an xor of all of our supported features.
// we should be working on a ulong here, but we cannot rely on bigint support.
let feat = 0;
for (let f of this.getSupportedFeatures()) {
feat = feat ^ f;
}
return plugin_1.CodeGeneratorResponse.create({
file: files
.map(f => plugin_1.CodeGeneratorResponse_File.create({
name: f.getFilename(),
content: f.getContent()
}))
.filter(f => f.content && f.content.length > 0),
supportedFeatures: runtime_1.PbULong.from(feat).toString()
});
}
errorToString(error) {
var _a;
if (error && typeof error.name == 'string' && error.name == 'ParameterError') {
return error.name + '\n\n' + error.message;
}
if (error && typeof error.name == 'string' && error.name == 'PluginMessageError') {
return error.message;
}
if (util_1.types.isNativeError(error)) {
return (_a = error.stack) !== null && _a !== void 0 ? _a : error.toString();
}
let text;
try {
text = error.toString();
}
catch (e) {
text = 'unknown error';
}
return text;
}
setBlockingStdout() {
// Fixes https://github.com/timostamm/protobuf-ts/issues/134
// Node is buffering chunks to stdout, meaning that for big generated
// files the CodeGeneratorResponse will not reach protoc completely.
// To fix this, we set stdout to block using the internal private
// method setBlocking(true)
const stdoutHandle = process.stdout._handle;
if (stdoutHandle) {
stdoutHandle.setBlocking(true);
}
}
}
exports.PluginBase = PluginBase;
@@ -0,0 +1,249 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileDescriptorProtoFields = exports.makeSourceCodePathComponent = exports.makeSourceCodePath = exports.filterSourceCodeLocations = exports.sourceCodeLocationToComment = exports.sourceCodeLocationToCursor = exports.SourceCodeInfoLookup = void 0;
const descriptor_1 = require("./google/protobuf/descriptor");
const runtime_1 = require("@protobuf-ts/runtime");
class SourceCodeInfoLookup {
constructor(parentResolver) {
this._parentResolver = parentResolver;
}
sourceCodeCursor(descriptor) {
var _a, _b;
const path = makeSourceCodePath(x => this._parentResolver(x), descriptor);
runtime_1.assert(path !== undefined, `Cannot create source code path`);
const all = (_b = (_a = this._findFile(descriptor).sourceCodeInfo) === null || _a === void 0 ? void 0 : _a.location) !== null && _b !== void 0 ? _b : [];
const hit = filterSourceCodeLocations(all, path);
return sourceCodeLocationToCursor(hit);
}
sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber) {
var _a, _b;
const path = makeSourceCodePath(x => this._parentResolver(x), descriptorOrFile);
runtime_1.assert(path !== undefined, `Cannot create source code path`);
if (fileDescriptorFieldNumber !== undefined) {
path.push(fileDescriptorFieldNumber);
}
const all = (_b = (_a = this._findFile(descriptorOrFile).sourceCodeInfo) === null || _a === void 0 ? void 0 : _a.location) !== null && _b !== void 0 ? _b : [];
const hit = filterSourceCodeLocations(all, path);
return sourceCodeLocationToComment(hit);
}
_findFile(d) {
let c = d;
while (c) {
if (descriptor_1.FileDescriptorProto.is(c)) {
return c;
}
c = this._parentResolver(c);
}
runtime_1.assert(false);
}
}
exports.SourceCodeInfoLookup = SourceCodeInfoLookup;
/**
* Return cursor position of the given source code location
* as line number and column, both starting at 1.
*
* If more than one location is given, only the first one
* is evaluated, the others are discarded.
*/
function sourceCodeLocationToCursor(locations) {
if (locations.length === 0) {
return emptyCursor;
}
const span = locations[0].span;
if (span === undefined || span.length < 3 || span.length > 4) {
return emptyCursor;
}
return [
span[0] + 1,
span[1] + 1
];
}
exports.sourceCodeLocationToCursor = sourceCodeLocationToCursor;
const emptyCursor = [undefined, undefined];
/**
* Return the comments for the given source code location.
*
* If more than one location is given, only the first one
* is evaluated, the others are discarded.
*
* If no comments found, empty (not undefined) object
* is returned.
*
* Trailing newlines are removed.
*/
function sourceCodeLocationToComment(locations) {
if (locations.length === 0) {
return emptyComment;
}
const location = locations[0], leadingDetached = location.leadingDetachedComments.map(stripTrailingNewline), leadingComments = location.leadingComments, leading = leadingComments === ''
? undefined
: (leadingComments === undefined
? undefined
: stripTrailingNewline(leadingComments)), trailingComments = location.trailingComments, trailing = trailingComments === ''
? undefined
: (trailingComments === undefined
? undefined
: stripTrailingNewline(trailingComments));
return (leadingDetached.length === 0 && leading === undefined && trailing === undefined)
? emptyComment
: { leadingDetached, leading, trailing };
}
exports.sourceCodeLocationToComment = sourceCodeLocationToComment;
function stripTrailingNewline(block) {
return block.endsWith('\n')
? block.slice(0, -1)
: block;
}
const emptyComment = {
leadingDetached: [],
leading: undefined,
trailing: undefined,
};
/**
* Find the source code locations that match the given path.
*/
function filterSourceCodeLocations(locations, path) {
return locations.filter(l => {
const p = l.path;
if (p.length !== path.length) {
return false;
}
for (let i = 0; i < p.length; i++) {
if (p[i] !== path[i]) {
return false;
}
}
return true;
});
}
exports.filterSourceCodeLocations = filterSourceCodeLocations;
/**
* Create the path to the source code location where the
* given element was declared.
*
* Returns `undefined` if we don't know how to make the path.
*
* For example, the path [4, 0, 2, 3] points to the 4th field
* of the first message of a .proto file:
*
* file
* .messageType // FileDescriptorProto.message_type = 3;
* [0] // first message
* .field // FileDescriptorProto.field = 2;
* [3] // 4th field
*
* See https://github.com/protocolbuffers/protobuf/blob/f1ce8663ac88df54cf212d29ce5123b69203b135/src/google/protobuf/descriptor.proto#L799
*/
function makeSourceCodePath(parentProvider, descriptor) {
const path = [];
let parent = parentProvider(descriptor);
let component;
while (parent) {
component = makeSourceCodePathComponent(parent, descriptor);
if (component === undefined) {
return undefined;
}
path.unshift(...component);
descriptor = parent;
parent = parentProvider(parent);
}
return path;
}
exports.makeSourceCodePath = makeSourceCodePath;
/**
* Make a path from the parent to the immediate child.
*
* Returns `undefined` if we don't know how to make the path.
*/
function makeSourceCodePathComponent(parent, child) {
if (descriptor_1.FileDescriptorProto.is(parent) && descriptor_1.DescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.message_type,
parent.messageType.indexOf(child)
];
}
if (descriptor_1.FileDescriptorProto.is(parent) && descriptor_1.EnumDescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.enum_type,
parent.enumType.indexOf(child)
];
}
if (descriptor_1.FileDescriptorProto.is(parent) && descriptor_1.ServiceDescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.service,
parent.service.indexOf(child)
];
}
if (descriptor_1.DescriptorProto.is(parent) && descriptor_1.EnumDescriptorProto.is(child)) {
return [
DescriptorProtoFields.enum_type,
parent.enumType.indexOf(child)
];
}
if (descriptor_1.DescriptorProto.is(parent) && descriptor_1.DescriptorProto.is(child)) {
return [
DescriptorProtoFields.nested_type,
parent.nestedType.indexOf(child)
];
}
if (descriptor_1.DescriptorProto.is(parent) && descriptor_1.FieldDescriptorProto.is(child)) {
return [
DescriptorProtoFields.field,
parent.field.indexOf(child)
];
}
if (descriptor_1.DescriptorProto.is(parent) && descriptor_1.OneofDescriptorProto.is(child)) {
return [
DescriptorProtoFields.oneof_decl,
parent.oneofDecl.indexOf(child)
];
}
if (descriptor_1.EnumDescriptorProto.is(parent) && descriptor_1.EnumValueDescriptorProto.is(child)) {
return [
EnumDescriptorProtoFields.value,
parent.value.indexOf(child)
];
}
if (descriptor_1.ServiceDescriptorProto.is(parent) && descriptor_1.MethodDescriptorProto.is(child)) {
return [
ServiceDescriptorProtoFields.method,
parent.method.indexOf(child)
];
}
return undefined;
}
exports.makeSourceCodePathComponent = makeSourceCodePathComponent;
var FileDescriptorProtoFields;
(function (FileDescriptorProtoFields) {
FileDescriptorProtoFields[FileDescriptorProtoFields["syntax"] = 12] = "syntax";
FileDescriptorProtoFields[FileDescriptorProtoFields["package"] = 2] = "package";
FileDescriptorProtoFields[FileDescriptorProtoFields["message_type"] = 4] = "message_type";
FileDescriptorProtoFields[FileDescriptorProtoFields["enum_type"] = 5] = "enum_type";
FileDescriptorProtoFields[FileDescriptorProtoFields["service"] = 6] = "service";
})(FileDescriptorProtoFields = exports.FileDescriptorProtoFields || (exports.FileDescriptorProtoFields = {}));
var DescriptorProtoFields;
(function (DescriptorProtoFields) {
DescriptorProtoFields[DescriptorProtoFields["field"] = 2] = "field";
DescriptorProtoFields[DescriptorProtoFields["nested_type"] = 3] = "nested_type";
DescriptorProtoFields[DescriptorProtoFields["enum_type"] = 4] = "enum_type";
DescriptorProtoFields[DescriptorProtoFields["options"] = 7] = "options";
DescriptorProtoFields[DescriptorProtoFields["oneof_decl"] = 8] = "oneof_decl";
})(DescriptorProtoFields || (DescriptorProtoFields = {}));
// enum FieldDescriptorProtoFields {
// name = 1, // optional string name = 1;
// number = 3, // optional int32 number = 3;
// label = 4, // optional Label label = 4;
// type = 5, // optional Type type = 5;
// }
var EnumDescriptorProtoFields;
(function (EnumDescriptorProtoFields) {
// name = 1, // optional string name = 1;
EnumDescriptorProtoFields[EnumDescriptorProtoFields["value"] = 2] = "value";
// options = 3, // optional EnumOptions options = 3;
})(EnumDescriptorProtoFields || (EnumDescriptorProtoFields = {}));
var ServiceDescriptorProtoFields;
(function (ServiceDescriptorProtoFields) {
// name = 1, // optional string name = 1;
ServiceDescriptorProtoFields[ServiceDescriptorProtoFields["method"] = 2] = "method";
// options = 3, // optional ServiceOptions options = 3;
})(ServiceDescriptorProtoFields || (ServiceDescriptorProtoFields = {}));
@@ -0,0 +1,220 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringFormat = void 0;
const descriptor_1 = require("./google/protobuf/descriptor");
const descriptor_info_1 = require("./descriptor-info");
const runtime_1 = require("@protobuf-ts/runtime");
class StringFormat {
constructor(a, b, c, d) {
if (b === undefined) {
this.nameLookup = a;
this.treeLookup = a;
this.sourceCodeLookup = a;
this.descriptorInfo = a;
}
else {
this.nameLookup = a;
this.treeLookup = b;
this.sourceCodeLookup = c;
this.descriptorInfo = d;
}
}
/**
* Returns name of a scalar value type like it would
* appear in a .proto.
*
* For example, `FieldDescriptorProto_Type.UINT32` -> `"uint32"`.
*/
static formatScalarType(type) {
let name = descriptor_1.FieldDescriptorProto_Type[type];
runtime_1.assert(name !== undefined, "unexpected ScalarValueType " + type);
return name.toLowerCase();
}
/**
* Returns type ('message', 'field', etc.) and descriptor name.
*
* Examples:
* message Bar
* field value = 2
* rpc Fetch()
*/
static formatName(descriptor) {
if (descriptor_1.FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
}
else if (descriptor_1.DescriptorProto.is(descriptor)) {
return `message ${descriptor.name}`;
}
else if (descriptor_1.FieldDescriptorProto.is(descriptor)) {
if (descriptor.extendee !== undefined) {
return `extension field ${descriptor.name} = ${descriptor.number}`;
}
return `field ${descriptor.name} = ${descriptor.number}`;
}
else if (descriptor_1.EnumDescriptorProto.is(descriptor)) {
return `enum ${descriptor.name}`;
}
else if (descriptor_1.EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${descriptor.name} = ${descriptor.number}`;
}
else if (descriptor_1.ServiceDescriptorProto.is(descriptor)) {
return `service ${descriptor.name}`;
}
else if (descriptor_1.MethodDescriptorProto.is(descriptor)) {
return `rpc ${descriptor.name}()`;
}
else
// noinspection SuspiciousTypeOfGuard
if (descriptor_1.OneofDescriptorProto.is(descriptor)) {
return `oneof ${descriptor.name}`;
}
runtime_1.assertNever(descriptor);
runtime_1.assert(false);
}
formatQualifiedName(descriptor, includeFileInfo) {
if (descriptor_1.FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
}
const file = includeFileInfo ? ' in ' + getSourceWithLineNo(descriptor, this.treeLookup, this.sourceCodeLookup) : '';
if (descriptor_1.DescriptorProto.is(descriptor)) {
return `message ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (descriptor_1.EnumDescriptorProto.is(descriptor)) {
return `enum ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (descriptor_1.ServiceDescriptorProto.is(descriptor)) {
return `service ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
let parent = this.treeLookup.parentOf(descriptor);
if (descriptor_1.FieldDescriptorProto.is(descriptor) && this.descriptorInfo.isExtension(descriptor)) {
let extensionName = this.descriptorInfo.getExtensionName(descriptor);
runtime_1.assert(descriptor.extendee);
let extendeeTypeName = this.nameLookup.normalizeTypeName(descriptor.extendee);
return `extension ${extendeeTypeName}.(${extensionName})${file}`;
}
runtime_1.assert(descriptor_info_1.isAnyTypeDescriptorProto(parent));
let parentTypeName = this.nameLookup.makeTypeName(parent);
if (descriptor_1.FieldDescriptorProto.is(descriptor)) {
return `field ${parentTypeName}.${descriptor.name}${file}`;
}
if (descriptor_1.EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${parentTypeName}.${descriptor.name}${file}`;
}
if (descriptor_1.MethodDescriptorProto.is(descriptor)) {
return `rpc ${parentTypeName}.${descriptor.name}()${file}`;
}
return `oneof ${parentTypeName}.${descriptor.name}${file}`;
}
formatName(descriptor) {
return StringFormat.formatName(descriptor);
}
formatFieldDeclaration(descriptor) {
var _a, _b, _c, _d, _e;
let text = '';
// repeated ?
if (this.descriptorInfo.isUserDeclaredRepeated(descriptor)) {
text += 'repeated ';
}
// optional ?
if (this.descriptorInfo.isUserDeclaredOptional(descriptor)) {
text += 'optional ';
}
switch (descriptor.type) {
case descriptor_1.FieldDescriptorProto_Type.ENUM:
text += this.nameLookup.makeTypeName(this.descriptorInfo.getEnumFieldEnum(descriptor));
break;
case descriptor_1.FieldDescriptorProto_Type.MESSAGE:
if (this.descriptorInfo.isMapField(descriptor)) {
let mapK = StringFormat.formatScalarType(this.descriptorInfo.getMapKeyType(descriptor));
let mapVType = this.descriptorInfo.getMapValueType(descriptor);
let mapV = typeof mapVType === "number"
? StringFormat.formatScalarType(mapVType)
: this.nameLookup.makeTypeName(mapVType);
text += `map<${mapK}, ${mapV}>`;
}
else {
text += this.nameLookup.makeTypeName(this.descriptorInfo.getMessageFieldMessage(descriptor));
}
break;
case descriptor_1.FieldDescriptorProto_Type.DOUBLE:
case descriptor_1.FieldDescriptorProto_Type.FLOAT:
case descriptor_1.FieldDescriptorProto_Type.INT64:
case descriptor_1.FieldDescriptorProto_Type.UINT64:
case descriptor_1.FieldDescriptorProto_Type.INT32:
case descriptor_1.FieldDescriptorProto_Type.FIXED64:
case descriptor_1.FieldDescriptorProto_Type.FIXED32:
case descriptor_1.FieldDescriptorProto_Type.BOOL:
case descriptor_1.FieldDescriptorProto_Type.STRING:
case descriptor_1.FieldDescriptorProto_Type.BYTES:
case descriptor_1.FieldDescriptorProto_Type.UINT32:
case descriptor_1.FieldDescriptorProto_Type.SFIXED32:
case descriptor_1.FieldDescriptorProto_Type.SFIXED64:
case descriptor_1.FieldDescriptorProto_Type.SINT32:
case descriptor_1.FieldDescriptorProto_Type.SINT64:
text += StringFormat.formatScalarType(descriptor.type);
break;
case descriptor_1.FieldDescriptorProto_Type.GROUP:
text += "group";
break;
case descriptor_1.FieldDescriptorProto_Type.UNSPECIFIED$:
text += "???";
break;
}
// name
text += ' ' + descriptor.name;
// number
text += ' = ' + descriptor.number;
// options
let options = [];
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
options.push('deprecated = true');
}
if (this.descriptorInfo.getFieldCustomJsonName(descriptor)) {
options.push(`json_name = "${this.descriptorInfo.getFieldCustomJsonName(descriptor)}"`);
}
if (((_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.jstype) == descriptor_1.FieldOptions_JSType.JS_STRING) {
options.push(`jstype = JS_STRING`);
}
if (((_b = descriptor.options) === null || _b === void 0 ? void 0 : _b.jstype) == descriptor_1.FieldOptions_JSType.JS_NUMBER) {
options.push(`jstype = JS_NUMBER`);
}
if (((_c = descriptor.options) === null || _c === void 0 ? void 0 : _c.jstype) == descriptor_1.FieldOptions_JSType.JS_NORMAL) {
options.push(`jstype = JS_NORMAL`);
}
if (((_d = descriptor.options) === null || _d === void 0 ? void 0 : _d.packed) === true) {
options.push(`packed = true`);
}
if (((_e = descriptor.options) === null || _e === void 0 ? void 0 : _e.packed) === false) {
options.push(`packed = false`);
}
if (options.length) {
text += ' [' + options.join(', ') + ']';
}
// semicolon
text += ';';
return text;
}
formatEnumValueDeclaration(descriptor) {
let text = `${descriptor.name} = ${descriptor.number}`;
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
text += ' [deprecated = true]';
}
return text + ';';
}
formatRpcDeclaration(descriptor) {
this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor);
let m = descriptor.name, i = descriptor.inputType, is = descriptor.clientStreaming ? 'stream ' : '', o = descriptor.outputType, os = descriptor.serverStreaming ? 'stream ' : '';
if (i.startsWith('.')) {
i = i.substring(1);
}
if (o.startsWith('.')) {
o = o.substring(1);
}
return `${m}(${is}${i}) returns (${os}${o});`;
}
}
exports.StringFormat = StringFormat;
function getSourceWithLineNo(descriptor, treeLookup, sourceCodeLookup) {
let file = treeLookup.fileOf(descriptor), [l] = sourceCodeLookup.sourceCodeCursor(descriptor);
return `${file.name}:${l}`;
}
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SymbolTable = void 0;
const string_format_1 = require("./string-format");
/**
* A table for unique symbols (for any DescriptorProto, EnumDescriptorProto
* or ServiceDescriptorProto) in files (GeneratedFile).
*/
class SymbolTable {
constructor(clashResolver) {
this.entries = [];
this.clashResolveMaxTries = 100;
this.hasNameInFile = (name, file) => this.entries.some(e => e.file === file && e.name === name);
this.clashResolver = clashResolver !== null && clashResolver !== void 0 ? clashResolver : SymbolTable.defaultClashResolver;
}
/**
* Register a symbol in the given file for the given descriptor.
*
* If the name is already taken in the file, an alternative name
* is automatically generated by appending '$' and a running
* number to the requested name. You can change the behaviour by
* providing your own `clashResolver`.
*
* Only one symbol per kind can be registered for a descriptor.
*
* If you want to generate an interface *and* a class for a
* message, use a different `kind` for each.
*
* Returns the actual name registered.
*/
register(requestedName, descriptor, file, kind = 'default') {
// Only one symbol per kind can be registered for a descriptor.
if (this.has(descriptor, kind)) {
let { file, name } = this.get(descriptor, kind);
let msg = `Cannot register name "${requestedName}" of kind "${kind}" for ${string_format_1.StringFormat.formatName(descriptor)}. `
+ `The descriptor is already registered in file "${file.getFilename()}" with name "${name}". `
+ `Use a different 'kind' to register multiple symbols for a descriptor.`;
throw new Error(msg);
}
// find a free name within the file
let name = requestedName;
let count = 0;
while (this.hasNameInFile(name, file) && count < this.clashResolveMaxTries) {
name = this.clashResolver(descriptor, file, requestedName, kind, ++count, name);
}
if (this.hasNameInFile(name, file)) {
let msg = `Failed to register name "${requestedName}" for ${string_format_1.StringFormat.formatName(descriptor)}. `
+ `Gave up finding alternative name after ${this.clashResolveMaxTries} tries. `
+ `There is something wrong with the clash resolver.`;
throw new Error(msg);
}
// add the entry and return name
this.entries.push({ file, descriptor, kind, name });
return name;
}
/**
* Find a symbol (of the given kind) for the given descriptor.
* Return `undefined` if not found.
*/
find(descriptor, kind = 'default') {
return this.entries.find(e => e.descriptor === descriptor && e.kind === kind);
}
/**
* Find a symbol (of the given kind) for the given descriptor.
* Raises error if not found.
*/
get(descriptor, kind = 'default') {
const found = this.find(descriptor, kind);
if (!found) {
let files = this.entries.map(e => e.file)
.filter((value, index, array) => array.indexOf(value) === index);
let msg = `Failed to find name for ${string_format_1.StringFormat.formatName(descriptor)} of kind "${kind}". `
+ `Searched in ${files.length} files.`;
throw new Error(msg);
}
return found;
}
/**
* Is a name (of the given kind) registered for the the given descriptor?
*/
has(descriptor, kind = 'default') {
return !!this.find(descriptor, kind);
}
list(file, kind) {
let matches = this.entries.filter(e => e.file === file);
if (kind !== undefined) {
matches = matches.filter(e => e.kind === kind);
}
return matches;
}
static defaultClashResolver(descriptor, file, requestedName, kind, tryCount) {
let n = requestedName;
n = n.endsWith('$') ? n.substring(1) : n;
return n + '$' + tryCount;
}
}
exports.SymbolTable = SymbolTable;
@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeNameLookup = void 0;
const descriptor_info_1 = require("./descriptor-info");
const descriptor_1 = require("./google/protobuf/descriptor");
const runtime_1 = require("@protobuf-ts/runtime");
class TypeNameLookup {
constructor(data) {
const names = new Map();
const reverse = new Map();
for (let { descriptor, ancestors } of data) {
let name = composeTypeName([...ancestors, descriptor]);
runtime_1.assert(!names.has(name));
names.set(name, descriptor);
reverse.set(descriptor, name);
}
this._names = names;
this._reverse = reverse;
}
static from(a, b) {
let data = [];
if (Array.isArray(a) && b) {
for (let descriptor of a) {
if (!descriptor_info_1.isAnyTypeDescriptorProto(descriptor)) {
continue;
}
let ancestors = [];
let p = b(descriptor);
while (p) {
ancestors.unshift(p);
p = b(descriptor);
}
data.push({ descriptor, ancestors });
}
}
else if (!Array.isArray(a) && !b) {
a.visitTypes(descriptor => {
data.push({ descriptor, ancestors: a.ancestorsOf(descriptor) });
});
}
else {
runtime_1.assert(false);
}
return new TypeNameLookup(data);
}
normalizeTypeName(typeName) {
return typeName.startsWith(".") ? typeName.substring(1) : typeName;
}
resolveTypeName(typeName) {
typeName = this.normalizeTypeName(typeName);
const d = this._names.get(typeName);
runtime_1.assert(d !== undefined, `Unable to resolve type name "${typeName}"`);
return d;
}
peekTypeName(typeName) {
typeName = this.normalizeTypeName(typeName);
return this._names.get(typeName);
}
makeTypeName(descriptor) {
const n = this._reverse.get(descriptor);
runtime_1.assert(n !== undefined);
return n;
}
}
exports.TypeNameLookup = TypeNameLookup;
/**
* Compose a fully qualified type name for enum,
* message or service.
*
* Example:
* my_package.MyMessage.MyNestedMessage
*
* Throws if given array is invalid.
*/
function composeTypeName(descriptors) {
runtime_1.assert(descriptors.length > 0);
const parts = [], mid = descriptors.concat(), first = mid.shift(), last = mid.pop();
runtime_1.assert(descriptor_1.FileDescriptorProto.is(first));
runtime_1.assert(descriptor_info_1.isAnyTypeDescriptorProto(last), "expected any type descriptor, got: " + typeof (last));
const pkg = first.package;
if (pkg !== undefined && pkg !== '') {
parts.push(pkg);
}
for (const item of [...mid, last]) {
let part = item.name;
runtime_1.assert(part !== undefined);
parts.push(part);
}
return parts.join('.');
}
@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCommentBlockAsJsDoc = exports.addCommentBlocksAsLeadingDetachedLines = void 0;
const ts = require("typescript");
/**
* Adds multiple comment blocks as line comments
* in front of the given node.
*
* Applies a dirty hack to enforce newlines
* between each block.
*/
function addCommentBlocksAsLeadingDetachedLines(node, ...texts) {
for (let text of texts) {
let lines = text.split('\n').map(l => l[0] !== ' ' ? ` ${l}` : l);
for (let j = 0; j < lines.length; j++) {
const line = lines[j];
if (j === lines.length - 1) {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, line + '\n\n', false);
}
else {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, line, true);
}
}
}
}
exports.addCommentBlocksAsLeadingDetachedLines = addCommentBlocksAsLeadingDetachedLines;
/**
* Adds a JSDoc comment block in front of the given node.
*
* A JSDoc comment looks like this:
* /**
* * body text
* *\/
*
* A regular block comment looks like this:
* /* body text *\/
*
*/
function addCommentBlockAsJsDoc(node, text) {
let lines = text
.split('\n')
.map(line => {
if (line[0] === ' ') {
return ' *' + line;
}
return ' * ' + line;
});
text = '*\n' + lines.join('\n') + '\n ';
text = text.split('*/').join('*\\/'); // need to escape a comment in the comment
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, text, true);
}
exports.addCommentBlockAsJsDoc = addCommentBlockAsJsDoc;
@@ -0,0 +1,123 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCompiler = void 0;
const ts = require("typescript");
const path = require("path");
function setupCompiler(options, files, rootFileNames) {
const original = ts.createCompilerHost(options, true), host = new VirtualCompilerHost(original, files), libs = options.lib ? options.lib.map(lib => require.resolve(`typescript/lib/lib.${lib.toLowerCase()}.d.ts`)) : [], roots = rootFileNames.concat(libs), program = ts.createProgram(roots, options, host);
return [program, host];
}
exports.setupCompiler = setupCompiler;
class VirtualCompilerHost {
constructor(wrapped, files) {
this.wrapped = wrapped;
this._sourceFiles = new Map();
this._files = new Map();
this._dirs = new Set();
for (let vf of files) {
// create map from path to file
if (this._files.has(vf.getFilename())) {
throw new Error('Duplicate file paths in virtual files: ' + vf.getFilename());
}
this._files.set(vf.getFilename(), vf);
// create set of directory paths
let path = vf.getFilename().split('/');
while (path.length > 1) {
path.pop();
this._dirs.add(path.join('/'));
}
}
}
lookupVirtualFile(fileName) {
let vf = this._files.get(fileName);
if (vf)
return vf;
let cwd = process.cwd();
if (fileName.startsWith(cwd)) {
let relativePath = path.relative(cwd, fileName);
vf = this._files.get(relativePath);
if (vf)
return vf;
if (!relativePath.endsWith('.ts')) {
relativePath = relativePath += '.ts';
vf = this._files.get(relativePath);
if (vf)
return vf;
}
}
return undefined;
}
lookupVirtualDirectory(directoryName) {
let cwd = process.cwd();
if (directoryName.startsWith(cwd)) {
let relativePath = path.relative(cwd, directoryName);
return this._dirs.has(relativePath);
}
return false;
}
// noinspection JSUnusedGlobalSymbols
getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
const vf = this.lookupVirtualFile(fileName);
if (vf) {
let sf = this._sourceFiles.get(vf);
if (!sf) {
this._sourceFiles.set(vf, sf = ts.createSourceFile(vf.getFilename(), vf.getContent(), ts.ScriptTarget.Latest));
}
return sf;
}
return this.wrapped.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
}
// noinspection JSUnusedGlobalSymbols
getDefaultLibFileName(options) {
return this.wrapped.getDefaultLibFileName(options);
}
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles) {
// this.wrapped.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
}
// noinspection JSUnusedGlobalSymbols
getCurrentDirectory() {
return this.wrapped.getCurrentDirectory();
}
// noinspection JSUnusedGlobalSymbols
getCanonicalFileName(fileName) {
return this.wrapped.getCanonicalFileName(fileName);
}
// noinspection JSUnusedGlobalSymbols
useCaseSensitiveFileNames() {
return this.wrapped.useCaseSensitiveFileNames();
}
// noinspection JSUnusedGlobalSymbols
getNewLine() {
return this.wrapped.getNewLine();
}
// resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[], redirectedReference: ts.ResolvedProjectReference, options: ts.CompilerOptions): (ts.ResolvedModule | undefined)[] {
// resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ts.ResolvedProjectReference, options: ts.CompilerOptions): ts.ResolvedTypeReferenceDirective[] {
// noinspection JSUnusedGlobalSymbols
fileExists(fileName) {
return !!this.lookupVirtualFile(fileName) || this.wrapped.fileExists(fileName);
}
// noinspection JSUnusedGlobalSymbols
readFile(fileName) {
const vf = this.lookupVirtualFile(fileName);
if (vf)
return vf.getContent();
this.wrapped.readFile(fileName);
}
// noinspection JSUnusedGlobalSymbols
directoryExists(directoryName) {
if (this.lookupVirtualDirectory(directoryName))
return true;
const f = this.wrapped.directoryExists;
if (!f)
throw new Error('wrapped.directoryExists is undefined');
return f(directoryName);
}
// noinspection JSUnusedGlobalSymbols
getDirectories(path) {
const f = this.wrapped.getDirectories;
if (!f)
throw new Error('wrapped.getDirectories is undefined');
return f(path);
}
}
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypescriptEnumBuilder = void 0;
const ts = require("typescript");
const rt = require("@protobuf-ts/runtime");
const typescript_comments_1 = require("./typescript-comments");
/**
* Creates an enum declaration.
*/
class TypescriptEnumBuilder {
constructor() {
this.values = [];
}
add(name, number, comment) {
this.values.push({ name, number, comment });
}
build(name, modifiers) {
this.validate();
const members = [];
for (let { name, number, comment } of this.values) {
let member = ts.createEnumMember(ts.createIdentifier(name), ts.createNumericLiteral(number.toString()));
if (comment) {
typescript_comments_1.addCommentBlockAsJsDoc(member, comment);
}
members.push(member);
}
return ts.createEnumDeclaration(undefined, modifiers, name, members);
}
validate() {
if (this.values.map(v => v.name).some((name, i, a) => a.indexOf(name) !== i))
throw new Error("duplicate names");
let ei = {};
for (let v of this.values) {
ei[v.number] = v.name;
ei[v.name] = v.number;
}
if (!rt.isEnumObject(ei)) {
throw new Error("not a typescript enum object");
}
}
}
exports.TypescriptEnumBuilder = TypescriptEnumBuilder;
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypescriptFile = void 0;
const ts = require("typescript");
class TypescriptFile {
constructor(filename) {
this.sf = ts.createSourceFile(filename, "", ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
}
getFilename() {
return this.sf.fileName;
}
/**
* Add the new statement to the file.
*/
addStatement(statement, atTop = false) {
const newStatements = atTop
? [statement, ...this.sf.statements]
: this.sf.statements.concat(statement);
this.sf = ts.updateSourceFileNode(this.sf, newStatements);
}
/**
* The underlying SourceFile
*/
getSourceFile() {
return this.sf;
}
/**
* Are there any statements in this file?
*/
isEmpty() {
return this.sf.statements.length === 0;
}
/**
* The full content of this file.
* Returns an empty string if there are no statements.
*/
getContent() {
let printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
return printer.printFile(this.sf);
}
}
exports.TypescriptFile = TypescriptFile;
@@ -0,0 +1,206 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypescriptImportManager = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const ts = require("typescript");
const path = require("path");
/** @deprecated */
class TypescriptImportManager {
constructor(generatedFile, symbols, source) {
this.file = generatedFile;
this.symbols = symbols;
this.source = source;
}
/**
* Import {importName} from "importFrom";
*
* Automatically finds a free name if the
* `importName` would collide with another
* identifier.
*
* Returns imported name.
*/
name(importName, importFrom) {
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(this.source.getSourceFile(), importName, importFrom, blackListedNames, statementToAdd => this.source.addStatement(statementToAdd, true));
}
/**
* Import * as importAs from "importFrom";
*
* Returns name for `importAs`.
*/
namespace(importAs, importFrom) {
return ensureNamespaceImportPresent(this.source.getSourceFile(), importAs, importFrom, statementToAdd => this.source.addStatement(statementToAdd, true));
}
/**
* Import a previously registered identifier for a message
* or other descriptor.
*
* Uses the symbol table to look for the type, adds an
* import statement if necessary and automatically finds a
* free name if the identifier would clash in this file.
*
* If you have multiple representations for a descriptor
* in your generated code, use `kind` to discriminate.
*/
type(descriptor, kind = 'default') {
const symbolReg = this.symbols.get(descriptor, kind);
// symbol in this file?
if (symbolReg.file === this.file) {
return symbolReg.name;
}
// symbol not in file
// add an import statement
const importPath = createRelativeImportPath(this.source.getSourceFile().fileName, symbolReg.file.getFilename());
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(this.source.getSourceFile(), symbolReg.name, importPath, blackListedNames, statementToAdd => this.source.addStatement(statementToAdd, true));
}
}
exports.TypescriptImportManager = TypescriptImportManager;
/**
* Import * as asName from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* Does *not* check for collisions.
*/
function ensureNamespaceImportPresent(currentFile, asName, importFrom, addStatementFn) {
const all = findNamespaceImports(currentFile), match = all.find(ni => ni.as === asName && ni.from === importFrom);
if (match) {
return match.as;
}
const statementToAdd = createNamespaceImport(asName, importFrom);
addStatementFn(statementToAdd);
return asName;
}
/**
* import * as <asName> from "<importFrom>";
*/
function createNamespaceImport(asName, importFrom) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(asName))), ts.createStringLiteral(importFrom));
}
/**
* import * as <as> from "<from>";
*/
function findNamespaceImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
runtime_1.assert(ts.isStringLiteral(s.moduleSpecifier));
r.push({
as: namedBindings.name.escapedText.toString(),
from: s.moduleSpecifier.text
});
}
}
}
return r;
}
/**
* Import {importName} from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* If the import name is taken by another named import
* or is in the list of blacklisted names, an
* alternative name is used:
*
* Import {importName as alternativeName} from "importFrom";
*
* Returns the imported name or the alternative name.
*/
function ensureNamedImportPresent(currentFile, importName, importFrom, blacklistedNames, addStatementFn, escapeCharacter = '$') {
var _a;
const all = findNamedImports(currentFile), taken = all.map(ni => { var _a; return (_a = ni.as) !== null && _a !== void 0 ? _a : ni.name; }).concat(blacklistedNames), match = all.find(ni => ni.name === importName && ni.from === importFrom);
if (match) {
return (_a = match.as) !== null && _a !== void 0 ? _a : match.name;
}
let as;
if (taken.includes(importName)) {
let i = 0;
as = importName;
while (taken.includes(as)) {
as = importName + escapeCharacter;
if (i++ > 0) {
as += i;
}
}
}
const statementToAdd = createNamedImport(importName, importFrom, as);
addStatementFn(statementToAdd);
return as !== null && as !== void 0 ? as : importName;
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function createNamedImport(name, from, as) {
if (as) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(ts.createIdentifier(name), ts.createIdentifier(as))]), false), ts.createStringLiteral(from));
}
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([
ts.createImportSpecifier(undefined, ts.createIdentifier(name))
])), ts.createStringLiteral(from));
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function findNamedImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
for (let importSpecifier of namedBindings.elements) {
runtime_1.assert(ts.isStringLiteral(s.moduleSpecifier));
if (importSpecifier.propertyName) {
r.push({
name: importSpecifier.propertyName.escapedText.toString(),
as: importSpecifier.name.escapedText.toString(),
from: s.moduleSpecifier.text
});
}
else {
r.push({
name: importSpecifier.name.escapedText.toString(),
as: undefined,
from: s.moduleSpecifier.text
});
}
}
}
}
}
return r;
}
/**
* Create a relative path for an import statement like
* `import {Foo} from "./foo"`
*/
function createRelativeImportPath(currentPath, pathToImportFrom) {
// create relative path to the file to import
let fromPath = path.relative(path.dirname(currentPath), pathToImportFrom);
// on windows, this may add backslash directory separators.
// we replace them with forward slash.
if (path.sep !== "/") {
fromPath = fromPath.split(path.sep).join("/");
}
// drop file extension
fromPath = fromPath.replace(/\.[a-z]+$/, '');
// make sure to start with './' to signal relative path to module resolution
if (!fromPath.startsWith('../') && !fromPath.startsWith('./')) {
fromPath = './' + fromPath;
}
return fromPath;
}
@@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findNamedImports = exports.createNamedImport = exports.ensureNamedImportPresent = exports.TypeScriptImports = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const ts = require("typescript");
const path = require("path");
class TypeScriptImports {
constructor(symbols) {
this.symbols = symbols;
}
/**
* Import {importName} from "importFrom";
*
* Automatically finds a free name if the
* `importName` would collide with another
* identifier.
*
* Returns imported name.
*/
name(source, importName, importFrom, isTypeOnly = false) {
const blackListedNames = this.symbols.list(source).map(e => e.name);
return ensureNamedImportPresent(source.getSourceFile(), importName, importFrom, isTypeOnly, blackListedNames, statementToAdd => source.addStatement(statementToAdd, true));
}
/**
* Import * as importAs from "importFrom";
*
* Returns name for `importAs`.
*/
namespace(source, importAs, importFrom, isTypeOnly = false) {
return ensureNamespaceImportPresent(source.getSourceFile(), importAs, importFrom, isTypeOnly, statementToAdd => source.addStatement(statementToAdd, true));
}
/**
* Import a previously registered identifier for a message
* or other descriptor.
*
* Uses the symbol table to look for the type, adds an
* import statement if necessary and automatically finds a
* free name if the identifier would clash in this file.
*
* If you have multiple representations for a descriptor
* in your generated code, use `kind` to discriminate.
*/
type(source, descriptor, kind = 'default', isTypeOnly = false) {
const symbolReg = this.symbols.get(descriptor, kind);
// symbol in this file?
if (symbolReg.file === source) {
return symbolReg.name;
}
// symbol not in file
// add an import statement
const importPath = createRelativeImportPath(source.getSourceFile().fileName, symbolReg.file.getFilename());
const blackListedNames = this.symbols.list(source).map(e => e.name);
return ensureNamedImportPresent(source.getSourceFile(), symbolReg.name, importPath, isTypeOnly, blackListedNames, statementToAdd => source.addStatement(statementToAdd, true));
}
}
exports.TypeScriptImports = TypeScriptImports;
/**
* Import * as asName from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* Does *not* check for collisions.
*/
function ensureNamespaceImportPresent(currentFile, asName, importFrom, isTypeOnly, addStatementFn) {
const all = findNamespaceImports(currentFile), match = all.find(ni => ni.as === asName && ni.from === importFrom && ni.isTypeOnly === isTypeOnly);
if (match) {
return match.as;
}
const statementToAdd = createNamespaceImport(asName, importFrom, isTypeOnly);
addStatementFn(statementToAdd);
return asName;
}
/**
* import * as <asName> from "<importFrom>";
*/
function createNamespaceImport(asName, importFrom, isTypeOnly) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(asName)), isTypeOnly), ts.createStringLiteral(importFrom));
}
/**
* import * as <as> from "<from>";
*/
function findNamespaceImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
runtime_1.assert(ts.isStringLiteral(s.moduleSpecifier));
r.push({
as: namedBindings.name.escapedText.toString(),
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly,
});
}
}
}
return r;
}
/**
* import {importName} from "importFrom";
* import type {importName} from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* If the import name is taken by another named import
* or is in the list of blacklisted names, an
* alternative name is used:
*
* Import {importName as alternativeName} from "importFrom";
*
* Returns the imported name or the alternative name.
*/
function ensureNamedImportPresent(currentFile, importName, importFrom, isTypeOnly, blacklistedNames, addStatementFn, escapeCharacter = '$') {
var _a;
const all = findNamedImports(currentFile), taken = all.map(ni => { var _a; return (_a = ni.as) !== null && _a !== void 0 ? _a : ni.name; }).concat(blacklistedNames), match = all.find(ni => ni.name === importName && ni.from === importFrom && ni.isTypeOnly === isTypeOnly);
if (match) {
return (_a = match.as) !== null && _a !== void 0 ? _a : match.name;
}
let as;
if (taken.includes(importName)) {
let i = 0;
as = importName;
while (taken.includes(as)) {
as = importName + escapeCharacter;
if (i++ > 0) {
as += i;
}
}
}
const statementToAdd = createNamedImport(importName, importFrom, as, isTypeOnly);
addStatementFn(statementToAdd);
return as !== null && as !== void 0 ? as : importName;
}
exports.ensureNamedImportPresent = ensureNamedImportPresent;
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
* import type {<name>} from '<from>';
* import type {<name> as <as>} from '<from>';
*/
function createNamedImport(name, from, as, isTypeOnly = false) {
if (as) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(ts.createIdentifier(name), ts.createIdentifier(as))]), isTypeOnly), ts.createStringLiteral(from));
}
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([
ts.createImportSpecifier(undefined, ts.createIdentifier(name))
]), isTypeOnly), ts.createStringLiteral(from));
}
exports.createNamedImport = createNamedImport;
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
* import type {<name>} from '<from>';
* import type {<name> as <as>} from '<from>';
*/
function findNamedImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
for (let importSpecifier of namedBindings.elements) {
runtime_1.assert(ts.isStringLiteral(s.moduleSpecifier));
if (importSpecifier.propertyName) {
r.push({
name: importSpecifier.propertyName.escapedText.toString(),
as: importSpecifier.name.escapedText.toString(),
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly
});
}
else {
r.push({
name: importSpecifier.name.escapedText.toString(),
as: undefined,
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly
});
}
}
}
}
}
return r;
}
exports.findNamedImports = findNamedImports;
/**
* Create a relative path for an import statement like
* `import {Foo} from "./foo"`
*/
function createRelativeImportPath(currentPath, pathToImportFrom) {
// create relative path to the file to import
let fromPath = path.relative(path.dirname(currentPath), pathToImportFrom);
// on windows, this may add backslash directory separators.
// we replace them with forward slash.
if (path.sep !== "/") {
fromPath = fromPath.split(path.sep).join("/");
}
// drop file extension
fromPath = fromPath.replace(/\.[a-z]+$/, '');
// make sure to start with './' to signal relative path to module resolution
if (!fromPath.startsWith('../') && !fromPath.startsWith('./')) {
fromPath = './' + fromPath;
}
return fromPath;
}
@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typescriptLiteralFromValue = void 0;
const runtime_1 = require("@protobuf-ts/runtime");
const ts = require("typescript");
const validPropertyKey = /^(?![0-9])[a-zA-Z0-9$_]+$/;
/**
* Creates nodes for simple JavaScript values.
*
* Simple JavaScript values include:
* - all primitives: number, bigint, string, boolean
* - undefined, null
* - plain objects containing only simple JavaScript values
* - arrays containing only simple JavaScript values
* - typed arrays
*/
function typescriptLiteralFromValue(value) {
switch (typeof value) {
case "undefined":
return ts.createIdentifier("undefined");
case "boolean":
return value ? ts.createTrue() : ts.createFalse();
case "string":
return ts.createStringLiteral(value);
case "bigint":
return ts.createNumericLiteral(`${value}n`);
case "number":
if (isNaN(value)) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("Nan"));
}
else if (value === Number.POSITIVE_INFINITY) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("POSITIVE_INFINITY"));
}
else if (value === Number.NEGATIVE_INFINITY) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("NEGATIVE_INFINITY"));
}
return ts.createNumericLiteral(`${value}`);
case "object":
if (value === null) {
return ts.createNull();
}
if (isTypedArray(value)) {
if (value.length == 0) {
return ts.createNew(ts.createIdentifier(typedArrayName(value)), undefined, [ts.createNumericLiteral("0")]);
}
let values = [];
for (let i = 0; i < value.length; i++) {
values.push(ts.createNumericLiteral(value.toString()));
}
return ts.createNew(ts.createIdentifier(typedArrayName(value)), undefined, [ts.createArrayLiteral(values, false)]);
}
if (Array.isArray(value)) {
let elements = value.map(ele => typescriptLiteralFromValue(ele));
return ts.createArrayLiteral(elements, false);
}
if (value.constructor !== Object) {
throw new Error(`got a non-plain object ${value.constructor}`);
}
let props = [];
for (let key of Object.keys(value)) {
let propName = validPropertyKey.test(key) ? key : ts.createStringLiteral(key);
let propVal = typescriptLiteralFromValue(value[key]);
props.push(ts.createPropertyAssignment(propName, propVal));
}
return ts.createObjectLiteral(props, false);
}
runtime_1.assertNever(value);
}
exports.typescriptLiteralFromValue = typescriptLiteralFromValue;
function isTypedArray(arg) {
return arg instanceof Uint8Array
|| arg instanceof Int8Array
|| arg instanceof Uint8ClampedArray
|| arg instanceof Int16Array
|| arg instanceof Uint16Array
|| arg instanceof Int32Array
|| arg instanceof Uint32Array
|| arg instanceof Float32Array
|| arg instanceof Float64Array;
}
function typedArrayName(arg) {
if (arg instanceof Uint8Array) {
return 'Uint8Array';
}
if (arg instanceof Int8Array) {
return 'Int8Array';
}
if (arg instanceof Uint8ClampedArray) {
return 'Uint8ClampedArray';
}
if (arg instanceof Int16Array) {
return 'Int16Array';
}
if (arg instanceof Uint16Array) {
return 'Uint16Array';
}
if (arg instanceof Int32Array) {
return 'Int32Array';
}
if (arg instanceof Uint32Array) {
return 'Uint32Array';
}
if (arg instanceof Float32Array) {
return 'Float32Array';
}
return 'Float64Array';
}
@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typescriptMethodFromText = void 0;
const ts = require("typescript");
const typescript_comments_1 = require("./typescript-comments");
/**
* Provide a function statement as plain text, receive a
* method declaration.
*/
function typescriptMethodFromText(functionText) {
const sourceFile = ts.createSourceFile('temp.ts', functionText, ts.ScriptTarget.Latest);
if (sourceFile.statements.length !== 1) {
throw new Error('Expected exactly one statement, got ' + sourceFile.statements.length);
}
const node = sourceFile.statements[0];
if (!ts.isFunctionDeclaration(node)) {
throw new Error('Expected a function declaration');
}
if (node.name === undefined) {
throw new Error('function needs a name');
}
const method = ts.createMethod(node.decorators /*decorators*/, node.modifiers /*modifiers*/, node.asteriskToken /*asteriskToken*/, node.name, node.questionToken /*questionToken*/, node.typeParameters /*typeParameters*/, node.parameters, node.type /*return type*/, node.body);
ts.forEachLeadingCommentRange(functionText, node.getFullStart(), (pos, end) => {
let text = functionText.substring(pos, end);
text = text.trim();
if (text.startsWith('/*'))
text = text.substring(2);
if (text.endsWith('*/'))
text = text.substring(0, text.length - 2);
text = text.split('\n').map(l => l.replace(/^\s*\*/, '')).join('\n');
text = text.trim();
typescript_comments_1.addCommentBlockAsJsDoc(method, text);
});
return method;
}
exports.typescriptMethodFromText = typescriptMethodFromText;
@@ -0,0 +1,329 @@
import { DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FieldDescriptorProto_Label, FieldDescriptorProto_Type, FileDescriptorProto, MethodDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto } from "./google/protobuf/descriptor";
import { assert, lowerCamelCase } from "@protobuf-ts/runtime";
import { StringFormat } from "./string-format";
/**
* Is this a first-class type?
*/
export function isAnyTypeDescriptorProto(arg) {
return DescriptorProto.is(arg) || EnumDescriptorProto.is(arg) || ServiceDescriptorProto.is(arg);
}
export class DescriptorInfo {
constructor(tree, nameLookup) {
this.tree = tree;
this.nameLookup = nameLookup;
}
getAllExtensions() {
if (!this.allExtensions) {
this.allExtensions = [];
for (let file of this.tree.allFiles()) {
this.allExtensions.push(...file.extension);
for (let msg of file.messageType) {
this.allExtensions.push(...msg.extension);
}
}
}
return this.allExtensions;
}
isExtension(fieldDescriptor) {
if (fieldDescriptor.extendee === undefined) {
return false;
}
const parent = this.tree.parentOf(fieldDescriptor);
return parent.extension.includes(fieldDescriptor);
}
extensionsFor(descriptorOrTypeName) {
let extendeeTypeName;
if (typeof descriptorOrTypeName === "string") {
extendeeTypeName = this.nameLookup.makeTypeName(this.nameLookup.resolveTypeName(descriptorOrTypeName));
}
else {
extendeeTypeName = this.nameLookup.makeTypeName(descriptorOrTypeName);
}
return this.getAllExtensions().filter(ext => this.nameLookup.normalizeTypeName(ext.extendee) === extendeeTypeName);
}
getExtensionName(fieldDescriptor) {
assert(this.isExtension(fieldDescriptor), `${StringFormat.formatName(fieldDescriptor)} is not an extension. use isExtension() before getExtensionName()`);
assert(fieldDescriptor.name);
let extensionName;
let parent = this.tree.parentOf(fieldDescriptor);
if (FileDescriptorProto.is(parent)) {
extensionName = parent.package
? `${parent.package}.${fieldDescriptor.name}`
: `${fieldDescriptor.name}`;
}
else {
extensionName = `${this.nameLookup.makeTypeName(parent)}.${fieldDescriptor.name}`;
}
return extensionName;
}
getFieldCustomJsonName(fieldDescriptor) {
const name = lowerCamelCase(fieldDescriptor.name);
const jsonName = fieldDescriptor.jsonName;
if (jsonName !== undefined && jsonName !== '' && jsonName !== name) {
return jsonName;
}
return undefined;
}
isEnumField(fieldDescriptor) {
return fieldDescriptor.type === FieldDescriptorProto_Type.ENUM;
}
getEnumFieldEnum(fieldDescriptor) {
if (fieldDescriptor.type !== FieldDescriptorProto_Type.ENUM) {
throw new Error(`${StringFormat.formatName(fieldDescriptor)} is not a enum field. use isEnumField() before getEnumFieldEnum().`);
}
assert(fieldDescriptor.typeName !== undefined, `Missing enum type name for ${StringFormat.formatName(fieldDescriptor)}`);
let enumType = this.nameLookup.peekTypeName(fieldDescriptor.typeName);
assert(enumType !== undefined, `Missing enum type ${fieldDescriptor.typeName} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(EnumDescriptorProto.is(enumType), `Invalid enum type for ${StringFormat.formatName(fieldDescriptor)}`);
return enumType;
}
isMessageField(fieldDescriptor) {
let msg = fieldDescriptor.type === FieldDescriptorProto_Type.MESSAGE;
if (!msg) {
return false;
}
if (fieldDescriptor.name === undefined) {
return false;
}
if (this.isMapField(fieldDescriptor)) {
return false;
}
return true;
}
isGroupField(fieldDescriptor) {
return fieldDescriptor.type === FieldDescriptorProto_Type.GROUP;
}
getMessageFieldMessage(fieldDescriptor) {
if (!this.isMessageField(fieldDescriptor)) {
throw new Error(`${StringFormat.formatName(fieldDescriptor)} is not a message field. use isMessageField() before getMessageFieldMessage().`);
}
assert(fieldDescriptor.typeName !== undefined, `Missing message type name for ${StringFormat.formatName(fieldDescriptor)}`);
let messageType = this.nameLookup.peekTypeName(fieldDescriptor.typeName);
assert(messageType !== undefined, `Missing message type ${fieldDescriptor.typeName} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(DescriptorProto.is(messageType), `Invalid message type for ${StringFormat.formatName(fieldDescriptor)}`);
return messageType;
}
isScalarField(fieldDescriptor) {
switch (fieldDescriptor.type) {
case FieldDescriptorProto_Type.ENUM:
case FieldDescriptorProto_Type.MESSAGE:
case FieldDescriptorProto_Type.GROUP:
case FieldDescriptorProto_Type.UNSPECIFIED$:
return false;
}
return true;
}
getScalarFieldType(fieldDescriptor) {
if (!this.isScalarField(fieldDescriptor)) {
throw new Error(`${StringFormat.formatName(fieldDescriptor)} is not a scalar field. use isScalarField() before getScalarFieldType().`);
}
assert(fieldDescriptor.type !== undefined);
assert(fieldDescriptor.type !== FieldDescriptorProto_Type.ENUM);
assert(fieldDescriptor.type !== FieldDescriptorProto_Type.MESSAGE);
assert(fieldDescriptor.type !== FieldDescriptorProto_Type.GROUP);
assert(fieldDescriptor.type !== FieldDescriptorProto_Type.UNSPECIFIED$);
return fieldDescriptor.type;
}
isMapField(fieldDescriptor) {
return this.getMapEntryMessage(fieldDescriptor) !== undefined;
}
getMapKeyType(fieldDescriptor) {
let entry = this.getMapEntryMessage(fieldDescriptor);
if (!entry) {
throw new Error(`${StringFormat.formatName(fieldDescriptor)} is not a map field. use isMapField() before getMapKeyType().`);
}
let keyField = entry.field.find(fd => fd.number === 1);
assert(keyField !== undefined, `Missing map entry key field 1 for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== undefined, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.UNSPECIFIED$, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.GROUP, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.MESSAGE, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.ENUM, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.FLOAT, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.DOUBLE, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
assert(keyField.type !== FieldDescriptorProto_Type.BYTES, `Unexpected map key type ${keyField === null || keyField === void 0 ? void 0 : keyField.type} for ${StringFormat.formatName(fieldDescriptor)}`);
return keyField.type;
}
getMapValueType(fieldDescriptor) {
let entry = this.getMapEntryMessage(fieldDescriptor);
if (!entry) {
throw new Error(`${StringFormat.formatName(fieldDescriptor)} is not a map field. use isMapField() before getMapValueType().`);
}
let valueField = entry.field.find(fd => fd.number === 2);
assert(valueField !== undefined, `Missing map entry value field 2 for ${StringFormat.formatName(fieldDescriptor)}`);
if (this.isScalarField(valueField)) {
return this.getScalarFieldType(valueField);
}
if (this.isEnumField(valueField)) {
return this.getEnumFieldEnum(valueField);
}
return this.getMessageFieldMessage(valueField);
}
getMapEntryMessage(fieldDescriptor) {
var _a;
if (fieldDescriptor.type !== FieldDescriptorProto_Type.MESSAGE) {
return undefined;
}
if (fieldDescriptor.typeName === undefined || fieldDescriptor.typeName === "") {
return undefined;
}
let typeDescriptor = this.nameLookup.resolveTypeName(fieldDescriptor.typeName);
if (!DescriptorProto.is(typeDescriptor)) {
return undefined;
}
if (((_a = typeDescriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry) !== true) {
return undefined;
}
return typeDescriptor;
}
isExplicitlyDeclaredDeprecated(descriptor) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
if (FileDescriptorProto.is(descriptor)) {
return (_b = (_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false;
}
if (DescriptorProto.is(descriptor)) {
return (_d = (_c = descriptor.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false;
}
if (FieldDescriptorProto.is(descriptor)) {
return (_f = (_e = descriptor.options) === null || _e === void 0 ? void 0 : _e.deprecated) !== null && _f !== void 0 ? _f : false;
}
if (EnumDescriptorProto.is(descriptor)) {
return (_h = (_g = descriptor.options) === null || _g === void 0 ? void 0 : _g.deprecated) !== null && _h !== void 0 ? _h : false;
}
if (EnumValueDescriptorProto.is(descriptor)) {
return (_k = (_j = descriptor.options) === null || _j === void 0 ? void 0 : _j.deprecated) !== null && _k !== void 0 ? _k : false;
}
if (ServiceDescriptorProto.is(descriptor)) {
return (_m = (_l = descriptor.options) === null || _l === void 0 ? void 0 : _l.deprecated) !== null && _m !== void 0 ? _m : false;
}
if (MethodDescriptorProto.is(descriptor)) {
return (_p = (_o = descriptor.options) === null || _o === void 0 ? void 0 : _o.deprecated) !== null && _p !== void 0 ? _p : false;
}
if (OneofDescriptorProto.is(descriptor)) {
return false;
}
return false;
}
isSyntheticElement(descriptor) {
var _a;
if (DescriptorProto.is(descriptor)) {
if ((_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry) {
return true;
}
if (descriptor.name && descriptor.name.startsWith("$synthetic.")) {
return true;
}
}
return false;
}
isUserDeclaredOneof(fieldDescriptor) {
if (fieldDescriptor.oneofIndex === undefined) {
return false;
}
return fieldDescriptor.proto3Optional !== true;
}
isUserDeclaredOptional(fieldDescriptor) {
if (this.isUserDeclaredOneof(fieldDescriptor)) {
return false;
}
if (fieldDescriptor.proto3Optional === true) {
return true;
}
if (fieldDescriptor.proto3Optional === false) {
return false;
}
const file = this.tree.fileOf(fieldDescriptor);
if (file.syntax === 'proto3') {
return false;
}
assert(file.syntax === undefined || file.syntax === 'proto2', `unsupported syntax "${file.syntax}"`);
return fieldDescriptor.label === FieldDescriptorProto_Label.OPTIONAL;
}
isUserDeclaredRepeated(fieldDescriptor) {
var _a;
if (fieldDescriptor.label !== FieldDescriptorProto_Label.REPEATED) {
return false;
}
const name = fieldDescriptor.typeName;
if (name === undefined || name === "") {
return true;
}
const typeDescriptor = this.nameLookup.resolveTypeName(name);
if (DescriptorProto.is(typeDescriptor)) {
return !((_a = typeDescriptor.options) === null || _a === void 0 ? void 0 : _a.mapEntry);
}
return true;
}
shouldBePackedRepeated(fieldDescriptor) {
var _a;
let file = this.tree.fileOf(fieldDescriptor);
let standard, declared = (_a = fieldDescriptor.options) === null || _a === void 0 ? void 0 : _a.packed;
if (file.syntax === 'proto3') {
standard = true;
}
else {
assert(file.syntax === undefined || file.syntax === 'proto2', `unsupported syntax "${file.syntax}"`);
standard = false;
}
if (fieldDescriptor.type === FieldDescriptorProto_Type.BYTES || fieldDescriptor.type === FieldDescriptorProto_Type.STRING) {
assert(!declared, `repeated bytes | string cannot be packed. protoc should have caught this. probably unsupported protoc version.`);
standard = false;
}
return declared !== null && declared !== void 0 ? declared : standard;
}
findEnumSharedPrefix(enumDescriptor, enumLocalName) {
if (enumLocalName === undefined) {
enumLocalName = `${enumDescriptor.name}`;
}
// create possible prefix from local enum name
// for example, "MyEnum" => "MY_ENUM_"
let enumPrefix = enumLocalName;
enumPrefix = enumPrefix.replace(/[A-Z]/g, letter => "_" + letter.toLowerCase());
enumPrefix = (enumPrefix[0] === "_") ? enumPrefix.substring(1) : enumPrefix;
enumPrefix = enumPrefix.toUpperCase();
enumPrefix += '_';
// do all members share the prefix?
let names = enumDescriptor.value.map(enumValue => `${enumValue.name}`);
let allNamesSharePrefix = names.every(name => name.startsWith(enumPrefix));
// are the names with stripped prefix still valid?
// (start with uppercase letter, at least 2 chars long)
let strippedNames = names.map(name => name.substring(enumPrefix.length));
let strippedNamesAreValid = strippedNames.every(name => name.length > 0 && /^[A-Z].+/.test(name));
return (allNamesSharePrefix && strippedNamesAreValid) ? enumPrefix : undefined;
}
isFileUsed(file, inFiles) {
let used = false;
this.tree.visitTypes(file, typeDescriptor => {
if (used)
return;
if (this.isTypeUsed(typeDescriptor, inFiles)) {
used = true;
}
});
return used;
}
isTypeUsed(type, inFiles) {
const needle = this.nameLookup.makeTypeName(type);
let used = false;
for (let fd of inFiles) {
this.tree.visitTypes(fd, typeDescriptor => {
if (used)
return;
if (DescriptorProto.is(typeDescriptor)) {
const usedInField = typeDescriptor.field.some(fd => fd.typeName !== undefined && this.nameLookup.normalizeTypeName(fd.typeName) === needle);
if (usedInField) {
used = true;
}
}
else if (ServiceDescriptorProto.is(typeDescriptor)) {
const usedInMethodInput = typeDescriptor.method.some(md => md.inputType !== undefined && this.nameLookup.normalizeTypeName(md.inputType) === needle);
const usedInMethodOutput = typeDescriptor.method.some(md => md.outputType !== undefined && this.nameLookup.normalizeTypeName(md.outputType) === needle);
if (usedInMethodInput || usedInMethodOutput) {
used = true;
}
}
});
}
return used;
}
}
@@ -0,0 +1,150 @@
import { FileDescriptorProto } from "./google/protobuf/descriptor";
import { CodeGeneratorRequest } from "./google/protobuf/compiler/plugin";
import { DescriptorInfo } from "./descriptor-info";
import { DescriptorTree } from "./descriptor-tree";
import { SourceCodeInfoLookup } from "./source-code-info";
import { StringFormat } from "./string-format";
import { TypeNameLookup } from "./type-names";
export class DescriptorRegistry {
constructor(tree, typeNames, sourceCode, stringFormat, descriptorInfo) {
this.tree = tree;
this.typeNames = typeNames;
this.sourceCode = sourceCode;
this.stringFormat = stringFormat;
this.descriptorInfo = descriptorInfo;
}
static createFrom(requestOrFile) {
const files = CodeGeneratorRequest.is(requestOrFile)
? requestOrFile.protoFile
: [requestOrFile], tree = DescriptorTree.from(...files), nameLookup = TypeNameLookup.from(tree), sourceCodeLookup = new SourceCodeInfoLookup(d => tree.parentOf(d)), descriptorInfo = new DescriptorInfo(tree, nameLookup), stringFormat = new StringFormat(nameLookup, tree, sourceCodeLookup, descriptorInfo);
return new DescriptorRegistry(tree, nameLookup, sourceCodeLookup, stringFormat, descriptorInfo);
}
// ITypeNameLookup
normalizeTypeName(typeName) {
return this.typeNames.normalizeTypeName(typeName);
}
resolveTypeName(typeName) {
return this.typeNames.resolveTypeName(typeName);
}
peekTypeName(typeName) {
return this.typeNames.peekTypeName(typeName);
}
makeTypeName(descriptor) {
return this.typeNames.makeTypeName(descriptor);
}
// IDescriptorTree
ancestorsOf(descriptor) {
return this.tree.ancestorsOf(descriptor);
}
fileOf(descriptor) {
return this.tree.fileOf(descriptor);
}
allFiles() {
return this.tree.allFiles();
}
parentOf(descriptorOrOptions) {
return this.tree.parentOf(descriptorOrOptions);
}
visit(a, b) {
this.tree.visit(a, b);
}
visitTypes(a, b) {
this.tree.visitTypes(a, b);
}
// ISourceCodeInfoLookup
sourceCodeCursor(descriptor) {
return this.sourceCode.sourceCodeCursor(descriptor);
}
sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber) {
if (FileDescriptorProto.is(descriptorOrFile) && fileDescriptorFieldNumber !== undefined) {
return this.sourceCode.sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber);
}
return this.sourceCode.sourceCodeComments(descriptorOrFile);
}
// IStringFormat
formatFieldDeclaration(descriptor) {
return this.stringFormat.formatFieldDeclaration(descriptor);
}
formatQualifiedName(descriptor, includeFileInfo = false) {
return this.stringFormat.formatQualifiedName(descriptor, includeFileInfo);
}
formatName(descriptor) {
return this.stringFormat.formatName(descriptor);
}
formatEnumValueDeclaration(descriptor) {
return this.stringFormat.formatEnumValueDeclaration(descriptor);
}
formatRpcDeclaration(descriptor) {
return this.stringFormat.formatRpcDeclaration(descriptor);
}
// IDescriptorInfo
isExtension(descriptor) {
return this.descriptorInfo.isExtension(descriptor);
}
extensionsFor(descriptorOrTypeName) {
return this.descriptorInfo.extensionsFor(descriptorOrTypeName);
}
getExtensionName(descriptor) {
return this.descriptorInfo.getExtensionName(descriptor);
}
getFieldCustomJsonName(descriptor) {
return this.descriptorInfo.getFieldCustomJsonName(descriptor);
}
isEnumField(fieldDescriptor) {
return this.descriptorInfo.isEnumField(fieldDescriptor);
}
getEnumFieldEnum(fieldDescriptor) {
return this.descriptorInfo.getEnumFieldEnum(fieldDescriptor);
}
isMessageField(fieldDescriptor) {
return this.descriptorInfo.isMessageField(fieldDescriptor);
}
isGroupField(fieldDescriptor) {
return this.descriptorInfo.isGroupField(fieldDescriptor);
}
getMessageFieldMessage(fieldDescriptor) {
return this.descriptorInfo.getMessageFieldMessage(fieldDescriptor);
}
isScalarField(fieldDescriptor) {
return this.descriptorInfo.isScalarField(fieldDescriptor);
}
getScalarFieldType(fieldDescriptor) {
return this.descriptorInfo.getScalarFieldType(fieldDescriptor);
}
isMapField(fieldDescriptor) {
return this.descriptorInfo.isMapField(fieldDescriptor);
}
getMapKeyType(fieldDescriptor) {
return this.descriptorInfo.getMapKeyType(fieldDescriptor);
}
getMapValueType(fieldDescriptor) {
return this.descriptorInfo.getMapValueType(fieldDescriptor);
}
isExplicitlyDeclaredDeprecated(descriptor) {
return this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor);
}
isSyntheticElement(descriptor) {
return this.descriptorInfo.isSyntheticElement(descriptor);
}
findEnumSharedPrefix(descriptor, enumLocalName) {
return this.descriptorInfo.findEnumSharedPrefix(descriptor, enumLocalName);
}
isUserDeclaredOneof(descriptor) {
return this.descriptorInfo.isUserDeclaredOneof(descriptor);
}
isUserDeclaredOptional(descriptor) {
return this.descriptorInfo.isUserDeclaredOptional(descriptor);
}
isUserDeclaredRepeated(descriptor) {
return this.descriptorInfo.isUserDeclaredRepeated(descriptor);
}
shouldBePackedRepeated(descriptor) {
return this.descriptorInfo.shouldBePackedRepeated(descriptor);
}
isFileUsed(file, inFiles) {
return this.descriptorInfo.isFileUsed(file, inFiles);
}
isTypeUsed(type, inFiles) {
return this.descriptorInfo.isTypeUsed(type, inFiles);
}
}
@@ -0,0 +1,175 @@
import { DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto } from "./google/protobuf/descriptor";
import { isAnyTypeDescriptorProto } from "./descriptor-info";
import { assert, assertNever } from "@protobuf-ts/runtime";
export class DescriptorTree {
constructor(descriptors, options) {
const descriptorMap = new Map();
const optionMap = new Map();
const files = [];
for (const [descriptor, info] of descriptors) {
// infos
assert(!descriptorMap.has(descriptor));
descriptorMap.set(descriptor, info);
// files
if (FileDescriptorProto.is(descriptor)) {
files.push(descriptor);
}
}
for (const [option, descriptor] of options) {
optionMap.set(option, descriptor);
}
this._files = files;
this._descriptors = descriptorMap;
this._options = optionMap;
}
/**
* Create the tree from a list of root files.
*/
static from(...files) {
const descriptors = [];
const options = [];
for (const file of files) {
visitDescriptorTree(file, (descriptor, ancestors) => {
descriptors.push([descriptor, { ancestors, file, parent: ancestors[ancestors.length - 1] }]);
if (descriptor.options) {
options.push([descriptor.options, descriptor]);
}
});
}
return new DescriptorTree(descriptors, options);
}
ancestorsOf(descriptor) {
const v = this._descriptors.get(descriptor);
assert(v !== undefined);
return v.ancestors.concat();
}
fileOf(descriptor) {
const v = this._descriptors.get(descriptor);
assert(v !== undefined);
return v.file;
}
allFiles() {
return this._files;
}
parentOf(descriptorOrOptions) {
const optionParent = this._options.get(descriptorOrOptions);
if (optionParent) {
return optionParent;
}
const descriptorEntry = this._descriptors.get(descriptorOrOptions);
if (descriptorEntry) {
return descriptorEntry.parent;
}
assert(FileDescriptorProto.is(descriptorOrOptions));
return undefined;
}
visit(a, b) {
if (b === undefined) {
for (const file of this._files) {
visitDescriptorTree(file, a);
}
}
else {
const startingFrom = a;
visitDescriptorTree(startingFrom, descriptor => {
if (descriptor === a) {
return; // visitDescriptorTree invokes on starting element. ignore.
}
b(descriptor);
});
}
}
visitTypes(a, b) {
if (b === undefined) {
for (const file of this._files) {
visitDescriptorTree(file, descriptor => {
if (isAnyTypeDescriptorProto(descriptor)) {
a(descriptor);
}
});
}
}
else {
visitDescriptorTree(a, descriptor => {
if (descriptor === a) {
return; // visitDescriptorTree invokes on starting element. ignore.
}
if (isAnyTypeDescriptorProto(descriptor)) {
b(descriptor);
}
});
}
}
}
/**
* Visit all logical children of the given descriptor proto.
*
* The "visitor" function is called for each element,
* including the input. It receives two arguments:
* 1) the current descriptor proto
* 2) the ancestors of the current descriptor proto (an array of descriptors)
*/
export function visitDescriptorTree(input, visitor) {
visitWithCarry(input, [], visitor);
}
function visitWithCarry(input, carry, visitor) {
visitor(input, carry);
carry = carry.concat(input);
// noinspection SuspiciousTypeOfGuard
if (EnumDescriptorProto.is(input)) {
for (const val of input.value) {
visitWithCarry(val, carry, visitor);
}
}
else if (DescriptorProto.is(input)) {
for (const oneof of input.oneofDecl) {
visitWithCarry(oneof, carry, visitor);
}
for (const field of input.field) {
visitWithCarry(field, carry, visitor);
}
for (const message of input.nestedType) {
visitWithCarry(message, carry, visitor);
}
for (const enu of input.enumType) {
visitWithCarry(enu, carry, visitor);
}
for (const extensionField of input.extension) {
visitWithCarry(extensionField, carry, visitor);
}
}
else if (FileDescriptorProto.is(input)) {
for (const message of input.messageType) {
visitWithCarry(message, carry, visitor);
}
for (const enu of input.enumType) {
visitWithCarry(enu, carry, visitor);
}
for (const service of input.service) {
visitWithCarry(service, carry, visitor);
}
for (const extensionField of input.extension) {
visitWithCarry(extensionField, carry, visitor);
}
}
else if (ServiceDescriptorProto.is(input)) {
for (const method of input.method) {
visitWithCarry(method, carry, visitor);
}
}
else if (EnumValueDescriptorProto.is(input)) {
//
}
else if (FieldDescriptorProto.is(input)) {
//
}
else if (MethodDescriptorProto.is(input)) {
//
}
else if (OneofDescriptorProto.is(input)) {
//
}
else {
assertNever(input);
}
}
@@ -0,0 +1,125 @@
// @generated by protobuf-ts 1.0.0-alpha.35 with parameters force_optimize_code_size,long_type_string
// @generated from protobuf file "google/protobuf/compiler/plugin.proto" (package "google.protobuf.compiler", syntax proto2)
// tslint:disable
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Author: [email protected] (Kenton Varda)
//
// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
// change.
//
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "protoc-gen-$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.
//
import { RepeatType } from "@protobuf-ts/runtime";
import { ScalarType } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { FileDescriptorProto } from "../descriptor";
/**
* Sync with code_generator.h.
*
* @generated from protobuf enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export var CodeGeneratorResponse_Feature;
(function (CodeGeneratorResponse_Feature) {
/**
* @generated from protobuf enum value: FEATURE_NONE = 0;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["NONE"] = 0] = "NONE";
/**
* @generated from protobuf enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["PROTO3_OPTIONAL"] = 1] = "PROTO3_OPTIONAL";
})(CodeGeneratorResponse_Feature || (CodeGeneratorResponse_Feature = {}));
/**
* Type for protobuf message google.protobuf.compiler.Version
*/
class Version$Type extends MessageType {
constructor() {
super("google.protobuf.compiler.Version", [
{ no: 1, name: "major", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 2, name: "minor", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 3, name: "patch", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 4, name: "suffix", kind: "scalar", opt: true, T: ScalarType.STRING }
]);
}
}
export const Version = new Version$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorRequest
*/
class CodeGeneratorRequest$Type extends MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorRequest", [
{ no: 1, name: "file_to_generate", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING },
{ no: 2, name: "parameter", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 15, name: "proto_file", kind: "message", repeat: RepeatType.UNPACKED, T: () => FileDescriptorProto },
{ no: 3, name: "compiler_version", kind: "message", T: () => Version }
]);
}
}
export const CodeGeneratorRequest = new CodeGeneratorRequest$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse
*/
class CodeGeneratorResponse$Type extends MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorResponse", [
{ no: 1, name: "error", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "supported_features", kind: "scalar", opt: true, T: ScalarType.UINT64 },
{ no: 15, name: "file", kind: "message", repeat: RepeatType.UNPACKED, T: () => CodeGeneratorResponse_File }
]);
}
}
export const CodeGeneratorResponse = new CodeGeneratorResponse$Type();
/**
* Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse.File
*/
class CodeGeneratorResponse_File$Type extends MessageType {
constructor() {
super("google.protobuf.compiler.CodeGeneratorResponse.File", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "insertion_point", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 15, name: "content", kind: "scalar", opt: true, T: ScalarType.STRING }
]);
}
}
export const CodeGeneratorResponse_File = new CodeGeneratorResponse_File$Type();
@@ -0,0 +1,671 @@
// @generated by protobuf-ts 1.0.0-alpha.35 with parameters force_optimize_code_size,long_type_string
// @generated from protobuf file "google/protobuf/descriptor.proto" (package "google.protobuf", syntax proto2)
// tslint:disable
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
//
import { ScalarType } from "@protobuf-ts/runtime";
import { RepeatType } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Type
*/
export var FieldDescriptorProto_Type;
(function (FieldDescriptorProto_Type) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* 0 is reserved for errors.
* Order is weird for historical reasons.
*
* @generated from protobuf enum value: TYPE_DOUBLE = 1;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["DOUBLE"] = 1] = "DOUBLE";
/**
* @generated from protobuf enum value: TYPE_FLOAT = 2;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FLOAT"] = 2] = "FLOAT";
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT64 = 3;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["INT64"] = 3] = "INT64";
/**
* @generated from protobuf enum value: TYPE_UINT64 = 4;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UINT64"] = 4] = "UINT64";
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT32 = 5;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["INT32"] = 5] = "INT32";
/**
* @generated from protobuf enum value: TYPE_FIXED64 = 6;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FIXED64"] = 6] = "FIXED64";
/**
* @generated from protobuf enum value: TYPE_FIXED32 = 7;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["FIXED32"] = 7] = "FIXED32";
/**
* @generated from protobuf enum value: TYPE_BOOL = 8;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["BOOL"] = 8] = "BOOL";
/**
* @generated from protobuf enum value: TYPE_STRING = 9;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["STRING"] = 9] = "STRING";
/**
* Tag-delimited aggregate.
* Group type is deprecated and not supported in proto3. However, Proto3
* implementations should still be able to parse the group wire format and
* treat group fields as unknown fields.
*
* @generated from protobuf enum value: TYPE_GROUP = 10;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["GROUP"] = 10] = "GROUP";
/**
* Length-delimited aggregate.
*
* @generated from protobuf enum value: TYPE_MESSAGE = 11;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["MESSAGE"] = 11] = "MESSAGE";
/**
* New in version 2.
*
* @generated from protobuf enum value: TYPE_BYTES = 12;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["BYTES"] = 12] = "BYTES";
/**
* @generated from protobuf enum value: TYPE_UINT32 = 13;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["UINT32"] = 13] = "UINT32";
/**
* @generated from protobuf enum value: TYPE_ENUM = 14;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["ENUM"] = 14] = "ENUM";
/**
* @generated from protobuf enum value: TYPE_SFIXED32 = 15;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SFIXED32"] = 15] = "SFIXED32";
/**
* @generated from protobuf enum value: TYPE_SFIXED64 = 16;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SFIXED64"] = 16] = "SFIXED64";
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT32 = 17;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SINT32"] = 17] = "SINT32";
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT64 = 18;
*/
FieldDescriptorProto_Type[FieldDescriptorProto_Type["SINT64"] = 18] = "SINT64";
})(FieldDescriptorProto_Type || (FieldDescriptorProto_Type = {}));
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Label
*/
export var FieldDescriptorProto_Label;
(function (FieldDescriptorProto_Label) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* 0 is reserved for errors
*
* @generated from protobuf enum value: LABEL_OPTIONAL = 1;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["OPTIONAL"] = 1] = "OPTIONAL";
/**
* @generated from protobuf enum value: LABEL_REQUIRED = 2;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["REQUIRED"] = 2] = "REQUIRED";
/**
* @generated from protobuf enum value: LABEL_REPEATED = 3;
*/
FieldDescriptorProto_Label[FieldDescriptorProto_Label["REPEATED"] = 3] = "REPEATED";
})(FieldDescriptorProto_Label || (FieldDescriptorProto_Label = {}));
/**
* Generated classes can be optimized for speed or code size.
*
* @generated from protobuf enum google.protobuf.FileOptions.OptimizeMode
*/
export var FileOptions_OptimizeMode;
(function (FileOptions_OptimizeMode) {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["UNSPECIFIED$"] = 0] = "UNSPECIFIED$";
/**
* Generate complete code for parsing, serialization,
*
* @generated from protobuf enum value: SPEED = 1;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["SPEED"] = 1] = "SPEED";
/**
* etc.
*
* Use ReflectionOps to implement these methods.
*
* @generated from protobuf enum value: CODE_SIZE = 2;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE";
/**
* Generate code using MessageLite and the lite runtime.
*
* @generated from protobuf enum value: LITE_RUNTIME = 3;
*/
FileOptions_OptimizeMode[FileOptions_OptimizeMode["LITE_RUNTIME"] = 3] = "LITE_RUNTIME";
})(FileOptions_OptimizeMode || (FileOptions_OptimizeMode = {}));
/**
* @generated from protobuf enum google.protobuf.FieldOptions.CType
*/
export var FieldOptions_CType;
(function (FieldOptions_CType) {
/**
* Default mode.
*
* @generated from protobuf enum value: STRING = 0;
*/
FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING";
/**
* @generated from protobuf enum value: CORD = 1;
*/
FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD";
/**
* @generated from protobuf enum value: STRING_PIECE = 2;
*/
FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE";
})(FieldOptions_CType || (FieldOptions_CType = {}));
/**
* @generated from protobuf enum google.protobuf.FieldOptions.JSType
*/
export var FieldOptions_JSType;
(function (FieldOptions_JSType) {
/**
* Use the default type.
*
* @generated from protobuf enum value: JS_NORMAL = 0;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_NORMAL"] = 0] = "JS_NORMAL";
/**
* Use JavaScript strings.
*
* @generated from protobuf enum value: JS_STRING = 1;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_STRING"] = 1] = "JS_STRING";
/**
* Use JavaScript numbers.
*
* @generated from protobuf enum value: JS_NUMBER = 2;
*/
FieldOptions_JSType[FieldOptions_JSType["JS_NUMBER"] = 2] = "JS_NUMBER";
})(FieldOptions_JSType || (FieldOptions_JSType = {}));
/**
* Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
* or neither? HTTP based RPC implementation may choose GET verb for safe
* methods, and PUT verb for idempotent methods instead of the default POST.
*
* @generated from protobuf enum google.protobuf.MethodOptions.IdempotencyLevel
*/
export var MethodOptions_IdempotencyLevel;
(function (MethodOptions_IdempotencyLevel) {
/**
* @generated from protobuf enum value: IDEMPOTENCY_UNKNOWN = 0;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = 0] = "IDEMPOTENCY_UNKNOWN";
/**
* implies idempotent
*
* @generated from protobuf enum value: NO_SIDE_EFFECTS = 1;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["NO_SIDE_EFFECTS"] = 1] = "NO_SIDE_EFFECTS";
/**
* idempotent, but may have side effects
*
* @generated from protobuf enum value: IDEMPOTENT = 2;
*/
MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENT"] = 2] = "IDEMPOTENT";
})(MethodOptions_IdempotencyLevel || (MethodOptions_IdempotencyLevel = {}));
/**
* Type for protobuf message google.protobuf.FileDescriptorSet
*/
class FileDescriptorSet$Type extends MessageType {
constructor() {
super("google.protobuf.FileDescriptorSet", [
{ no: 1, name: "file", kind: "message", repeat: RepeatType.UNPACKED, T: () => FileDescriptorProto }
]);
}
}
export const FileDescriptorSet = new FileDescriptorSet$Type();
/**
* Type for protobuf message google.protobuf.FileDescriptorProto
*/
class FileDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.FileDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "package", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 3, name: "dependency", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING },
{ no: 10, name: "public_dependency", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.INT32 },
{ no: 11, name: "weak_dependency", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.INT32 },
{ no: 4, name: "message_type", kind: "message", repeat: RepeatType.UNPACKED, T: () => DescriptorProto },
{ no: 5, name: "enum_type", kind: "message", repeat: RepeatType.UNPACKED, T: () => EnumDescriptorProto },
{ no: 6, name: "service", kind: "message", repeat: RepeatType.UNPACKED, T: () => ServiceDescriptorProto },
{ no: 7, name: "extension", kind: "message", repeat: RepeatType.UNPACKED, T: () => FieldDescriptorProto },
{ no: 8, name: "options", kind: "message", T: () => FileOptions },
{ no: 9, name: "source_code_info", kind: "message", T: () => SourceCodeInfo },
{ no: 12, name: "syntax", kind: "scalar", opt: true, T: ScalarType.STRING }
]);
}
}
export const FileDescriptorProto = new FileDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto
*/
class DescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.DescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "field", kind: "message", repeat: RepeatType.UNPACKED, T: () => FieldDescriptorProto },
{ no: 6, name: "extension", kind: "message", repeat: RepeatType.UNPACKED, T: () => FieldDescriptorProto },
{ no: 3, name: "nested_type", kind: "message", repeat: RepeatType.UNPACKED, T: () => DescriptorProto },
{ no: 4, name: "enum_type", kind: "message", repeat: RepeatType.UNPACKED, T: () => EnumDescriptorProto },
{ no: 5, name: "extension_range", kind: "message", repeat: RepeatType.UNPACKED, T: () => DescriptorProto_ExtensionRange },
{ no: 8, name: "oneof_decl", kind: "message", repeat: RepeatType.UNPACKED, T: () => OneofDescriptorProto },
{ no: 7, name: "options", kind: "message", T: () => MessageOptions },
{ no: 9, name: "reserved_range", kind: "message", repeat: RepeatType.UNPACKED, T: () => DescriptorProto_ReservedRange },
{ no: 10, name: "reserved_name", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING }
]);
}
}
export const DescriptorProto = new DescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto.ExtensionRange
*/
class DescriptorProto_ExtensionRange$Type extends MessageType {
constructor() {
super("google.protobuf.DescriptorProto.ExtensionRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 3, name: "options", kind: "message", T: () => ExtensionRangeOptions }
]);
}
}
export const DescriptorProto_ExtensionRange = new DescriptorProto_ExtensionRange$Type();
/**
* Type for protobuf message google.protobuf.DescriptorProto.ReservedRange
*/
class DescriptorProto_ReservedRange$Type extends MessageType {
constructor() {
super("google.protobuf.DescriptorProto.ReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: ScalarType.INT32 }
]);
}
}
export const DescriptorProto_ReservedRange = new DescriptorProto_ReservedRange$Type();
/**
* Type for protobuf message google.protobuf.ExtensionRangeOptions
*/
class ExtensionRangeOptions$Type extends MessageType {
constructor() {
super("google.protobuf.ExtensionRangeOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const ExtensionRangeOptions = new ExtensionRangeOptions$Type();
/**
* Type for protobuf message google.protobuf.FieldDescriptorProto
*/
class FieldDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.FieldDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 3, name: "number", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 4, name: "label", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Label", FieldDescriptorProto_Label, "LABEL_"] },
{ no: 5, name: "type", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Type", FieldDescriptorProto_Type, "TYPE_"] },
{ no: 6, name: "type_name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "extendee", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 7, name: "default_value", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 9, name: "oneof_index", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 10, name: "json_name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 8, name: "options", kind: "message", T: () => FieldOptions },
{ no: 17, name: "proto3_optional", kind: "scalar", opt: true, T: ScalarType.BOOL }
]);
}
}
export const FieldDescriptorProto = new FieldDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.OneofDescriptorProto
*/
class OneofDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.OneofDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "options", kind: "message", T: () => OneofOptions }
]);
}
}
export const OneofDescriptorProto = new OneofDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.EnumDescriptorProto
*/
class EnumDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.EnumDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "value", kind: "message", repeat: RepeatType.UNPACKED, T: () => EnumValueDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => EnumOptions },
{ no: 4, name: "reserved_range", kind: "message", repeat: RepeatType.UNPACKED, T: () => EnumDescriptorProto_EnumReservedRange },
{ no: 5, name: "reserved_name", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING }
]);
}
}
export const EnumDescriptorProto = new EnumDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.EnumDescriptorProto.EnumReservedRange
*/
class EnumDescriptorProto_EnumReservedRange$Type extends MessageType {
constructor() {
super("google.protobuf.EnumDescriptorProto.EnumReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 2, name: "end", kind: "scalar", opt: true, T: ScalarType.INT32 }
]);
}
}
export const EnumDescriptorProto_EnumReservedRange = new EnumDescriptorProto_EnumReservedRange$Type();
/**
* Type for protobuf message google.protobuf.EnumValueDescriptorProto
*/
class EnumValueDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.EnumValueDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "number", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 3, name: "options", kind: "message", T: () => EnumValueOptions }
]);
}
}
export const EnumValueDescriptorProto = new EnumValueDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.ServiceDescriptorProto
*/
class ServiceDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.ServiceDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "method", kind: "message", repeat: RepeatType.UNPACKED, T: () => MethodDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => ServiceOptions }
]);
}
}
export const ServiceDescriptorProto = new ServiceDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.MethodDescriptorProto
*/
class MethodDescriptorProto$Type extends MessageType {
constructor() {
super("google.protobuf.MethodDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 2, name: "input_type", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 3, name: "output_type", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 4, name: "options", kind: "message", T: () => MethodOptions },
{ no: 5, name: "client_streaming", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 6, name: "server_streaming", kind: "scalar", opt: true, T: ScalarType.BOOL }
]);
}
}
export const MethodDescriptorProto = new MethodDescriptorProto$Type();
/**
* Type for protobuf message google.protobuf.FileOptions
*/
class FileOptions$Type extends MessageType {
constructor() {
super("google.protobuf.FileOptions", [
{ no: 1, name: "java_package", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 8, name: "java_outer_classname", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 10, name: "java_multiple_files", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 20, name: "java_generate_equals_and_hash", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 27, name: "java_string_check_utf8", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 9, name: "optimize_for", kind: "enum", opt: true, T: () => ["google.protobuf.FileOptions.OptimizeMode", FileOptions_OptimizeMode] },
{ no: 11, name: "go_package", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 16, name: "cc_generic_services", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 17, name: "java_generic_services", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 18, name: "py_generic_services", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 42, name: "php_generic_services", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 23, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 31, name: "cc_enable_arenas", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 36, name: "objc_class_prefix", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 37, name: "csharp_namespace", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 39, name: "swift_prefix", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 40, name: "php_class_prefix", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 41, name: "php_namespace", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 44, name: "php_metadata_namespace", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 45, name: "ruby_package", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const FileOptions = new FileOptions$Type();
/**
* Type for protobuf message google.protobuf.MessageOptions
*/
class MessageOptions$Type extends MessageType {
constructor() {
super("google.protobuf.MessageOptions", [
{ no: 1, name: "message_set_wire_format", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 2, name: "no_standard_descriptor_accessor", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 7, name: "map_entry", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const MessageOptions = new MessageOptions$Type();
/**
* Type for protobuf message google.protobuf.FieldOptions
*/
class FieldOptions$Type extends MessageType {
constructor() {
super("google.protobuf.FieldOptions", [
{ no: 1, name: "ctype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.CType", FieldOptions_CType] },
{ no: 2, name: "packed", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 6, name: "jstype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.JSType", FieldOptions_JSType] },
{ no: 5, name: "lazy", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 10, name: "weak", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const FieldOptions = new FieldOptions$Type();
/**
* Type for protobuf message google.protobuf.OneofOptions
*/
class OneofOptions$Type extends MessageType {
constructor() {
super("google.protobuf.OneofOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const OneofOptions = new OneofOptions$Type();
/**
* Type for protobuf message google.protobuf.EnumOptions
*/
class EnumOptions$Type extends MessageType {
constructor() {
super("google.protobuf.EnumOptions", [
{ no: 2, name: "allow_alias", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const EnumOptions = new EnumOptions$Type();
/**
* Type for protobuf message google.protobuf.EnumValueOptions
*/
class EnumValueOptions$Type extends MessageType {
constructor() {
super("google.protobuf.EnumValueOptions", [
{ no: 1, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const EnumValueOptions = new EnumValueOptions$Type();
/**
* Type for protobuf message google.protobuf.ServiceOptions
*/
class ServiceOptions$Type extends MessageType {
constructor() {
super("google.protobuf.ServiceOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const ServiceOptions = new ServiceOptions$Type();
/**
* Type for protobuf message google.protobuf.MethodOptions
*/
class MethodOptions$Type extends MessageType {
constructor() {
super("google.protobuf.MethodOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: ScalarType.BOOL },
{ no: 34, name: "idempotency_level", kind: "enum", opt: true, T: () => ["google.protobuf.MethodOptions.IdempotencyLevel", MethodOptions_IdempotencyLevel] },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption }
]);
}
}
export const MethodOptions = new MethodOptions$Type();
/**
* Type for protobuf message google.protobuf.UninterpretedOption
*/
class UninterpretedOption$Type extends MessageType {
constructor() {
super("google.protobuf.UninterpretedOption", [
{ no: 2, name: "name", kind: "message", repeat: RepeatType.UNPACKED, T: () => UninterpretedOption_NamePart },
{ no: 3, name: "identifier_value", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 4, name: "positive_int_value", kind: "scalar", opt: true, T: ScalarType.UINT64 },
{ no: 5, name: "negative_int_value", kind: "scalar", opt: true, T: ScalarType.INT64 },
{ no: 6, name: "double_value", kind: "scalar", opt: true, T: ScalarType.DOUBLE },
{ no: 7, name: "string_value", kind: "scalar", opt: true, T: ScalarType.BYTES },
{ no: 8, name: "aggregate_value", kind: "scalar", opt: true, T: ScalarType.STRING }
]);
}
}
export const UninterpretedOption = new UninterpretedOption$Type();
/**
* Type for protobuf message google.protobuf.UninterpretedOption.NamePart
*/
class UninterpretedOption_NamePart$Type extends MessageType {
constructor() {
super("google.protobuf.UninterpretedOption.NamePart", [
{ no: 1, name: "name_part", kind: "scalar", T: ScalarType.STRING },
{ no: 2, name: "is_extension", kind: "scalar", T: ScalarType.BOOL }
]);
}
}
export const UninterpretedOption_NamePart = new UninterpretedOption_NamePart$Type();
/**
* Type for protobuf message google.protobuf.SourceCodeInfo
*/
class SourceCodeInfo$Type extends MessageType {
constructor() {
super("google.protobuf.SourceCodeInfo", [
{ no: 1, name: "location", kind: "message", repeat: RepeatType.UNPACKED, T: () => SourceCodeInfo_Location }
]);
}
}
export const SourceCodeInfo = new SourceCodeInfo$Type();
/**
* Type for protobuf message google.protobuf.SourceCodeInfo.Location
*/
class SourceCodeInfo_Location$Type extends MessageType {
constructor() {
super("google.protobuf.SourceCodeInfo.Location", [
{ no: 1, name: "path", kind: "scalar", repeat: RepeatType.PACKED, T: ScalarType.INT32 },
{ no: 2, name: "span", kind: "scalar", repeat: RepeatType.PACKED, T: ScalarType.INT32 },
{ no: 3, name: "leading_comments", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 4, name: "trailing_comments", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 6, name: "leading_detached_comments", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING }
]);
}
}
export const SourceCodeInfo_Location = new SourceCodeInfo_Location$Type();
/**
* Type for protobuf message google.protobuf.GeneratedCodeInfo
*/
class GeneratedCodeInfo$Type extends MessageType {
constructor() {
super("google.protobuf.GeneratedCodeInfo", [
{ no: 1, name: "annotation", kind: "message", repeat: RepeatType.UNPACKED, T: () => GeneratedCodeInfo_Annotation }
]);
}
}
export const GeneratedCodeInfo = new GeneratedCodeInfo$Type();
/**
* Type for protobuf message google.protobuf.GeneratedCodeInfo.Annotation
*/
class GeneratedCodeInfo_Annotation$Type extends MessageType {
constructor() {
super("google.protobuf.GeneratedCodeInfo.Annotation", [
{ no: 1, name: "path", kind: "scalar", repeat: RepeatType.PACKED, T: ScalarType.INT32 },
{ no: 2, name: "source_file", kind: "scalar", opt: true, T: ScalarType.STRING },
{ no: 3, name: "begin", kind: "scalar", opt: true, T: ScalarType.INT32 },
{ no: 4, name: "end", kind: "scalar", opt: true, T: ScalarType.INT32 }
]);
}
}
export const GeneratedCodeInfo_Annotation = new GeneratedCodeInfo_Annotation$Type();
+19
View File
@@ -0,0 +1,19 @@
export * from './descriptor-info';
export * from './descriptor-registry';
export * from './descriptor-tree';
export * from './generated-file';
export * from './plugin-base';
export * from './source-code-info';
export * from './string-format';
export * from './symbol-table';
export * from './type-names';
export * from './google/protobuf/descriptor';
export * from './google/protobuf/compiler/plugin';
export * from './typescript-compile';
export * from './typescript-comments';
export * from './typescript-import-manager';
export * from './typescript-method-from-text';
export * from './typescript-literal-from-value';
export * from './typescript-enum-builder';
export * from "./typescript-file";
export * from "./typescript-imports";
+199
View File
@@ -0,0 +1,199 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { CodeGeneratorRequest, CodeGeneratorResponse, CodeGeneratorResponse_File } from "./google/protobuf/compiler/plugin";
import { types } from "util";
import { PbULong } from "@protobuf-ts/runtime";
/**
* Base class for a protobuf plugin.
*
* Implement the abstract `generate()` method to create a plugin.
* The method takes a `CodeGeneratorRequest` and returns an
* array of `GeneratedFile` or a promise thereof.
*
*
* Usage:
*
* #!/usr/bin/env node
* const {MyPlugin} = require( ... );
* new MyPlugin.run().catch(_ => {
* process.stderr.write('failed to run plugin');
* process.exit(1);
* });
*
* Reads a `CodeGeneratorRequest` created by `protoc` from stdin,
* passes it to the plugin-function and writes a
* `CodeGeneratorResponse` to stdout.
*
*
* Options:
*
* Use the `parseOptions()` method the parse the parameter
* of a `CodeGeneratorRequest` to a map of flags. Options are
* validated and usage is generated on error.
*
*
* Error handling:
*
* `generate()` may raise an error, reject it's promise or
* return an `GeneratedFile` with an attached error.
*
* Throwing `new Error("hello")` will result in the output:
*
* $ protoc --xx_out=/tmp -I protos protos/*
* --xx_out: Error: hello
* at /path/to/your-plugin.js:69
* ...
*
*
*/
export class PluginBase {
run() {
return __awaiter(this, void 0, void 0, function* () {
try {
let response, bytes = yield this.readBytes(process.stdin), request = CodeGeneratorRequest.fromBinary(bytes);
try {
const files = yield this.generate(request);
response = this.createResponse(files);
}
catch (error) {
response = CodeGeneratorResponse.create({
error: this.errorToString(error)
});
}
this.setBlockingStdout();
process.stdout.write(CodeGeneratorResponse.toBinary(response));
}
catch (error) {
process.stderr.write('Plugin failed to read CodeGeneratorRequest from stdin or write CodeGeneratorResponse to stdout.\n');
process.stderr.write(this.errorToString(error));
process.stderr.write('\n');
process.exit(1);
}
});
}
getSupportedFeatures() {
return [];
}
parseOptions(spec, parameter) {
var _a, _b, _c, _d;
this.validateOptionsSpec(spec);
let given = parameter ? parameter.split(',') : [];
let known = Object.keys(spec);
let excess = given.filter(i => !known.includes(i));
if (excess.length > 0) {
this.throwOptionError(spec, `Option "${excess.join('", "')}" not recognized.`);
}
for (let [key, val] of Object.entries(spec)) {
if (given.includes(key)) {
let missing = (_b = (_a = val.requires) === null || _a === void 0 ? void 0 : _a.filter(i => !given.includes(i))) !== null && _b !== void 0 ? _b : [];
if (missing.length > 0) {
this.throwOptionError(spec, `Option "${key}" requires option "${missing.join('", "')}" to be set.`);
}
let excess = (_d = (_c = val.excludes) === null || _c === void 0 ? void 0 : _c.filter(i => given.includes(i))) !== null && _d !== void 0 ? _d : [];
if (excess.length > 0) {
this.throwOptionError(spec, `If option "${key}" is set, option "${excess.join('", "')}" cannot be set.`);
}
}
}
let resolved = {};
for (let key of Object.keys(spec)) {
resolved[key] = given.includes(key);
}
return resolved;
}
throwOptionError(spec, error) {
let text = '';
text += error + '\n';
text += `\n`;
text += `Available options:\n`;
text += `\n`;
for (let [key, val] of Object.entries(spec)) {
text += `- "${key}"\n`;
for (let l of val.description.split('\n')) {
text += ` ${l}\n`;
}
text += `\n`;
}
let err = new Error(text);
err.name = `ParameterError`;
throw err;
}
validateOptionsSpec(spec) {
var _a, _b;
let known = Object.keys(spec);
for (let [key, { excludes, requires }] of Object.entries(spec)) {
let r = (_a = requires === null || requires === void 0 ? void 0 : requires.filter(i => !known.includes(i))) !== null && _a !== void 0 ? _a : [];
if (r.length > 0) {
throw new Error(`Invalid parameter spec for parameter "${key}". "requires" points to unknown parameters: ${r.join(', ')}`);
}
let e = (_b = excludes === null || excludes === void 0 ? void 0 : excludes.filter(i => !known.includes(i))) !== null && _b !== void 0 ? _b : [];
if (e.length > 0) {
throw new Error(`Invalid parameter spec for parameter "${key}". "excludes" points to unknown parameters: ${e.join(', ')}`);
}
}
}
readBytes(stream) {
return new Promise(resolve => {
const chunks = [];
stream.on('data', chunk => chunks.push(chunk));
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
});
}
createResponse(files) {
// we have to respond with an xor of all of our supported features.
// we should be working on a ulong here, but we cannot rely on bigint support.
let feat = 0;
for (let f of this.getSupportedFeatures()) {
feat = feat ^ f;
}
return CodeGeneratorResponse.create({
file: files
.map(f => CodeGeneratorResponse_File.create({
name: f.getFilename(),
content: f.getContent()
}))
.filter(f => f.content && f.content.length > 0),
supportedFeatures: PbULong.from(feat).toString()
});
}
errorToString(error) {
var _a;
if (error && typeof error.name == 'string' && error.name == 'ParameterError') {
return error.name + '\n\n' + error.message;
}
if (error && typeof error.name == 'string' && error.name == 'PluginMessageError') {
return error.message;
}
if (types.isNativeError(error)) {
return (_a = error.stack) !== null && _a !== void 0 ? _a : error.toString();
}
let text;
try {
text = error.toString();
}
catch (e) {
text = 'unknown error';
}
return text;
}
setBlockingStdout() {
// Fixes https://github.com/timostamm/protobuf-ts/issues/134
// Node is buffering chunks to stdout, meaning that for big generated
// files the CodeGeneratorResponse will not reach protoc completely.
// To fix this, we set stdout to block using the internal private
// method setBlocking(true)
const stdoutHandle = process.stdout._handle;
if (stdoutHandle) {
stdoutHandle.setBlocking(true);
}
}
}
@@ -0,0 +1,240 @@
import { DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto } from "./google/protobuf/descriptor";
import { assert } from "@protobuf-ts/runtime";
export class SourceCodeInfoLookup {
constructor(parentResolver) {
this._parentResolver = parentResolver;
}
sourceCodeCursor(descriptor) {
var _a, _b;
const path = makeSourceCodePath(x => this._parentResolver(x), descriptor);
assert(path !== undefined, `Cannot create source code path`);
const all = (_b = (_a = this._findFile(descriptor).sourceCodeInfo) === null || _a === void 0 ? void 0 : _a.location) !== null && _b !== void 0 ? _b : [];
const hit = filterSourceCodeLocations(all, path);
return sourceCodeLocationToCursor(hit);
}
sourceCodeComments(descriptorOrFile, fileDescriptorFieldNumber) {
var _a, _b;
const path = makeSourceCodePath(x => this._parentResolver(x), descriptorOrFile);
assert(path !== undefined, `Cannot create source code path`);
if (fileDescriptorFieldNumber !== undefined) {
path.push(fileDescriptorFieldNumber);
}
const all = (_b = (_a = this._findFile(descriptorOrFile).sourceCodeInfo) === null || _a === void 0 ? void 0 : _a.location) !== null && _b !== void 0 ? _b : [];
const hit = filterSourceCodeLocations(all, path);
return sourceCodeLocationToComment(hit);
}
_findFile(d) {
let c = d;
while (c) {
if (FileDescriptorProto.is(c)) {
return c;
}
c = this._parentResolver(c);
}
assert(false);
}
}
/**
* Return cursor position of the given source code location
* as line number and column, both starting at 1.
*
* If more than one location is given, only the first one
* is evaluated, the others are discarded.
*/
export function sourceCodeLocationToCursor(locations) {
if (locations.length === 0) {
return emptyCursor;
}
const span = locations[0].span;
if (span === undefined || span.length < 3 || span.length > 4) {
return emptyCursor;
}
return [
span[0] + 1,
span[1] + 1
];
}
const emptyCursor = [undefined, undefined];
/**
* Return the comments for the given source code location.
*
* If more than one location is given, only the first one
* is evaluated, the others are discarded.
*
* If no comments found, empty (not undefined) object
* is returned.
*
* Trailing newlines are removed.
*/
export function sourceCodeLocationToComment(locations) {
if (locations.length === 0) {
return emptyComment;
}
const location = locations[0], leadingDetached = location.leadingDetachedComments.map(stripTrailingNewline), leadingComments = location.leadingComments, leading = leadingComments === ''
? undefined
: (leadingComments === undefined
? undefined
: stripTrailingNewline(leadingComments)), trailingComments = location.trailingComments, trailing = trailingComments === ''
? undefined
: (trailingComments === undefined
? undefined
: stripTrailingNewline(trailingComments));
return (leadingDetached.length === 0 && leading === undefined && trailing === undefined)
? emptyComment
: { leadingDetached, leading, trailing };
}
function stripTrailingNewline(block) {
return block.endsWith('\n')
? block.slice(0, -1)
: block;
}
const emptyComment = {
leadingDetached: [],
leading: undefined,
trailing: undefined,
};
/**
* Find the source code locations that match the given path.
*/
export function filterSourceCodeLocations(locations, path) {
return locations.filter(l => {
const p = l.path;
if (p.length !== path.length) {
return false;
}
for (let i = 0; i < p.length; i++) {
if (p[i] !== path[i]) {
return false;
}
}
return true;
});
}
/**
* Create the path to the source code location where the
* given element was declared.
*
* Returns `undefined` if we don't know how to make the path.
*
* For example, the path [4, 0, 2, 3] points to the 4th field
* of the first message of a .proto file:
*
* file
* .messageType // FileDescriptorProto.message_type = 3;
* [0] // first message
* .field // FileDescriptorProto.field = 2;
* [3] // 4th field
*
* See https://github.com/protocolbuffers/protobuf/blob/f1ce8663ac88df54cf212d29ce5123b69203b135/src/google/protobuf/descriptor.proto#L799
*/
export function makeSourceCodePath(parentProvider, descriptor) {
const path = [];
let parent = parentProvider(descriptor);
let component;
while (parent) {
component = makeSourceCodePathComponent(parent, descriptor);
if (component === undefined) {
return undefined;
}
path.unshift(...component);
descriptor = parent;
parent = parentProvider(parent);
}
return path;
}
/**
* Make a path from the parent to the immediate child.
*
* Returns `undefined` if we don't know how to make the path.
*/
export function makeSourceCodePathComponent(parent, child) {
if (FileDescriptorProto.is(parent) && DescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.message_type,
parent.messageType.indexOf(child)
];
}
if (FileDescriptorProto.is(parent) && EnumDescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.enum_type,
parent.enumType.indexOf(child)
];
}
if (FileDescriptorProto.is(parent) && ServiceDescriptorProto.is(child)) {
return [
FileDescriptorProtoFields.service,
parent.service.indexOf(child)
];
}
if (DescriptorProto.is(parent) && EnumDescriptorProto.is(child)) {
return [
DescriptorProtoFields.enum_type,
parent.enumType.indexOf(child)
];
}
if (DescriptorProto.is(parent) && DescriptorProto.is(child)) {
return [
DescriptorProtoFields.nested_type,
parent.nestedType.indexOf(child)
];
}
if (DescriptorProto.is(parent) && FieldDescriptorProto.is(child)) {
return [
DescriptorProtoFields.field,
parent.field.indexOf(child)
];
}
if (DescriptorProto.is(parent) && OneofDescriptorProto.is(child)) {
return [
DescriptorProtoFields.oneof_decl,
parent.oneofDecl.indexOf(child)
];
}
if (EnumDescriptorProto.is(parent) && EnumValueDescriptorProto.is(child)) {
return [
EnumDescriptorProtoFields.value,
parent.value.indexOf(child)
];
}
if (ServiceDescriptorProto.is(parent) && MethodDescriptorProto.is(child)) {
return [
ServiceDescriptorProtoFields.method,
parent.method.indexOf(child)
];
}
return undefined;
}
export var FileDescriptorProtoFields;
(function (FileDescriptorProtoFields) {
FileDescriptorProtoFields[FileDescriptorProtoFields["syntax"] = 12] = "syntax";
FileDescriptorProtoFields[FileDescriptorProtoFields["package"] = 2] = "package";
FileDescriptorProtoFields[FileDescriptorProtoFields["message_type"] = 4] = "message_type";
FileDescriptorProtoFields[FileDescriptorProtoFields["enum_type"] = 5] = "enum_type";
FileDescriptorProtoFields[FileDescriptorProtoFields["service"] = 6] = "service";
})(FileDescriptorProtoFields || (FileDescriptorProtoFields = {}));
var DescriptorProtoFields;
(function (DescriptorProtoFields) {
DescriptorProtoFields[DescriptorProtoFields["field"] = 2] = "field";
DescriptorProtoFields[DescriptorProtoFields["nested_type"] = 3] = "nested_type";
DescriptorProtoFields[DescriptorProtoFields["enum_type"] = 4] = "enum_type";
DescriptorProtoFields[DescriptorProtoFields["options"] = 7] = "options";
DescriptorProtoFields[DescriptorProtoFields["oneof_decl"] = 8] = "oneof_decl";
})(DescriptorProtoFields || (DescriptorProtoFields = {}));
// enum FieldDescriptorProtoFields {
// name = 1, // optional string name = 1;
// number = 3, // optional int32 number = 3;
// label = 4, // optional Label label = 4;
// type = 5, // optional Type type = 5;
// }
var EnumDescriptorProtoFields;
(function (EnumDescriptorProtoFields) {
// name = 1, // optional string name = 1;
EnumDescriptorProtoFields[EnumDescriptorProtoFields["value"] = 2] = "value";
// options = 3, // optional EnumOptions options = 3;
})(EnumDescriptorProtoFields || (EnumDescriptorProtoFields = {}));
var ServiceDescriptorProtoFields;
(function (ServiceDescriptorProtoFields) {
// name = 1, // optional string name = 1;
ServiceDescriptorProtoFields[ServiceDescriptorProtoFields["method"] = 2] = "method";
// options = 3, // optional ServiceOptions options = 3;
})(ServiceDescriptorProtoFields || (ServiceDescriptorProtoFields = {}));
@@ -0,0 +1,216 @@
import { DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FieldDescriptorProto_Type, FieldOptions_JSType, FileDescriptorProto, MethodDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto } from "./google/protobuf/descriptor";
import { isAnyTypeDescriptorProto } from "./descriptor-info";
import { assert, assertNever } from "@protobuf-ts/runtime";
export class StringFormat {
constructor(a, b, c, d) {
if (b === undefined) {
this.nameLookup = a;
this.treeLookup = a;
this.sourceCodeLookup = a;
this.descriptorInfo = a;
}
else {
this.nameLookup = a;
this.treeLookup = b;
this.sourceCodeLookup = c;
this.descriptorInfo = d;
}
}
/**
* Returns name of a scalar value type like it would
* appear in a .proto.
*
* For example, `FieldDescriptorProto_Type.UINT32` -> `"uint32"`.
*/
static formatScalarType(type) {
let name = FieldDescriptorProto_Type[type];
assert(name !== undefined, "unexpected ScalarValueType " + type);
return name.toLowerCase();
}
/**
* Returns type ('message', 'field', etc.) and descriptor name.
*
* Examples:
* message Bar
* field value = 2
* rpc Fetch()
*/
static formatName(descriptor) {
if (FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
}
else if (DescriptorProto.is(descriptor)) {
return `message ${descriptor.name}`;
}
else if (FieldDescriptorProto.is(descriptor)) {
if (descriptor.extendee !== undefined) {
return `extension field ${descriptor.name} = ${descriptor.number}`;
}
return `field ${descriptor.name} = ${descriptor.number}`;
}
else if (EnumDescriptorProto.is(descriptor)) {
return `enum ${descriptor.name}`;
}
else if (EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${descriptor.name} = ${descriptor.number}`;
}
else if (ServiceDescriptorProto.is(descriptor)) {
return `service ${descriptor.name}`;
}
else if (MethodDescriptorProto.is(descriptor)) {
return `rpc ${descriptor.name}()`;
}
else
// noinspection SuspiciousTypeOfGuard
if (OneofDescriptorProto.is(descriptor)) {
return `oneof ${descriptor.name}`;
}
assertNever(descriptor);
assert(false);
}
formatQualifiedName(descriptor, includeFileInfo) {
if (FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
}
const file = includeFileInfo ? ' in ' + getSourceWithLineNo(descriptor, this.treeLookup, this.sourceCodeLookup) : '';
if (DescriptorProto.is(descriptor)) {
return `message ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (EnumDescriptorProto.is(descriptor)) {
return `enum ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (ServiceDescriptorProto.is(descriptor)) {
return `service ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
let parent = this.treeLookup.parentOf(descriptor);
if (FieldDescriptorProto.is(descriptor) && this.descriptorInfo.isExtension(descriptor)) {
let extensionName = this.descriptorInfo.getExtensionName(descriptor);
assert(descriptor.extendee);
let extendeeTypeName = this.nameLookup.normalizeTypeName(descriptor.extendee);
return `extension ${extendeeTypeName}.(${extensionName})${file}`;
}
assert(isAnyTypeDescriptorProto(parent));
let parentTypeName = this.nameLookup.makeTypeName(parent);
if (FieldDescriptorProto.is(descriptor)) {
return `field ${parentTypeName}.${descriptor.name}${file}`;
}
if (EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${parentTypeName}.${descriptor.name}${file}`;
}
if (MethodDescriptorProto.is(descriptor)) {
return `rpc ${parentTypeName}.${descriptor.name}()${file}`;
}
return `oneof ${parentTypeName}.${descriptor.name}${file}`;
}
formatName(descriptor) {
return StringFormat.formatName(descriptor);
}
formatFieldDeclaration(descriptor) {
var _a, _b, _c, _d, _e;
let text = '';
// repeated ?
if (this.descriptorInfo.isUserDeclaredRepeated(descriptor)) {
text += 'repeated ';
}
// optional ?
if (this.descriptorInfo.isUserDeclaredOptional(descriptor)) {
text += 'optional ';
}
switch (descriptor.type) {
case FieldDescriptorProto_Type.ENUM:
text += this.nameLookup.makeTypeName(this.descriptorInfo.getEnumFieldEnum(descriptor));
break;
case FieldDescriptorProto_Type.MESSAGE:
if (this.descriptorInfo.isMapField(descriptor)) {
let mapK = StringFormat.formatScalarType(this.descriptorInfo.getMapKeyType(descriptor));
let mapVType = this.descriptorInfo.getMapValueType(descriptor);
let mapV = typeof mapVType === "number"
? StringFormat.formatScalarType(mapVType)
: this.nameLookup.makeTypeName(mapVType);
text += `map<${mapK}, ${mapV}>`;
}
else {
text += this.nameLookup.makeTypeName(this.descriptorInfo.getMessageFieldMessage(descriptor));
}
break;
case FieldDescriptorProto_Type.DOUBLE:
case FieldDescriptorProto_Type.FLOAT:
case FieldDescriptorProto_Type.INT64:
case FieldDescriptorProto_Type.UINT64:
case FieldDescriptorProto_Type.INT32:
case FieldDescriptorProto_Type.FIXED64:
case FieldDescriptorProto_Type.FIXED32:
case FieldDescriptorProto_Type.BOOL:
case FieldDescriptorProto_Type.STRING:
case FieldDescriptorProto_Type.BYTES:
case FieldDescriptorProto_Type.UINT32:
case FieldDescriptorProto_Type.SFIXED32:
case FieldDescriptorProto_Type.SFIXED64:
case FieldDescriptorProto_Type.SINT32:
case FieldDescriptorProto_Type.SINT64:
text += StringFormat.formatScalarType(descriptor.type);
break;
case FieldDescriptorProto_Type.GROUP:
text += "group";
break;
case FieldDescriptorProto_Type.UNSPECIFIED$:
text += "???";
break;
}
// name
text += ' ' + descriptor.name;
// number
text += ' = ' + descriptor.number;
// options
let options = [];
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
options.push('deprecated = true');
}
if (this.descriptorInfo.getFieldCustomJsonName(descriptor)) {
options.push(`json_name = "${this.descriptorInfo.getFieldCustomJsonName(descriptor)}"`);
}
if (((_a = descriptor.options) === null || _a === void 0 ? void 0 : _a.jstype) == FieldOptions_JSType.JS_STRING) {
options.push(`jstype = JS_STRING`);
}
if (((_b = descriptor.options) === null || _b === void 0 ? void 0 : _b.jstype) == FieldOptions_JSType.JS_NUMBER) {
options.push(`jstype = JS_NUMBER`);
}
if (((_c = descriptor.options) === null || _c === void 0 ? void 0 : _c.jstype) == FieldOptions_JSType.JS_NORMAL) {
options.push(`jstype = JS_NORMAL`);
}
if (((_d = descriptor.options) === null || _d === void 0 ? void 0 : _d.packed) === true) {
options.push(`packed = true`);
}
if (((_e = descriptor.options) === null || _e === void 0 ? void 0 : _e.packed) === false) {
options.push(`packed = false`);
}
if (options.length) {
text += ' [' + options.join(', ') + ']';
}
// semicolon
text += ';';
return text;
}
formatEnumValueDeclaration(descriptor) {
let text = `${descriptor.name} = ${descriptor.number}`;
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
text += ' [deprecated = true]';
}
return text + ';';
}
formatRpcDeclaration(descriptor) {
this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor);
let m = descriptor.name, i = descriptor.inputType, is = descriptor.clientStreaming ? 'stream ' : '', o = descriptor.outputType, os = descriptor.serverStreaming ? 'stream ' : '';
if (i.startsWith('.')) {
i = i.substring(1);
}
if (o.startsWith('.')) {
o = o.substring(1);
}
return `${m}(${is}${i}) returns (${os}${o});`;
}
}
function getSourceWithLineNo(descriptor, treeLookup, sourceCodeLookup) {
let file = treeLookup.fileOf(descriptor), [l] = sourceCodeLookup.sourceCodeCursor(descriptor);
return `${file.name}:${l}`;
}
@@ -0,0 +1,93 @@
import { StringFormat } from "./string-format";
/**
* A table for unique symbols (for any DescriptorProto, EnumDescriptorProto
* or ServiceDescriptorProto) in files (GeneratedFile).
*/
export class SymbolTable {
constructor(clashResolver) {
this.entries = [];
this.clashResolveMaxTries = 100;
this.hasNameInFile = (name, file) => this.entries.some(e => e.file === file && e.name === name);
this.clashResolver = clashResolver !== null && clashResolver !== void 0 ? clashResolver : SymbolTable.defaultClashResolver;
}
/**
* Register a symbol in the given file for the given descriptor.
*
* If the name is already taken in the file, an alternative name
* is automatically generated by appending '$' and a running
* number to the requested name. You can change the behaviour by
* providing your own `clashResolver`.
*
* Only one symbol per kind can be registered for a descriptor.
*
* If you want to generate an interface *and* a class for a
* message, use a different `kind` for each.
*
* Returns the actual name registered.
*/
register(requestedName, descriptor, file, kind = 'default') {
// Only one symbol per kind can be registered for a descriptor.
if (this.has(descriptor, kind)) {
let { file, name } = this.get(descriptor, kind);
let msg = `Cannot register name "${requestedName}" of kind "${kind}" for ${StringFormat.formatName(descriptor)}. `
+ `The descriptor is already registered in file "${file.getFilename()}" with name "${name}". `
+ `Use a different 'kind' to register multiple symbols for a descriptor.`;
throw new Error(msg);
}
// find a free name within the file
let name = requestedName;
let count = 0;
while (this.hasNameInFile(name, file) && count < this.clashResolveMaxTries) {
name = this.clashResolver(descriptor, file, requestedName, kind, ++count, name);
}
if (this.hasNameInFile(name, file)) {
let msg = `Failed to register name "${requestedName}" for ${StringFormat.formatName(descriptor)}. `
+ `Gave up finding alternative name after ${this.clashResolveMaxTries} tries. `
+ `There is something wrong with the clash resolver.`;
throw new Error(msg);
}
// add the entry and return name
this.entries.push({ file, descriptor, kind, name });
return name;
}
/**
* Find a symbol (of the given kind) for the given descriptor.
* Return `undefined` if not found.
*/
find(descriptor, kind = 'default') {
return this.entries.find(e => e.descriptor === descriptor && e.kind === kind);
}
/**
* Find a symbol (of the given kind) for the given descriptor.
* Raises error if not found.
*/
get(descriptor, kind = 'default') {
const found = this.find(descriptor, kind);
if (!found) {
let files = this.entries.map(e => e.file)
.filter((value, index, array) => array.indexOf(value) === index);
let msg = `Failed to find name for ${StringFormat.formatName(descriptor)} of kind "${kind}". `
+ `Searched in ${files.length} files.`;
throw new Error(msg);
}
return found;
}
/**
* Is a name (of the given kind) registered for the the given descriptor?
*/
has(descriptor, kind = 'default') {
return !!this.find(descriptor, kind);
}
list(file, kind) {
let matches = this.entries.filter(e => e.file === file);
if (kind !== undefined) {
matches = matches.filter(e => e.kind === kind);
}
return matches;
}
static defaultClashResolver(descriptor, file, requestedName, kind, tryCount) {
let n = requestedName;
n = n.endsWith('$') ? n.substring(1) : n;
return n + '$' + tryCount;
}
}
+86
View File
@@ -0,0 +1,86 @@
import { isAnyTypeDescriptorProto } from "./descriptor-info";
import { FileDescriptorProto } from "./google/protobuf/descriptor";
import { assert } from "@protobuf-ts/runtime";
export class TypeNameLookup {
constructor(data) {
const names = new Map();
const reverse = new Map();
for (let { descriptor, ancestors } of data) {
let name = composeTypeName([...ancestors, descriptor]);
assert(!names.has(name));
names.set(name, descriptor);
reverse.set(descriptor, name);
}
this._names = names;
this._reverse = reverse;
}
static from(a, b) {
let data = [];
if (Array.isArray(a) && b) {
for (let descriptor of a) {
if (!isAnyTypeDescriptorProto(descriptor)) {
continue;
}
let ancestors = [];
let p = b(descriptor);
while (p) {
ancestors.unshift(p);
p = b(descriptor);
}
data.push({ descriptor, ancestors });
}
}
else if (!Array.isArray(a) && !b) {
a.visitTypes(descriptor => {
data.push({ descriptor, ancestors: a.ancestorsOf(descriptor) });
});
}
else {
assert(false);
}
return new TypeNameLookup(data);
}
normalizeTypeName(typeName) {
return typeName.startsWith(".") ? typeName.substring(1) : typeName;
}
resolveTypeName(typeName) {
typeName = this.normalizeTypeName(typeName);
const d = this._names.get(typeName);
assert(d !== undefined, `Unable to resolve type name "${typeName}"`);
return d;
}
peekTypeName(typeName) {
typeName = this.normalizeTypeName(typeName);
return this._names.get(typeName);
}
makeTypeName(descriptor) {
const n = this._reverse.get(descriptor);
assert(n !== undefined);
return n;
}
}
/**
* Compose a fully qualified type name for enum,
* message or service.
*
* Example:
* my_package.MyMessage.MyNestedMessage
*
* Throws if given array is invalid.
*/
function composeTypeName(descriptors) {
assert(descriptors.length > 0);
const parts = [], mid = descriptors.concat(), first = mid.shift(), last = mid.pop();
assert(FileDescriptorProto.is(first));
assert(isAnyTypeDescriptorProto(last), "expected any type descriptor, got: " + typeof (last));
const pkg = first.package;
if (pkg !== undefined && pkg !== '') {
parts.push(pkg);
}
for (const item of [...mid, last]) {
let part = item.name;
assert(part !== undefined);
parts.push(part);
}
return parts.join('.');
}
@@ -0,0 +1,47 @@
import * as ts from "typescript";
/**
* Adds multiple comment blocks as line comments
* in front of the given node.
*
* Applies a dirty hack to enforce newlines
* between each block.
*/
export function addCommentBlocksAsLeadingDetachedLines(node, ...texts) {
for (let text of texts) {
let lines = text.split('\n').map(l => l[0] !== ' ' ? ` ${l}` : l);
for (let j = 0; j < lines.length; j++) {
const line = lines[j];
if (j === lines.length - 1) {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, line + '\n\n', false);
}
else {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, line, true);
}
}
}
}
/**
* Adds a JSDoc comment block in front of the given node.
*
* A JSDoc comment looks like this:
* /**
* * body text
* *\/
*
* A regular block comment looks like this:
* /* body text *\/
*
*/
export function addCommentBlockAsJsDoc(node, text) {
let lines = text
.split('\n')
.map(line => {
if (line[0] === ' ') {
return ' *' + line;
}
return ' * ' + line;
});
text = '*\n' + lines.join('\n') + '\n ';
text = text.split('*/').join('*\\/'); // need to escape a comment in the comment
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, text, true);
}
@@ -0,0 +1,119 @@
import * as ts from "typescript";
import * as path from "path";
export function setupCompiler(options, files, rootFileNames) {
const original = ts.createCompilerHost(options, true), host = new VirtualCompilerHost(original, files), libs = options.lib ? options.lib.map(lib => require.resolve(`typescript/lib/lib.${lib.toLowerCase()}.d.ts`)) : [], roots = rootFileNames.concat(libs), program = ts.createProgram(roots, options, host);
return [program, host];
}
class VirtualCompilerHost {
constructor(wrapped, files) {
this.wrapped = wrapped;
this._sourceFiles = new Map();
this._files = new Map();
this._dirs = new Set();
for (let vf of files) {
// create map from path to file
if (this._files.has(vf.getFilename())) {
throw new Error('Duplicate file paths in virtual files: ' + vf.getFilename());
}
this._files.set(vf.getFilename(), vf);
// create set of directory paths
let path = vf.getFilename().split('/');
while (path.length > 1) {
path.pop();
this._dirs.add(path.join('/'));
}
}
}
lookupVirtualFile(fileName) {
let vf = this._files.get(fileName);
if (vf)
return vf;
let cwd = process.cwd();
if (fileName.startsWith(cwd)) {
let relativePath = path.relative(cwd, fileName);
vf = this._files.get(relativePath);
if (vf)
return vf;
if (!relativePath.endsWith('.ts')) {
relativePath = relativePath += '.ts';
vf = this._files.get(relativePath);
if (vf)
return vf;
}
}
return undefined;
}
lookupVirtualDirectory(directoryName) {
let cwd = process.cwd();
if (directoryName.startsWith(cwd)) {
let relativePath = path.relative(cwd, directoryName);
return this._dirs.has(relativePath);
}
return false;
}
// noinspection JSUnusedGlobalSymbols
getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
const vf = this.lookupVirtualFile(fileName);
if (vf) {
let sf = this._sourceFiles.get(vf);
if (!sf) {
this._sourceFiles.set(vf, sf = ts.createSourceFile(vf.getFilename(), vf.getContent(), ts.ScriptTarget.Latest));
}
return sf;
}
return this.wrapped.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
}
// noinspection JSUnusedGlobalSymbols
getDefaultLibFileName(options) {
return this.wrapped.getDefaultLibFileName(options);
}
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles) {
// this.wrapped.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
}
// noinspection JSUnusedGlobalSymbols
getCurrentDirectory() {
return this.wrapped.getCurrentDirectory();
}
// noinspection JSUnusedGlobalSymbols
getCanonicalFileName(fileName) {
return this.wrapped.getCanonicalFileName(fileName);
}
// noinspection JSUnusedGlobalSymbols
useCaseSensitiveFileNames() {
return this.wrapped.useCaseSensitiveFileNames();
}
// noinspection JSUnusedGlobalSymbols
getNewLine() {
return this.wrapped.getNewLine();
}
// resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[], redirectedReference: ts.ResolvedProjectReference, options: ts.CompilerOptions): (ts.ResolvedModule | undefined)[] {
// resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ts.ResolvedProjectReference, options: ts.CompilerOptions): ts.ResolvedTypeReferenceDirective[] {
// noinspection JSUnusedGlobalSymbols
fileExists(fileName) {
return !!this.lookupVirtualFile(fileName) || this.wrapped.fileExists(fileName);
}
// noinspection JSUnusedGlobalSymbols
readFile(fileName) {
const vf = this.lookupVirtualFile(fileName);
if (vf)
return vf.getContent();
this.wrapped.readFile(fileName);
}
// noinspection JSUnusedGlobalSymbols
directoryExists(directoryName) {
if (this.lookupVirtualDirectory(directoryName))
return true;
const f = this.wrapped.directoryExists;
if (!f)
throw new Error('wrapped.directoryExists is undefined');
return f(directoryName);
}
// noinspection JSUnusedGlobalSymbols
getDirectories(path) {
const f = this.wrapped.getDirectories;
if (!f)
throw new Error('wrapped.getDirectories is undefined');
return f(path);
}
}
@@ -0,0 +1,38 @@
import * as ts from "typescript";
import * as rt from "@protobuf-ts/runtime";
import { addCommentBlockAsJsDoc } from "./typescript-comments";
/**
* Creates an enum declaration.
*/
export class TypescriptEnumBuilder {
constructor() {
this.values = [];
}
add(name, number, comment) {
this.values.push({ name, number, comment });
}
build(name, modifiers) {
this.validate();
const members = [];
for (let { name, number, comment } of this.values) {
let member = ts.createEnumMember(ts.createIdentifier(name), ts.createNumericLiteral(number.toString()));
if (comment) {
addCommentBlockAsJsDoc(member, comment);
}
members.push(member);
}
return ts.createEnumDeclaration(undefined, modifiers, name, members);
}
validate() {
if (this.values.map(v => v.name).some((name, i, a) => a.indexOf(name) !== i))
throw new Error("duplicate names");
let ei = {};
for (let v of this.values) {
ei[v.number] = v.name;
ei[v.name] = v.number;
}
if (!rt.isEnumObject(ei)) {
throw new Error("not a typescript enum object");
}
}
}
@@ -0,0 +1,38 @@
import * as ts from "typescript";
export class TypescriptFile {
constructor(filename) {
this.sf = ts.createSourceFile(filename, "", ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
}
getFilename() {
return this.sf.fileName;
}
/**
* Add the new statement to the file.
*/
addStatement(statement, atTop = false) {
const newStatements = atTop
? [statement, ...this.sf.statements]
: this.sf.statements.concat(statement);
this.sf = ts.updateSourceFileNode(this.sf, newStatements);
}
/**
* The underlying SourceFile
*/
getSourceFile() {
return this.sf;
}
/**
* Are there any statements in this file?
*/
isEmpty() {
return this.sf.statements.length === 0;
}
/**
* The full content of this file.
* Returns an empty string if there are no statements.
*/
getContent() {
let printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
return printer.printFile(this.sf);
}
}
@@ -0,0 +1,202 @@
import { assert } from "@protobuf-ts/runtime";
import * as ts from "typescript";
import * as path from "path";
/** @deprecated */
export class TypescriptImportManager {
constructor(generatedFile, symbols, source) {
this.file = generatedFile;
this.symbols = symbols;
this.source = source;
}
/**
* Import {importName} from "importFrom";
*
* Automatically finds a free name if the
* `importName` would collide with another
* identifier.
*
* Returns imported name.
*/
name(importName, importFrom) {
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(this.source.getSourceFile(), importName, importFrom, blackListedNames, statementToAdd => this.source.addStatement(statementToAdd, true));
}
/**
* Import * as importAs from "importFrom";
*
* Returns name for `importAs`.
*/
namespace(importAs, importFrom) {
return ensureNamespaceImportPresent(this.source.getSourceFile(), importAs, importFrom, statementToAdd => this.source.addStatement(statementToAdd, true));
}
/**
* Import a previously registered identifier for a message
* or other descriptor.
*
* Uses the symbol table to look for the type, adds an
* import statement if necessary and automatically finds a
* free name if the identifier would clash in this file.
*
* If you have multiple representations for a descriptor
* in your generated code, use `kind` to discriminate.
*/
type(descriptor, kind = 'default') {
const symbolReg = this.symbols.get(descriptor, kind);
// symbol in this file?
if (symbolReg.file === this.file) {
return symbolReg.name;
}
// symbol not in file
// add an import statement
const importPath = createRelativeImportPath(this.source.getSourceFile().fileName, symbolReg.file.getFilename());
const blackListedNames = this.symbols.list(this.file).map(e => e.name);
return ensureNamedImportPresent(this.source.getSourceFile(), symbolReg.name, importPath, blackListedNames, statementToAdd => this.source.addStatement(statementToAdd, true));
}
}
/**
* Import * as asName from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* Does *not* check for collisions.
*/
function ensureNamespaceImportPresent(currentFile, asName, importFrom, addStatementFn) {
const all = findNamespaceImports(currentFile), match = all.find(ni => ni.as === asName && ni.from === importFrom);
if (match) {
return match.as;
}
const statementToAdd = createNamespaceImport(asName, importFrom);
addStatementFn(statementToAdd);
return asName;
}
/**
* import * as <asName> from "<importFrom>";
*/
function createNamespaceImport(asName, importFrom) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(asName))), ts.createStringLiteral(importFrom));
}
/**
* import * as <as> from "<from>";
*/
function findNamespaceImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
assert(ts.isStringLiteral(s.moduleSpecifier));
r.push({
as: namedBindings.name.escapedText.toString(),
from: s.moduleSpecifier.text
});
}
}
}
return r;
}
/**
* Import {importName} from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* If the import name is taken by another named import
* or is in the list of blacklisted names, an
* alternative name is used:
*
* Import {importName as alternativeName} from "importFrom";
*
* Returns the imported name or the alternative name.
*/
function ensureNamedImportPresent(currentFile, importName, importFrom, blacklistedNames, addStatementFn, escapeCharacter = '$') {
var _a;
const all = findNamedImports(currentFile), taken = all.map(ni => { var _a; return (_a = ni.as) !== null && _a !== void 0 ? _a : ni.name; }).concat(blacklistedNames), match = all.find(ni => ni.name === importName && ni.from === importFrom);
if (match) {
return (_a = match.as) !== null && _a !== void 0 ? _a : match.name;
}
let as;
if (taken.includes(importName)) {
let i = 0;
as = importName;
while (taken.includes(as)) {
as = importName + escapeCharacter;
if (i++ > 0) {
as += i;
}
}
}
const statementToAdd = createNamedImport(importName, importFrom, as);
addStatementFn(statementToAdd);
return as !== null && as !== void 0 ? as : importName;
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function createNamedImport(name, from, as) {
if (as) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(ts.createIdentifier(name), ts.createIdentifier(as))]), false), ts.createStringLiteral(from));
}
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([
ts.createImportSpecifier(undefined, ts.createIdentifier(name))
])), ts.createStringLiteral(from));
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
*/
function findNamedImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
for (let importSpecifier of namedBindings.elements) {
assert(ts.isStringLiteral(s.moduleSpecifier));
if (importSpecifier.propertyName) {
r.push({
name: importSpecifier.propertyName.escapedText.toString(),
as: importSpecifier.name.escapedText.toString(),
from: s.moduleSpecifier.text
});
}
else {
r.push({
name: importSpecifier.name.escapedText.toString(),
as: undefined,
from: s.moduleSpecifier.text
});
}
}
}
}
}
return r;
}
/**
* Create a relative path for an import statement like
* `import {Foo} from "./foo"`
*/
function createRelativeImportPath(currentPath, pathToImportFrom) {
// create relative path to the file to import
let fromPath = path.relative(path.dirname(currentPath), pathToImportFrom);
// on windows, this may add backslash directory separators.
// we replace them with forward slash.
if (path.sep !== "/") {
fromPath = fromPath.split(path.sep).join("/");
}
// drop file extension
fromPath = fromPath.replace(/\.[a-z]+$/, '');
// make sure to start with './' to signal relative path to module resolution
if (!fromPath.startsWith('../') && !fromPath.startsWith('./')) {
fromPath = './' + fromPath;
}
return fromPath;
}
@@ -0,0 +1,207 @@
import { assert } from "@protobuf-ts/runtime";
import * as ts from "typescript";
import * as path from "path";
export class TypeScriptImports {
constructor(symbols) {
this.symbols = symbols;
}
/**
* Import {importName} from "importFrom";
*
* Automatically finds a free name if the
* `importName` would collide with another
* identifier.
*
* Returns imported name.
*/
name(source, importName, importFrom, isTypeOnly = false) {
const blackListedNames = this.symbols.list(source).map(e => e.name);
return ensureNamedImportPresent(source.getSourceFile(), importName, importFrom, isTypeOnly, blackListedNames, statementToAdd => source.addStatement(statementToAdd, true));
}
/**
* Import * as importAs from "importFrom";
*
* Returns name for `importAs`.
*/
namespace(source, importAs, importFrom, isTypeOnly = false) {
return ensureNamespaceImportPresent(source.getSourceFile(), importAs, importFrom, isTypeOnly, statementToAdd => source.addStatement(statementToAdd, true));
}
/**
* Import a previously registered identifier for a message
* or other descriptor.
*
* Uses the symbol table to look for the type, adds an
* import statement if necessary and automatically finds a
* free name if the identifier would clash in this file.
*
* If you have multiple representations for a descriptor
* in your generated code, use `kind` to discriminate.
*/
type(source, descriptor, kind = 'default', isTypeOnly = false) {
const symbolReg = this.symbols.get(descriptor, kind);
// symbol in this file?
if (symbolReg.file === source) {
return symbolReg.name;
}
// symbol not in file
// add an import statement
const importPath = createRelativeImportPath(source.getSourceFile().fileName, symbolReg.file.getFilename());
const blackListedNames = this.symbols.list(source).map(e => e.name);
return ensureNamedImportPresent(source.getSourceFile(), symbolReg.name, importPath, isTypeOnly, blackListedNames, statementToAdd => source.addStatement(statementToAdd, true));
}
}
/**
* Import * as asName from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* Does *not* check for collisions.
*/
function ensureNamespaceImportPresent(currentFile, asName, importFrom, isTypeOnly, addStatementFn) {
const all = findNamespaceImports(currentFile), match = all.find(ni => ni.as === asName && ni.from === importFrom && ni.isTypeOnly === isTypeOnly);
if (match) {
return match.as;
}
const statementToAdd = createNamespaceImport(asName, importFrom, isTypeOnly);
addStatementFn(statementToAdd);
return asName;
}
/**
* import * as <asName> from "<importFrom>";
*/
function createNamespaceImport(asName, importFrom, isTypeOnly) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(asName)), isTypeOnly), ts.createStringLiteral(importFrom));
}
/**
* import * as <as> from "<from>";
*/
function findNamespaceImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
assert(ts.isStringLiteral(s.moduleSpecifier));
r.push({
as: namedBindings.name.escapedText.toString(),
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly,
});
}
}
}
return r;
}
/**
* import {importName} from "importFrom";
* import type {importName} from "importFrom";
*
* If the import is already present, just return the
* identifier.
*
* If the import is not present, create the import
* statement and call `addStatementFn`.
*
* If the import name is taken by another named import
* or is in the list of blacklisted names, an
* alternative name is used:
*
* Import {importName as alternativeName} from "importFrom";
*
* Returns the imported name or the alternative name.
*/
export function ensureNamedImportPresent(currentFile, importName, importFrom, isTypeOnly, blacklistedNames, addStatementFn, escapeCharacter = '$') {
var _a;
const all = findNamedImports(currentFile), taken = all.map(ni => { var _a; return (_a = ni.as) !== null && _a !== void 0 ? _a : ni.name; }).concat(blacklistedNames), match = all.find(ni => ni.name === importName && ni.from === importFrom && ni.isTypeOnly === isTypeOnly);
if (match) {
return (_a = match.as) !== null && _a !== void 0 ? _a : match.name;
}
let as;
if (taken.includes(importName)) {
let i = 0;
as = importName;
while (taken.includes(as)) {
as = importName + escapeCharacter;
if (i++ > 0) {
as += i;
}
}
}
const statementToAdd = createNamedImport(importName, importFrom, as, isTypeOnly);
addStatementFn(statementToAdd);
return as !== null && as !== void 0 ? as : importName;
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
* import type {<name>} from '<from>';
* import type {<name> as <as>} from '<from>';
*/
export function createNamedImport(name, from, as, isTypeOnly = false) {
if (as) {
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(ts.createIdentifier(name), ts.createIdentifier(as))]), isTypeOnly), ts.createStringLiteral(from));
}
return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([
ts.createImportSpecifier(undefined, ts.createIdentifier(name))
]), isTypeOnly), ts.createStringLiteral(from));
}
/**
* import {<name>} from '<from>';
* import {<name> as <as>} from '<from>';
* import type {<name>} from '<from>';
* import type {<name> as <as>} from '<from>';
*/
export function findNamedImports(sourceFile) {
let r = [];
for (let s of sourceFile.statements) {
if (ts.isImportDeclaration(s) && s.importClause) {
let namedBindings = s.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
for (let importSpecifier of namedBindings.elements) {
assert(ts.isStringLiteral(s.moduleSpecifier));
if (importSpecifier.propertyName) {
r.push({
name: importSpecifier.propertyName.escapedText.toString(),
as: importSpecifier.name.escapedText.toString(),
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly
});
}
else {
r.push({
name: importSpecifier.name.escapedText.toString(),
as: undefined,
from: s.moduleSpecifier.text,
isTypeOnly: s.importClause.isTypeOnly
});
}
}
}
}
}
return r;
}
/**
* Create a relative path for an import statement like
* `import {Foo} from "./foo"`
*/
function createRelativeImportPath(currentPath, pathToImportFrom) {
// create relative path to the file to import
let fromPath = path.relative(path.dirname(currentPath), pathToImportFrom);
// on windows, this may add backslash directory separators.
// we replace them with forward slash.
if (path.sep !== "/") {
fromPath = fromPath.split(path.sep).join("/");
}
// drop file extension
fromPath = fromPath.replace(/\.[a-z]+$/, '');
// make sure to start with './' to signal relative path to module resolution
if (!fromPath.startsWith('../') && !fromPath.startsWith('./')) {
fromPath = './' + fromPath;
}
return fromPath;
}
@@ -0,0 +1,103 @@
import { assertNever } from "@protobuf-ts/runtime";
import * as ts from "typescript";
const validPropertyKey = /^(?![0-9])[a-zA-Z0-9$_]+$/;
/**
* Creates nodes for simple JavaScript values.
*
* Simple JavaScript values include:
* - all primitives: number, bigint, string, boolean
* - undefined, null
* - plain objects containing only simple JavaScript values
* - arrays containing only simple JavaScript values
* - typed arrays
*/
export function typescriptLiteralFromValue(value) {
switch (typeof value) {
case "undefined":
return ts.createIdentifier("undefined");
case "boolean":
return value ? ts.createTrue() : ts.createFalse();
case "string":
return ts.createStringLiteral(value);
case "bigint":
return ts.createNumericLiteral(`${value}n`);
case "number":
if (isNaN(value)) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("Nan"));
}
else if (value === Number.POSITIVE_INFINITY) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("POSITIVE_INFINITY"));
}
else if (value === Number.NEGATIVE_INFINITY) {
return ts.createPropertyAccess(ts.createIdentifier("Number"), ts.createIdentifier("NEGATIVE_INFINITY"));
}
return ts.createNumericLiteral(`${value}`);
case "object":
if (value === null) {
return ts.createNull();
}
if (isTypedArray(value)) {
if (value.length == 0) {
return ts.createNew(ts.createIdentifier(typedArrayName(value)), undefined, [ts.createNumericLiteral("0")]);
}
let values = [];
for (let i = 0; i < value.length; i++) {
values.push(ts.createNumericLiteral(value.toString()));
}
return ts.createNew(ts.createIdentifier(typedArrayName(value)), undefined, [ts.createArrayLiteral(values, false)]);
}
if (Array.isArray(value)) {
let elements = value.map(ele => typescriptLiteralFromValue(ele));
return ts.createArrayLiteral(elements, false);
}
if (value.constructor !== Object) {
throw new Error(`got a non-plain object ${value.constructor}`);
}
let props = [];
for (let key of Object.keys(value)) {
let propName = validPropertyKey.test(key) ? key : ts.createStringLiteral(key);
let propVal = typescriptLiteralFromValue(value[key]);
props.push(ts.createPropertyAssignment(propName, propVal));
}
return ts.createObjectLiteral(props, false);
}
assertNever(value);
}
function isTypedArray(arg) {
return arg instanceof Uint8Array
|| arg instanceof Int8Array
|| arg instanceof Uint8ClampedArray
|| arg instanceof Int16Array
|| arg instanceof Uint16Array
|| arg instanceof Int32Array
|| arg instanceof Uint32Array
|| arg instanceof Float32Array
|| arg instanceof Float64Array;
}
function typedArrayName(arg) {
if (arg instanceof Uint8Array) {
return 'Uint8Array';
}
if (arg instanceof Int8Array) {
return 'Int8Array';
}
if (arg instanceof Uint8ClampedArray) {
return 'Uint8ClampedArray';
}
if (arg instanceof Int16Array) {
return 'Int16Array';
}
if (arg instanceof Uint16Array) {
return 'Uint16Array';
}
if (arg instanceof Int32Array) {
return 'Int32Array';
}
if (arg instanceof Uint32Array) {
return 'Uint32Array';
}
if (arg instanceof Float32Array) {
return 'Float32Array';
}
return 'Float64Array';
}
@@ -0,0 +1,32 @@
import * as ts from "typescript";
import { addCommentBlockAsJsDoc } from "./typescript-comments";
/**
* Provide a function statement as plain text, receive a
* method declaration.
*/
export function typescriptMethodFromText(functionText) {
const sourceFile = ts.createSourceFile('temp.ts', functionText, ts.ScriptTarget.Latest);
if (sourceFile.statements.length !== 1) {
throw new Error('Expected exactly one statement, got ' + sourceFile.statements.length);
}
const node = sourceFile.statements[0];
if (!ts.isFunctionDeclaration(node)) {
throw new Error('Expected a function declaration');
}
if (node.name === undefined) {
throw new Error('function needs a name');
}
const method = ts.createMethod(node.decorators /*decorators*/, node.modifiers /*modifiers*/, node.asteriskToken /*asteriskToken*/, node.name, node.questionToken /*questionToken*/, node.typeParameters /*typeParameters*/, node.parameters, node.type /*return type*/, node.body);
ts.forEachLeadingCommentRange(functionText, node.getFullStart(), (pos, end) => {
let text = functionText.substring(pos, end);
text = text.trim();
if (text.startsWith('/*'))
text = text.substring(2);
if (text.endsWith('*/'))
text = text.substring(0, text.length - 2);
text = text.split('\n').map(l => l.replace(/^\s*\*/, '')).join('\n');
text = text.trim();
addCommentBlockAsJsDoc(method, text);
});
return method;
}
@@ -0,0 +1,239 @@
import { DescriptorProto, EnumDescriptorProto, EnumOptions, EnumValueDescriptorProto, EnumValueOptions, FieldDescriptorProto, FieldDescriptorProto_Type, FieldOptions, FileDescriptorProto, FileOptions, MessageOptions, MethodDescriptorProto, MethodOptions, OneofDescriptorProto, OneofOptions, ServiceDescriptorProto, ServiceOptions } from "./google/protobuf/descriptor";
import { ITypeNameLookup } from "./type-names";
import { IDescriptorTree } from "./descriptor-tree";
/**
* Union of all known descriptor proto.
*/
export declare type AnyDescriptorProto = FileDescriptorProto | DescriptorProto | FieldDescriptorProto | OneofDescriptorProto | EnumDescriptorProto | EnumValueDescriptorProto | ServiceDescriptorProto | MethodDescriptorProto;
/**
* Messages, enums and services are the only first-class
* types in the protobuf world.
*
* We assume that it should be possible to lookup these
* types by name.
*/
export declare type AnyTypeDescriptorProto = DescriptorProto | EnumDescriptorProto | ServiceDescriptorProto;
/**
* Union of all known descriptor options.
*/
export declare type AnyOptions = FileOptions | MessageOptions | FieldOptions | EnumOptions | OneofOptions | EnumValueOptions | ServiceOptions | MethodOptions;
/**
* Is this a first-class type?
*/
export declare function isAnyTypeDescriptorProto(arg: any): arg is AnyTypeDescriptorProto;
/**
* All scalar values types (which includes bytes)
* https://developers.google.com/protocol-buffers/docs/proto3#scalar_value_types
*/
export declare type ScalarValueType = Exclude<FieldDescriptorProto_Type, typeof FieldDescriptorProto_Type.UNSPECIFIED$ | typeof FieldDescriptorProto_Type.MESSAGE | typeof FieldDescriptorProto_Type.ENUM | typeof FieldDescriptorProto_Type.GROUP>;
/**
* Map field key type.
*
* The key_type can be any integral or string type
* (so, any scalar type except for floating point
* types and bytes)
*/
export declare type MapFieldKeyType = Exclude<FieldDescriptorProto_Type, typeof FieldDescriptorProto_Type.FLOAT | typeof FieldDescriptorProto_Type.DOUBLE | typeof FieldDescriptorProto_Type.BYTES | typeof FieldDescriptorProto_Type.UNSPECIFIED$ | typeof FieldDescriptorProto_Type.MESSAGE | typeof FieldDescriptorProto_Type.ENUM | typeof FieldDescriptorProto_Type.GROUP>;
/**
* Map field value type.
*
* Can be any scalar type, enum, or message.
*/
export declare type MapFieldValueType = DescriptorProto | EnumDescriptorProto | ScalarValueType;
export interface IDescriptorInfo {
/**
* Is this an extension field?
*/
isExtension(descriptor: FieldDescriptorProto): boolean;
/**
* Finds all extension fields extending the given message descriptor.
*/
extensionsFor(descriptorOrTypeName: DescriptorProto | string): FieldDescriptorProto[];
/**
* Get the name of an extension field, including the namespace
* where it was defined.
*
* For example, an extension field defined in the package "foo":
*
* ```proto
* extend google.protobuf.FieldOptions {
* bool opt = 1001;
* }
* ```
*
* Will have the extension name "foo.opt".
*
*/
getExtensionName(fieldDescriptor: FieldDescriptorProto): string;
/**
* Return the user-specified JSON name.
* Returns `undefined` if no name was specified or name
* equals lowerCamelCaseName.
*/
getFieldCustomJsonName(fieldDescriptor: FieldDescriptorProto): string | undefined;
/**
* Is this a enum field?
*/
isEnumField(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Get the enum descriptor for a enum field.
*/
getEnumFieldEnum(fieldDescriptor: FieldDescriptorProto): EnumDescriptorProto;
/**
* Is this a message field?
*
* Returns false if this is a map field, even though map fields have type MESSAGE.
*
* Before v2.0.0-alpha.23, this method returned true for group fields (type GROUP).
*/
isMessageField(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Is this a group field?
*
* Note that groups are deprecated and not supported in proto3.
*/
isGroupField(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Get the message descriptor for a message field.
*/
getMessageFieldMessage(fieldDescriptor: FieldDescriptorProto): DescriptorProto;
/**
* Is this a scalar field?
*/
isScalarField(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Get the scalar type of a scalar field.
*/
getScalarFieldType(fieldDescriptor: FieldDescriptorProto): ScalarValueType;
/**
* Is this a map field?
*/
isMapField(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Get the key type of a map field.
*/
getMapKeyType(fieldDescriptor: FieldDescriptorProto): MapFieldKeyType;
/**
* Get the value type (can be enum or message) of a map field.
*/
getMapValueType(fieldDescriptor: FieldDescriptorProto): DescriptorProto | EnumDescriptorProto | ScalarValueType;
/**
* Determines whether the user declared the field
* with `optional`.
*
* For proto2, the field descriptor's `label` is
* `LABEL_OPTIONAL`.
*
* For proto3, the field descriptor's `proto3_optional`
* is `true` and the field will be the sole member
* of a "synthetic" oneof.
*/
isUserDeclaredOptional(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Is this field declared as a oneof member by the user?
*
* When a field is declared `optional` in proto3, a
* "synthetic" oneof is generated by the compiler.
*/
isUserDeclaredOneof(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Determines whether the user declared the field
* with `repeated`.
*
* A map<K,V> for example cannot be repeated, but
* is internally represented as a repeated
* entry-message. This function recognizes this
* and returns false.
*/
isUserDeclaredRepeated(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Should this (repeated) field be encoded packed?
*
* Returns true if the user set [packed = true] or if syntax is proto3
* (and user did not explicitly disable default behaviour of proto3).
*
* Returns false if:
* - the field is not declared with `repeated`.
* - the user set [packed = false].
* - syntax is proto2 and there is no [packed = true].
*
* Throws if the field is `repeated` and type is `bytes` or `string`.
* This should have been a parse failure by protoc.
*/
shouldBePackedRepeated(fieldDescriptor: FieldDescriptorProto): boolean;
/**
* Is this element marked deprecated by the user?
*/
isExplicitlyDeclaredDeprecated(descriptor: AnyDescriptorProto): boolean;
/**
* Is the element intentionally created by the user
* or synthesized by the protobuf compiler?
*
* For example, the compiler generates an entry
* message for each map.
*/
isSyntheticElement(descriptor: AnyDescriptorProto): boolean;
/**
* Determine whether all enum value names start with the snake_case
* version of the enums name (enumLocalName or descriptor.name).
* If so, return the shared prefix. Otherwise, return undefined.
*
* For example, the following enum...
*
* ```proto
* enum MyEnum {
* MY_ENUM_FOO = 0;
* MY_ENUM_BAR = 1;
* }
* ```
*
* ... has the shared prefix "MY_ENUM_".
*/
findEnumSharedPrefix(enumDescriptor: EnumDescriptorProto, enumLocalName?: string): string | undefined;
/**
* Is a top-level type declared in the given file used anywhere the given
* "inFiles"?
*
* Returns true if a type from the file is used in a message field or
* method input or output.
*/
isFileUsed(file: FileDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
/**
* Is the given type used anywhere in the given "inFiles"?
*
* Returns true if the type is used in a message field or method input or
* output.
*/
isTypeUsed(type: AnyTypeDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
}
export declare class DescriptorInfo implements IDescriptorInfo {
private readonly tree;
private readonly nameLookup;
constructor(tree: IDescriptorTree, nameLookup: ITypeNameLookup);
private allExtensions;
private getAllExtensions;
isExtension(fieldDescriptor: FieldDescriptorProto): boolean;
extensionsFor(descriptorOrTypeName: DescriptorProto | string): FieldDescriptorProto[];
getExtensionName(fieldDescriptor: FieldDescriptorProto): string;
getFieldCustomJsonName(fieldDescriptor: FieldDescriptorProto): string | undefined;
isEnumField(fieldDescriptor: FieldDescriptorProto): boolean;
getEnumFieldEnum(fieldDescriptor: FieldDescriptorProto): EnumDescriptorProto;
isMessageField(fieldDescriptor: FieldDescriptorProto): boolean;
isGroupField(fieldDescriptor: FieldDescriptorProto): boolean;
getMessageFieldMessage(fieldDescriptor: FieldDescriptorProto): DescriptorProto;
isScalarField(fieldDescriptor: FieldDescriptorProto): boolean;
getScalarFieldType(fieldDescriptor: FieldDescriptorProto): ScalarValueType;
isMapField(fieldDescriptor: FieldDescriptorProto): boolean;
getMapKeyType(fieldDescriptor: FieldDescriptorProto): MapFieldKeyType;
getMapValueType(fieldDescriptor: FieldDescriptorProto): MapFieldValueType;
private getMapEntryMessage;
isExplicitlyDeclaredDeprecated(descriptor: AnyDescriptorProto): boolean;
isSyntheticElement(descriptor: AnyDescriptorProto): boolean;
isUserDeclaredOneof(fieldDescriptor: FieldDescriptorProto): boolean;
isUserDeclaredOptional(fieldDescriptor: FieldDescriptorProto): boolean;
isUserDeclaredRepeated(fieldDescriptor: FieldDescriptorProto): boolean;
shouldBePackedRepeated(fieldDescriptor: FieldDescriptorProto): boolean;
findEnumSharedPrefix(enumDescriptor: EnumDescriptorProto, enumLocalName?: string): string | undefined;
isFileUsed(file: FileDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
isTypeUsed(type: AnyTypeDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
}
@@ -0,0 +1,75 @@
import { DescriptorProto, EnumDescriptorProto, EnumOptions, EnumValueDescriptorProto, EnumValueOptions, FieldDescriptorProto, FieldOptions, FileDescriptorProto, FileOptions, MessageOptions, MethodDescriptorProto, MethodOptions, OneofDescriptorProto, OneofOptions, ServiceDescriptorProto, ServiceOptions } from "./google/protobuf/descriptor";
import { CodeGeneratorRequest } from "./google/protobuf/compiler/plugin";
import { AnyDescriptorProto, AnyTypeDescriptorProto, IDescriptorInfo, MapFieldKeyType, ScalarValueType } from "./descriptor-info";
import { IDescriptorTree } from "./descriptor-tree";
import { FileDescriptorProtoFields, ISourceCodeInfoLookup, SourceCodeComment, SourceCodeCursor } from "./source-code-info";
import { IStringFormat } from "./string-format";
import { ITypeNameLookup } from "./type-names";
export declare class DescriptorRegistry implements IDescriptorTree, ITypeNameLookup, ISourceCodeInfoLookup, IStringFormat, IDescriptorInfo {
private readonly tree;
private readonly typeNames;
private readonly sourceCode;
private readonly stringFormat;
private readonly descriptorInfo;
/**
* Create new registry from a FileDescriptorProto.
*/
static createFrom(file: FileDescriptorProto): DescriptorRegistry;
/**
* Create new registry from a CodeGeneratorRequest.
*/
static createFrom(request: CodeGeneratorRequest): DescriptorRegistry;
constructor(tree: IDescriptorTree, typeNames: ITypeNameLookup, sourceCode: ISourceCodeInfoLookup, stringFormat: IStringFormat, descriptorInfo: IDescriptorInfo);
normalizeTypeName(typeName: string): string;
resolveTypeName(typeName: string): AnyTypeDescriptorProto;
peekTypeName(typeName: string): AnyTypeDescriptorProto | undefined;
makeTypeName(descriptor: AnyTypeDescriptorProto): string;
ancestorsOf(descriptor: AnyDescriptorProto): AnyDescriptorProto[];
fileOf(descriptor: AnyDescriptorProto): FileDescriptorProto;
allFiles(): readonly FileDescriptorProto[];
parentOf(descriptor: FieldDescriptorProto): DescriptorProto;
parentOf(descriptor: AnyDescriptorProto): AnyDescriptorProto | undefined;
parentOf(options: FileOptions): FileDescriptorProto;
parentOf(options: MessageOptions): DescriptorProto;
parentOf(options: FieldOptions): FileDescriptorProto;
parentOf(options: OneofOptions): OneofDescriptorProto;
parentOf(options: EnumOptions): FieldDescriptorProto;
parentOf(options: EnumValueOptions): EnumValueDescriptorProto;
parentOf(options: ServiceOptions): ServiceDescriptorProto;
parentOf(options: MethodOptions): MethodDescriptorProto;
visit(visitor: (descriptor: AnyTypeDescriptorProto) => void): void;
visit(startingFrom: AnyDescriptorProto, visitor: (descriptor: AnyTypeDescriptorProto) => void): void;
visitTypes(visitor: (descriptor: AnyTypeDescriptorProto) => void): void;
visitTypes(startingFrom: AnyDescriptorProto, visitor: (descriptor: AnyTypeDescriptorProto) => void): void;
sourceCodeCursor(descriptor: AnyDescriptorProto): SourceCodeCursor;
sourceCodeComments(descriptor: AnyDescriptorProto): SourceCodeComment;
sourceCodeComments(file: FileDescriptorProto, field: FileDescriptorProtoFields): SourceCodeComment;
formatFieldDeclaration(descriptor: FieldDescriptorProto): string;
formatQualifiedName(descriptor: AnyDescriptorProto, includeFileInfo?: boolean): string;
formatName(descriptor: AnyDescriptorProto): string;
formatEnumValueDeclaration(descriptor: EnumValueDescriptorProto): string;
formatRpcDeclaration(descriptor: MethodDescriptorProto): string;
isExtension(descriptor: FieldDescriptorProto): boolean;
extensionsFor(descriptorOrTypeName: DescriptorProto | string): FieldDescriptorProto[];
getExtensionName(descriptor: FieldDescriptorProto): string;
getFieldCustomJsonName(descriptor: FieldDescriptorProto): string | undefined;
isEnumField(fieldDescriptor: FieldDescriptorProto): boolean;
getEnumFieldEnum(fieldDescriptor: FieldDescriptorProto): EnumDescriptorProto;
isMessageField(fieldDescriptor: FieldDescriptorProto): boolean;
isGroupField(fieldDescriptor: FieldDescriptorProto): boolean;
getMessageFieldMessage(fieldDescriptor: FieldDescriptorProto): DescriptorProto;
isScalarField(fieldDescriptor: FieldDescriptorProto): boolean;
getScalarFieldType(fieldDescriptor: FieldDescriptorProto): ScalarValueType;
isMapField(fieldDescriptor: FieldDescriptorProto): boolean;
getMapKeyType(fieldDescriptor: FieldDescriptorProto): MapFieldKeyType;
getMapValueType(fieldDescriptor: FieldDescriptorProto): DescriptorProto | EnumDescriptorProto | ScalarValueType;
isExplicitlyDeclaredDeprecated(descriptor: AnyDescriptorProto): boolean;
isSyntheticElement(descriptor: AnyDescriptorProto): boolean;
findEnumSharedPrefix(descriptor: EnumDescriptorProto, enumLocalName?: string): string | undefined;
isUserDeclaredOneof(descriptor: FieldDescriptorProto): boolean;
isUserDeclaredOptional(descriptor: FieldDescriptorProto): boolean;
isUserDeclaredRepeated(descriptor: FieldDescriptorProto): boolean;
shouldBePackedRepeated(descriptor: FieldDescriptorProto): boolean;
isFileUsed(file: FileDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
isTypeUsed(type: AnyTypeDescriptorProto, inFiles: FileDescriptorProto[]): boolean;
}

Some files were not shown because too many files have changed in this diff Show More