Initial commit
This commit is contained in:
+148
@@ -0,0 +1,148 @@
|
||||
import { BodyResponseCallback, DecorateRequestOptions, Metadata } from '@google-cloud/common';
|
||||
export interface AclOptions {
|
||||
pathPrefix: string;
|
||||
request: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void;
|
||||
}
|
||||
export declare type GetAclResponse = [AccessControlObject | AccessControlObject[], Metadata];
|
||||
export interface GetAclCallback {
|
||||
(err: Error | null, acl?: AccessControlObject | AccessControlObject[] | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface GetAclOptions {
|
||||
entity: string;
|
||||
generation?: number;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface UpdateAclOptions {
|
||||
entity: string;
|
||||
role: string;
|
||||
generation?: number;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type UpdateAclResponse = [AccessControlObject, Metadata];
|
||||
export interface UpdateAclCallback {
|
||||
(err: Error | null, acl?: AccessControlObject | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface AddAclOptions {
|
||||
entity: string;
|
||||
role: string;
|
||||
generation?: number;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type AddAclResponse = [AccessControlObject, Metadata];
|
||||
export interface AddAclCallback {
|
||||
(err: Error | null, acl?: AccessControlObject | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type RemoveAclResponse = [Metadata];
|
||||
export interface RemoveAclCallback {
|
||||
(err: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface RemoveAclOptions {
|
||||
entity: string;
|
||||
generation?: number;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface AccessControlObject {
|
||||
entity: string;
|
||||
role: string;
|
||||
projectTeam: string;
|
||||
}
|
||||
/**
|
||||
* Attach functionality to a {@link Storage.acl} instance. This will add an
|
||||
* object for each role group (owners, readers, and writers), with each object
|
||||
* containing methods to add or delete a type of entity.
|
||||
*
|
||||
* As an example, here are a few methods that are created.
|
||||
*
|
||||
* myBucket.acl.readers.deleteGroup('groupId', function(err) {});
|
||||
*
|
||||
* myBucket.acl.owners.addUser('[email protected]', function(err, acl) {});
|
||||
*
|
||||
* myBucket.acl.writers.addDomain('example.com', function(err, acl) {});
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
declare class AclRoleAccessorMethods {
|
||||
private static accessMethods;
|
||||
private static entities;
|
||||
private static roles;
|
||||
owners: {};
|
||||
readers: {};
|
||||
writers: {};
|
||||
constructor();
|
||||
_assignAccessMethods(role: string): void;
|
||||
}
|
||||
/**
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share objects with other
|
||||
* users and allow other users to access your buckets and objects.
|
||||
*
|
||||
* An ACL consists of one or more entries, where each entry grants permissions
|
||||
* to an entity. Permissions define the actions that can be performed against an
|
||||
* object or bucket (for example, `READ` or `WRITE`); the entity defines who the
|
||||
* permission applies to (for example, a specific user or group of users).
|
||||
*
|
||||
* Where an `entity` value is accepted, we follow the format the Cloud Storage
|
||||
* API expects.
|
||||
*
|
||||
* Refer to
|
||||
* https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls
|
||||
* for the most up-to-date values.
|
||||
*
|
||||
* - `user-userId`
|
||||
* - `user-email`
|
||||
* - `group-groupId`
|
||||
* - `group-email`
|
||||
* - `domain-domain`
|
||||
* - `project-team-projectId`
|
||||
* - `allUsers`
|
||||
* - `allAuthenticatedUsers`
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* - The user "[email protected]" would be `[email protected]`.
|
||||
* - The group "[email protected]" would be
|
||||
* `[email protected]`.
|
||||
* - To refer to all members of the Google Apps for Business domain
|
||||
* "example.com", the entity would be `domain-example.com`.
|
||||
*
|
||||
* For more detailed information, see
|
||||
* {@link http://goo.gl/6qBBPO| About Access Control Lists}.
|
||||
*
|
||||
* @constructor Acl
|
||||
* @mixin
|
||||
* @param {object} options Configuration options.
|
||||
*/
|
||||
declare class Acl extends AclRoleAccessorMethods {
|
||||
default: Acl;
|
||||
pathPrefix: string;
|
||||
request_: (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void;
|
||||
constructor(options: AclOptions);
|
||||
add(options: AddAclOptions): Promise<AddAclResponse>;
|
||||
add(options: AddAclOptions, callback: AddAclCallback): void;
|
||||
delete(options: RemoveAclOptions): Promise<RemoveAclResponse>;
|
||||
delete(options: RemoveAclOptions, callback: RemoveAclCallback): void;
|
||||
get(options?: GetAclOptions): Promise<GetAclResponse>;
|
||||
get(options: GetAclOptions, callback: GetAclCallback): void;
|
||||
get(callback: GetAclCallback): void;
|
||||
update(options: UpdateAclOptions): Promise<UpdateAclResponse>;
|
||||
update(options: UpdateAclOptions, callback: UpdateAclCallback): void;
|
||||
/**
|
||||
* Transform API responses to a consistent object format.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
makeAclObject_(accessControlObject: AccessControlObject): AccessControlObject;
|
||||
/**
|
||||
* Patch requests up to the bucket's request object.
|
||||
*
|
||||
* @private
|
||||
*
|
||||
* @param {string} method Action.
|
||||
* @param {string} path Request path.
|
||||
* @param {*} query Request query object.
|
||||
* @param {*} body Request body contents.
|
||||
* @param {function} callback Callback function.
|
||||
*/
|
||||
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
|
||||
}
|
||||
export { Acl, AclRoleAccessorMethods };
|
||||
+719
@@ -0,0 +1,719 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AclRoleAccessorMethods = exports.Acl = void 0;
|
||||
const promisify_1 = require("@google-cloud/promisify");
|
||||
const arrify = require("arrify");
|
||||
/**
|
||||
* Attach functionality to a {@link Storage.acl} instance. This will add an
|
||||
* object for each role group (owners, readers, and writers), with each object
|
||||
* containing methods to add or delete a type of entity.
|
||||
*
|
||||
* As an example, here are a few methods that are created.
|
||||
*
|
||||
* myBucket.acl.readers.deleteGroup('groupId', function(err) {});
|
||||
*
|
||||
* myBucket.acl.owners.addUser('[email protected]', function(err, acl) {});
|
||||
*
|
||||
* myBucket.acl.writers.addDomain('example.com', function(err, acl) {});
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
class AclRoleAccessorMethods {
|
||||
constructor() {
|
||||
this.owners = {};
|
||||
this.readers = {};
|
||||
this.writers = {};
|
||||
/**
|
||||
* An object of convenience methods to add or delete owner ACL permissions
|
||||
* for a given entity.
|
||||
*
|
||||
* The supported methods include:
|
||||
*
|
||||
* - `myFile.acl.owners.addAllAuthenticatedUsers`
|
||||
* - `myFile.acl.owners.deleteAllAuthenticatedUsers`
|
||||
* - `myFile.acl.owners.addAllUsers`
|
||||
* - `myFile.acl.owners.deleteAllUsers`
|
||||
* - `myFile.acl.owners.addDomain`
|
||||
* - `myFile.acl.owners.deleteDomain`
|
||||
* - `myFile.acl.owners.addGroup`
|
||||
* - `myFile.acl.owners.deleteGroup`
|
||||
* - `myFile.acl.owners.addProject`
|
||||
* - `myFile.acl.owners.deleteProject`
|
||||
* - `myFile.acl.owners.addUser`
|
||||
* - `myFile.acl.owners.deleteUser`
|
||||
*
|
||||
* @name Acl#owners
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* //-
|
||||
* // Add a user as an owner of a file.
|
||||
* //-
|
||||
* const myBucket = gcs.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
* myFile.acl.owners.addUser('[email protected]', function(err, aclObject)
|
||||
* {});
|
||||
*
|
||||
* //-
|
||||
* // For reference, the above command is the same as running the following.
|
||||
* //-
|
||||
* myFile.acl.add({
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.OWNER_ROLE
|
||||
* }, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myFile.acl.owners.addUser('[email protected]').then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
this.owners = {};
|
||||
/**
|
||||
* An object of convenience methods to add or delete reader ACL permissions
|
||||
* for a given entity.
|
||||
*
|
||||
* The supported methods include:
|
||||
*
|
||||
* - `myFile.acl.readers.addAllAuthenticatedUsers`
|
||||
* - `myFile.acl.readers.deleteAllAuthenticatedUsers`
|
||||
* - `myFile.acl.readers.addAllUsers`
|
||||
* - `myFile.acl.readers.deleteAllUsers`
|
||||
* - `myFile.acl.readers.addDomain`
|
||||
* - `myFile.acl.readers.deleteDomain`
|
||||
* - `myFile.acl.readers.addGroup`
|
||||
* - `myFile.acl.readers.deleteGroup`
|
||||
* - `myFile.acl.readers.addProject`
|
||||
* - `myFile.acl.readers.deleteProject`
|
||||
* - `myFile.acl.readers.addUser`
|
||||
* - `myFile.acl.readers.deleteUser`
|
||||
*
|
||||
* @name Acl#readers
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* //-
|
||||
* // Add a user as a reader of a file.
|
||||
* //-
|
||||
* myFile.acl.readers.addUser('[email protected]', function(err, aclObject)
|
||||
* {});
|
||||
*
|
||||
* //-
|
||||
* // For reference, the above command is the same as running the following.
|
||||
* //-
|
||||
* myFile.acl.add({
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.READER_ROLE
|
||||
* }, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myFile.acl.readers.addUser('[email protected]').then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
this.readers = {};
|
||||
/**
|
||||
* An object of convenience methods to add or delete writer ACL permissions
|
||||
* for a given entity.
|
||||
*
|
||||
* The supported methods include:
|
||||
*
|
||||
* - `myFile.acl.writers.addAllAuthenticatedUsers`
|
||||
* - `myFile.acl.writers.deleteAllAuthenticatedUsers`
|
||||
* - `myFile.acl.writers.addAllUsers`
|
||||
* - `myFile.acl.writers.deleteAllUsers`
|
||||
* - `myFile.acl.writers.addDomain`
|
||||
* - `myFile.acl.writers.deleteDomain`
|
||||
* - `myFile.acl.writers.addGroup`
|
||||
* - `myFile.acl.writers.deleteGroup`
|
||||
* - `myFile.acl.writers.addProject`
|
||||
* - `myFile.acl.writers.deleteProject`
|
||||
* - `myFile.acl.writers.addUser`
|
||||
* - `myFile.acl.writers.deleteUser`
|
||||
*
|
||||
* @name Acl#writers
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* //-
|
||||
* // Add a user as a writer of a file.
|
||||
* //-
|
||||
* myFile.acl.writers.addUser('[email protected]', function(err, aclObject)
|
||||
* {});
|
||||
*
|
||||
* //-
|
||||
* // For reference, the above command is the same as running the following.
|
||||
* //-
|
||||
* myFile.acl.add({
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.WRITER_ROLE
|
||||
* }, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myFile.acl.writers.addUser('[email protected]').then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
this.writers = {};
|
||||
AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this));
|
||||
}
|
||||
_assignAccessMethods(role) {
|
||||
const accessMethods = AclRoleAccessorMethods.accessMethods;
|
||||
const entities = AclRoleAccessorMethods.entities;
|
||||
const roleGroup = role.toLowerCase() + 's';
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
this[roleGroup] = entities.reduce((acc, entity) => {
|
||||
const isPrefix = entity.charAt(entity.length - 1) === '-';
|
||||
accessMethods.forEach(accessMethod => {
|
||||
let method = accessMethod + entity[0].toUpperCase() + entity.substr(1);
|
||||
if (isPrefix) {
|
||||
method = method.replace('-', '');
|
||||
}
|
||||
// Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the
|
||||
// more complex API of specifying an `entity` and `role`.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
acc[method] = (entityId, options, callback) => {
|
||||
let apiEntity;
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
if (isPrefix) {
|
||||
apiEntity = entity + entityId;
|
||||
}
|
||||
else {
|
||||
// If the entity is not a prefix, it is a special entity group
|
||||
// that does not require further details. The accessor methods
|
||||
// only accept a callback.
|
||||
apiEntity = entity;
|
||||
callback = entityId;
|
||||
}
|
||||
options = Object.assign({
|
||||
entity: apiEntity,
|
||||
role,
|
||||
}, options);
|
||||
const args = [options];
|
||||
if (typeof callback === 'function') {
|
||||
args.push(callback);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return this[accessMethod].apply(this, args);
|
||||
};
|
||||
});
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
}
|
||||
exports.AclRoleAccessorMethods = AclRoleAccessorMethods;
|
||||
AclRoleAccessorMethods.accessMethods = ['add', 'delete'];
|
||||
AclRoleAccessorMethods.entities = [
|
||||
// Special entity groups that do not require further specification.
|
||||
'allAuthenticatedUsers',
|
||||
'allUsers',
|
||||
// Entity groups that require specification, e.g. `[email protected]`.
|
||||
'domain-',
|
||||
'group-',
|
||||
'project-',
|
||||
'user-',
|
||||
];
|
||||
AclRoleAccessorMethods.roles = ['OWNER', 'READER', 'WRITER'];
|
||||
/**
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share objects with other
|
||||
* users and allow other users to access your buckets and objects.
|
||||
*
|
||||
* An ACL consists of one or more entries, where each entry grants permissions
|
||||
* to an entity. Permissions define the actions that can be performed against an
|
||||
* object or bucket (for example, `READ` or `WRITE`); the entity defines who the
|
||||
* permission applies to (for example, a specific user or group of users).
|
||||
*
|
||||
* Where an `entity` value is accepted, we follow the format the Cloud Storage
|
||||
* API expects.
|
||||
*
|
||||
* Refer to
|
||||
* https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls
|
||||
* for the most up-to-date values.
|
||||
*
|
||||
* - `user-userId`
|
||||
* - `user-email`
|
||||
* - `group-groupId`
|
||||
* - `group-email`
|
||||
* - `domain-domain`
|
||||
* - `project-team-projectId`
|
||||
* - `allUsers`
|
||||
* - `allAuthenticatedUsers`
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* - The user "[email protected]" would be `[email protected]`.
|
||||
* - The group "[email protected]" would be
|
||||
* `[email protected]`.
|
||||
* - To refer to all members of the Google Apps for Business domain
|
||||
* "example.com", the entity would be `domain-example.com`.
|
||||
*
|
||||
* For more detailed information, see
|
||||
* {@link http://goo.gl/6qBBPO| About Access Control Lists}.
|
||||
*
|
||||
* @constructor Acl
|
||||
* @mixin
|
||||
* @param {object} options Configuration options.
|
||||
*/
|
||||
class Acl extends AclRoleAccessorMethods {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.pathPrefix = options.pathPrefix;
|
||||
this.request_ = options.request;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} AddAclResponse
|
||||
* @property {object} 0 The Acl Objects.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback AddAclCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} acl The Acl Objects.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Add access controls on a {@link Bucket} or {@link File}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert| BucketAccessControls: insert API Documentation}
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation}
|
||||
*
|
||||
* @param {object} options Configuration options.
|
||||
* @param {string} options.entity Whose permissions will be added.
|
||||
* @param {string} options.role Permissions allowed for the defined entity.
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control Access
|
||||
* Control}.
|
||||
* @param {number} [options.generation] **File Objects Only** Select a specific
|
||||
* revision of this file (as opposed to the latest version, the default).
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {AddAclCallback} [callback] Callback function.
|
||||
* @returns {Promise<AddAclResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* const options = {
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.OWNER_ROLE
|
||||
* };
|
||||
*
|
||||
* myBucket.acl.add(options, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // For file ACL operations, you can also specify a `generation` property.
|
||||
* // Here is how you would grant ownership permissions to a user on a
|
||||
* specific
|
||||
* // revision of a file.
|
||||
* //-
|
||||
* myFile.acl.add({
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.OWNER_ROLE,
|
||||
* generation: 1
|
||||
* }, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myBucket.acl.add(options).then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_add_file_owner
|
||||
* Example of adding an owner to a file:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_add_bucket_owner
|
||||
* Example of adding an owner to a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_add_bucket_default_owner
|
||||
* Example of adding a default owner to a bucket:
|
||||
*/
|
||||
add(options, callback) {
|
||||
const query = {};
|
||||
if (options.generation) {
|
||||
query.generation = options.generation;
|
||||
}
|
||||
if (options.userProject) {
|
||||
query.userProject = options.userProject;
|
||||
}
|
||||
this.request({
|
||||
method: 'POST',
|
||||
uri: '',
|
||||
qs: query,
|
||||
json: {
|
||||
entity: options.entity,
|
||||
role: options.role.toUpperCase(),
|
||||
},
|
||||
}, (err, resp) => {
|
||||
if (err) {
|
||||
callback(err, null, resp);
|
||||
return;
|
||||
}
|
||||
callback(null, this.makeAclObject_(resp), resp);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @typedef {array} RemoveAclResponse
|
||||
* @property {object} 0 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback RemoveAclCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Delete access controls on a {@link Bucket} or {@link File}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete| BucketAccessControls: delete API Documentation}
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete| ObjectAccessControls: delete API Documentation}
|
||||
*
|
||||
* @param {object} options Configuration object.
|
||||
* @param {string} options.entity Whose permissions will be revoked.
|
||||
* @param {int} [options.generation] **File Objects Only** Select a specific
|
||||
* revision of this file (as opposed to the latest version, the default).
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {RemoveAclCallback} callback The callback function.
|
||||
* @returns {Promise<RemoveAclResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* myBucket.acl.delete({
|
||||
* entity: '[email protected]'
|
||||
* }, function(err, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // For file ACL operations, you can also specify a `generation` property.
|
||||
* //-
|
||||
* myFile.acl.delete({
|
||||
* entity: '[email protected]',
|
||||
* generation: 1
|
||||
* }, function(err, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myFile.acl.delete().then(function(data) {
|
||||
* const apiResponse = data[0];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_remove_bucket_owner
|
||||
* Example of removing an owner from a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_remove_bucket_default_owner
|
||||
* Example of removing a default owner from a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_remove_file_owner
|
||||
* Example of removing an owner from a bucket:
|
||||
*/
|
||||
delete(options, callback) {
|
||||
const query = {};
|
||||
if (options.generation) {
|
||||
query.generation = options.generation;
|
||||
}
|
||||
if (options.userProject) {
|
||||
query.userProject = options.userProject;
|
||||
}
|
||||
this.request({
|
||||
method: 'DELETE',
|
||||
uri: '/' + encodeURIComponent(options.entity),
|
||||
qs: query,
|
||||
}, (err, resp) => {
|
||||
callback(err, resp);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @typedef {array} GetAclResponse
|
||||
* @property {object|object[]} 0 Single or array of Acl Objects.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback GetAclCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object|object[]} acl Single or array of Acl Objects.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Get access controls on a {@link Bucket} or {@link File}. If
|
||||
* an entity is omitted, you will receive an array of all applicable access
|
||||
* controls.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get| BucketAccessControls: get API Documentation}
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get| ObjectAccessControls: get API Documentation}
|
||||
*
|
||||
* @param {object|function} [options] Configuration options. If you want to
|
||||
* receive a list of all access controls, pass the callback function as
|
||||
* the only argument.
|
||||
* @param {string} [options.entity] Whose permissions will be fetched.
|
||||
* @param {number} [options.generation] **File Objects Only** Select a specific
|
||||
* revision of this file (as opposed to the latest version, the default).
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {GetAclCallback} [callback] Callback function.
|
||||
* @returns {Promise<GetAclResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* myBucket.acl.get({
|
||||
* entity: '[email protected]'
|
||||
* }, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // Get all access controls.
|
||||
* //-
|
||||
* myBucket.acl.get(function(err, aclObjects, apiResponse) {
|
||||
* // aclObjects = [
|
||||
* // {
|
||||
* // entity: '[email protected]',
|
||||
* // role: 'owner'
|
||||
* // }
|
||||
* // ]
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // For file ACL operations, you can also specify a `generation` property.
|
||||
* //-
|
||||
* myFile.acl.get({
|
||||
* entity: '[email protected]',
|
||||
* generation: 1
|
||||
* }, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myBucket.acl.get().then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_file_acl
|
||||
* Example of printing a file's ACL:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_file_acl_for_user
|
||||
* Example of printing a file's ACL for a specific user:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_bucket_acl
|
||||
* Example of printing a bucket's ACL:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_bucket_acl_for_user
|
||||
* Example of printing a bucket's ACL for a specific user:
|
||||
*/
|
||||
get(optionsOrCallback, cb) {
|
||||
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null;
|
||||
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
|
||||
let path = '';
|
||||
const query = {};
|
||||
if (options) {
|
||||
path = '/' + encodeURIComponent(options.entity);
|
||||
if (options.generation) {
|
||||
query.generation = options.generation;
|
||||
}
|
||||
if (options.userProject) {
|
||||
query.userProject = options.userProject;
|
||||
}
|
||||
}
|
||||
this.request({
|
||||
uri: path,
|
||||
qs: query,
|
||||
}, (err, resp) => {
|
||||
if (err) {
|
||||
callback(err, null, resp);
|
||||
return;
|
||||
}
|
||||
let results;
|
||||
if (resp.items) {
|
||||
results = arrify(resp.items).map(this.makeAclObject_);
|
||||
}
|
||||
else {
|
||||
results = this.makeAclObject_(resp);
|
||||
}
|
||||
callback(null, results, resp);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @typedef {array} UpdateAclResponse
|
||||
* @property {object} 0 The updated Acl Objects.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback UpdateAclCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} acl The updated Acl Objects.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Update access controls on a {@link Bucket} or {@link File}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update| BucketAccessControls: update API Documentation}
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update| ObjectAccessControls: update API Documentation}
|
||||
*
|
||||
* @param {object} options Configuration options.
|
||||
* @param {string} options.entity Whose permissions will be updated.
|
||||
* @param {string} options.role Permissions allowed for the defined entity.
|
||||
* See {@link Storage.acl}.
|
||||
* @param {number} [options.generation] **File Objects Only** Select a specific
|
||||
* revision of this file (as opposed to the latest version, the default).
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {UpdateAclCallback} [callback] Callback function.
|
||||
* @returns {Promise<UpdateAclResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const storage = require('@google-cloud/storage')();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const myFile = myBucket.file('my-file');
|
||||
*
|
||||
* const options = {
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.WRITER_ROLE
|
||||
* };
|
||||
*
|
||||
* myBucket.acl.update(options, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // For file ACL operations, you can also specify a `generation` property.
|
||||
* //-
|
||||
* myFile.acl.update({
|
||||
* entity: '[email protected]',
|
||||
* role: gcs.acl.WRITER_ROLE,
|
||||
* generation: 1
|
||||
* }, function(err, aclObject, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myFile.acl.update(options).then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
update(options, callback) {
|
||||
const query = {};
|
||||
if (options.generation) {
|
||||
query.generation = options.generation;
|
||||
}
|
||||
if (options.userProject) {
|
||||
query.userProject = options.userProject;
|
||||
}
|
||||
this.request({
|
||||
method: 'PUT',
|
||||
uri: '/' + encodeURIComponent(options.entity),
|
||||
qs: query,
|
||||
json: {
|
||||
role: options.role.toUpperCase(),
|
||||
},
|
||||
}, (err, resp) => {
|
||||
if (err) {
|
||||
callback(err, null, resp);
|
||||
return;
|
||||
}
|
||||
callback(null, this.makeAclObject_(resp), resp);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Transform API responses to a consistent object format.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
makeAclObject_(accessControlObject) {
|
||||
const obj = {
|
||||
entity: accessControlObject.entity,
|
||||
role: accessControlObject.role,
|
||||
};
|
||||
if (accessControlObject.projectTeam) {
|
||||
obj.projectTeam = accessControlObject.projectTeam;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
/**
|
||||
* Patch requests up to the bucket's request object.
|
||||
*
|
||||
* @private
|
||||
*
|
||||
* @param {string} method Action.
|
||||
* @param {string} path Request path.
|
||||
* @param {*} query Request query object.
|
||||
* @param {*} body Request body contents.
|
||||
* @param {function} callback Callback function.
|
||||
*/
|
||||
request(reqOpts, callback) {
|
||||
reqOpts.uri = this.pathPrefix + reqOpts.uri;
|
||||
this.request_(reqOpts, callback);
|
||||
}
|
||||
}
|
||||
exports.Acl = Acl;
|
||||
/*! Developer Documentation
|
||||
*
|
||||
* All async methods (except for streams) will return a Promise in the event
|
||||
* that a callback is omitted.
|
||||
*/
|
||||
promisify_1.promisifyAll(Acl, {
|
||||
exclude: ['request'],
|
||||
});
|
||||
//# sourceMappingURL=acl.js.map
|
||||
+597
@@ -0,0 +1,597 @@
|
||||
/// <reference types="node" />
|
||||
import { ApiError, BodyResponseCallback, DecorateRequestOptions, DeleteCallback, ExistsCallback, GetConfig, Metadata, ResponseBody, ServiceObject } from '@google-cloud/common';
|
||||
import * as http from 'http';
|
||||
import { Acl } from './acl';
|
||||
import { Channel } from './channel';
|
||||
import { File, FileOptions, CreateResumableUploadOptions, CreateWriteStreamOptions } from './file';
|
||||
import { Iam } from './iam';
|
||||
import { Notification } from './notification';
|
||||
import { Storage, Cors, PreconditionOptions, BucketOptions } from './storage';
|
||||
import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, Query } from './signer';
|
||||
import { Readable } from 'stream';
|
||||
export declare type GetFilesResponse = [File[], {}, Metadata];
|
||||
export interface GetFilesCallback {
|
||||
(err: Error | null, files?: File[], nextQuery?: {}, apiResponse?: Metadata): void;
|
||||
}
|
||||
interface WatchAllOptions {
|
||||
delimiter?: string;
|
||||
maxResults?: number;
|
||||
pageToken?: string;
|
||||
prefix?: string;
|
||||
projection?: string;
|
||||
userProject?: string;
|
||||
versions?: boolean;
|
||||
}
|
||||
export interface AddLifecycleRuleOptions {
|
||||
append?: boolean;
|
||||
}
|
||||
export interface LifecycleRule {
|
||||
action: {
|
||||
type: string;
|
||||
storageClass?: string;
|
||||
} | string;
|
||||
condition: {
|
||||
[key: string]: boolean | Date | number | string;
|
||||
};
|
||||
storageClass?: string;
|
||||
}
|
||||
export interface EnableLoggingOptions {
|
||||
bucket?: string | Bucket;
|
||||
prefix: string;
|
||||
}
|
||||
export interface GetFilesOptions {
|
||||
autoPaginate?: boolean;
|
||||
delimiter?: string;
|
||||
/**
|
||||
* @deprecated dirrectory is deprecated
|
||||
* @internal
|
||||
* */
|
||||
directory?: string;
|
||||
endOffset?: string;
|
||||
includeTrailingDelimiter?: boolean;
|
||||
prefix?: string;
|
||||
maxApiCalls?: number;
|
||||
maxResults?: number;
|
||||
pageToken?: string;
|
||||
startOffset?: string;
|
||||
userProject?: string;
|
||||
versions?: boolean;
|
||||
}
|
||||
export interface CombineOptions extends PreconditionOptions {
|
||||
kmsKeyName?: string;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface CombineCallback {
|
||||
(err: Error | null, newFile: File | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export declare type CombineResponse = [File, Metadata];
|
||||
export interface CreateChannelConfig extends WatchAllOptions {
|
||||
address: string;
|
||||
}
|
||||
export interface CreateChannelOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type CreateChannelResponse = [Channel, Metadata];
|
||||
export interface CreateChannelCallback {
|
||||
(err: Error | null, channel: Channel | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export interface CreateNotificationOptions {
|
||||
customAttributes?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
eventTypes?: string[];
|
||||
objectNamePrefix?: string;
|
||||
payloadFormat?: string;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface CreateNotificationCallback {
|
||||
(err: Error | null, notification: Notification | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export declare type CreateNotificationResponse = [Notification, Metadata];
|
||||
export interface DeleteBucketOptions {
|
||||
ignoreNotFound?: boolean;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type DeleteBucketResponse = [Metadata];
|
||||
export interface DeleteBucketCallback extends DeleteCallback {
|
||||
(err: Error | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export interface DeleteFilesOptions extends GetFilesOptions, PreconditionOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
export interface DeleteFilesCallback {
|
||||
(err: Error | Error[] | null, apiResponse?: object): void;
|
||||
}
|
||||
export declare type DeleteLabelsResponse = [Metadata];
|
||||
export declare type DeleteLabelsCallback = SetLabelsCallback;
|
||||
export declare type DisableRequesterPaysResponse = [Metadata];
|
||||
export interface DisableRequesterPaysCallback {
|
||||
(err?: Error | null, apiResponse?: object): void;
|
||||
}
|
||||
export declare type EnableRequesterPaysResponse = [Metadata];
|
||||
export interface EnableRequesterPaysCallback {
|
||||
(err?: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface BucketExistsOptions extends GetConfig {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type BucketExistsResponse = [boolean];
|
||||
export declare type BucketExistsCallback = ExistsCallback;
|
||||
export interface GetBucketOptions extends GetConfig {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type GetBucketResponse = [Bucket, Metadata];
|
||||
export interface GetBucketCallback {
|
||||
(err: ApiError | null, bucket: Bucket | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export interface GetLabelsOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type GetLabelsResponse = [Metadata];
|
||||
export interface GetLabelsCallback {
|
||||
(err: Error | null, labels: object | null): void;
|
||||
}
|
||||
export declare type GetBucketMetadataResponse = [Metadata, Metadata];
|
||||
export interface GetBucketMetadataCallback {
|
||||
(err: ApiError | null, metadata: Metadata | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export interface GetBucketMetadataOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface GetBucketSignedUrlConfig {
|
||||
action: 'list';
|
||||
version?: 'v2' | 'v4';
|
||||
cname?: string;
|
||||
virtualHostedStyle?: boolean;
|
||||
expires: string | number | Date;
|
||||
extensionHeaders?: http.OutgoingHttpHeaders;
|
||||
queryParams?: Query;
|
||||
}
|
||||
export declare enum BucketActionToHTTPMethod {
|
||||
list = "GET"
|
||||
}
|
||||
export declare enum AvailableServiceObjectMethods {
|
||||
setMetadata = 0,
|
||||
delete = 1
|
||||
}
|
||||
export interface GetNotificationsOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface GetNotificationsCallback {
|
||||
(err: Error | null, notifications: Notification[] | null, apiResponse: Metadata): void;
|
||||
}
|
||||
export declare type GetNotificationsResponse = [Notification[], Metadata];
|
||||
export interface MakeBucketPrivateOptions {
|
||||
includeFiles?: boolean;
|
||||
force?: boolean;
|
||||
metadata?: Metadata;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type MakeBucketPrivateResponse = [File[]];
|
||||
export interface MakeBucketPrivateCallback {
|
||||
(err?: Error | null, files?: File[]): void;
|
||||
}
|
||||
export interface MakeBucketPublicOptions {
|
||||
includeFiles?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
export interface MakeBucketPublicCallback {
|
||||
(err?: Error | null, files?: File[]): void;
|
||||
}
|
||||
export declare type MakeBucketPublicResponse = [File[]];
|
||||
export interface SetBucketMetadataOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type SetBucketMetadataResponse = [Metadata];
|
||||
export interface SetBucketMetadataCallback {
|
||||
(err?: Error | null, metadata?: Metadata): void;
|
||||
}
|
||||
export interface BucketLockCallback {
|
||||
(err?: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type BucketLockResponse = [Metadata];
|
||||
export interface Labels {
|
||||
[key: string]: string;
|
||||
}
|
||||
export interface SetLabelsOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type SetLabelsResponse = [Metadata];
|
||||
export interface SetLabelsCallback {
|
||||
(err?: Error | null, metadata?: Metadata): void;
|
||||
}
|
||||
export interface SetBucketStorageClassOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface SetBucketStorageClassCallback {
|
||||
(err?: Error | null): void;
|
||||
}
|
||||
export declare type UploadResponse = [File, Metadata];
|
||||
export interface UploadCallback {
|
||||
(err: Error | null, file?: File | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface UploadOptions extends CreateResumableUploadOptions, CreateWriteStreamOptions {
|
||||
destination?: string | File;
|
||||
encryptionKey?: string | Buffer;
|
||||
kmsKeyName?: string;
|
||||
resumable?: boolean;
|
||||
timeout?: number;
|
||||
onUploadProgress?: (progressEvent: any) => void;
|
||||
}
|
||||
export interface MakeAllFilesPublicPrivateOptions {
|
||||
force?: boolean;
|
||||
private?: boolean;
|
||||
public?: boolean;
|
||||
userProject?: string;
|
||||
}
|
||||
interface MakeAllFilesPublicPrivateCallback {
|
||||
(err?: Error | Error[] | null, files?: File[]): void;
|
||||
}
|
||||
declare type MakeAllFilesPublicPrivateResponse = [File[]];
|
||||
/**
|
||||
* Get and set IAM policies for your bucket.
|
||||
*
|
||||
* @name Bucket#iam
|
||||
* @mixes Iam
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
|
||||
* See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
|
||||
* See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
*
|
||||
* //-
|
||||
* // Get the IAM policy for your bucket.
|
||||
* //-
|
||||
* bucket.iam.getPolicy(function(err, policy) {
|
||||
* console.log(policy);
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* bucket.iam.getPolicy().then(function(data) {
|
||||
* const policy = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_view_bucket_iam_members
|
||||
* Example of retrieving a bucket's IAM policy:
|
||||
*
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_add_bucket_iam_member
|
||||
* Example of adding to a bucket's IAM policy:
|
||||
*
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_remove_bucket_iam_member
|
||||
* Example of removing from a bucket's IAM policy:
|
||||
*/
|
||||
/**
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share objects with other
|
||||
* users and allow other users to access your buckets and objects.
|
||||
*
|
||||
* An ACL consists of one or more entries, where each entry grants permissions
|
||||
* to an entity. Permissions define the actions that can be performed against
|
||||
* an object or bucket (for example, `READ` or `WRITE`); the entity defines
|
||||
* who the permission applies to (for example, a specific user or group of
|
||||
* users).
|
||||
*
|
||||
* The `acl` object on a Bucket instance provides methods to get you a list of
|
||||
* the ACLs defined on your bucket, as well as set, update, and delete them.
|
||||
*
|
||||
* Buckets also have
|
||||
* {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
|
||||
* for all created files. Default ACLs specify permissions that all new
|
||||
* objects added to the bucket will inherit by default. You can add, delete,
|
||||
* get, and update entities and permissions for these as well with
|
||||
* {@link Bucket#acl.default}.
|
||||
*
|
||||
* See {@link http://goo.gl/6qBBPO| About Access Control Lists}
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs}
|
||||
*
|
||||
* @name Bucket#acl
|
||||
* @mixes Acl
|
||||
* @property {Acl} default Cloud Storage Buckets have
|
||||
* {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
|
||||
* for all created files. You can add, delete, get, and update entities and
|
||||
* permissions for these as well. The method signatures and examples are all
|
||||
* the same, after only prefixing the method call with `default`.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
*
|
||||
* //-
|
||||
* // Make a bucket's contents publicly readable.
|
||||
* //-
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const options = {
|
||||
* entity: 'allUsers',
|
||||
* role: storage.acl.READER_ROLE
|
||||
* };
|
||||
*
|
||||
* myBucket.acl.add(options, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* myBucket.acl.add(options).then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_bucket_acl
|
||||
* Example of printing a bucket's ACL:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_print_bucket_acl_for_user
|
||||
* Example of printing a bucket's ACL for a specific user:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_add_bucket_owner
|
||||
* Example of adding an owner to a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_remove_bucket_owner
|
||||
* Example of removing an owner from a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_add_bucket_default_owner
|
||||
* Example of adding a default owner to a bucket:
|
||||
*
|
||||
* @example <caption>include:samples/acl.js</caption>
|
||||
* region_tag:storage_remove_bucket_default_owner
|
||||
* Example of removing a default owner from a bucket:
|
||||
*/
|
||||
/**
|
||||
* The API-formatted resource description of the bucket.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name Bucket#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* The bucket's name.
|
||||
* @name Bucket#name
|
||||
* @type {string}
|
||||
*/
|
||||
/**
|
||||
* Get {@link File} objects for the files currently in the bucket as a
|
||||
* readable object stream.
|
||||
*
|
||||
* @method Bucket#getFilesStream
|
||||
* @param {GetFilesOptions} [query] Query object for listing files.
|
||||
* @returns {ReadableStream} A readable stream that emits {@link File} instances.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
*
|
||||
* bucket.getFilesStream()
|
||||
* .on('error', console.error)
|
||||
* .on('data', function(file) {
|
||||
* // file is a File object.
|
||||
* })
|
||||
* .on('end', function() {
|
||||
* // All files retrieved.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If you anticipate many results, you can end a stream early to prevent
|
||||
* // unnecessary processing and API requests.
|
||||
* //-
|
||||
* bucket.getFilesStream()
|
||||
* .on('data', function(file) {
|
||||
* this.end();
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If you're filtering files with a delimiter, you should use
|
||||
* // {@link Bucket#getFiles} and set `autoPaginate: false` in order to
|
||||
* // preserve the `apiResponse` argument.
|
||||
* //-
|
||||
* const prefixes = [];
|
||||
*
|
||||
* function callback(err, files, nextQuery, apiResponse) {
|
||||
* prefixes = prefixes.concat(apiResponse.prefixes);
|
||||
*
|
||||
* if (nextQuery) {
|
||||
* bucket.getFiles(nextQuery, callback);
|
||||
* } else {
|
||||
* // prefixes = The finished array of prefixes.
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* bucket.getFiles({
|
||||
* autoPaginate: false,
|
||||
* delimiter: '/'
|
||||
* }, callback);
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* Create a Bucket object to interact with a Cloud Storage bucket.
|
||||
*
|
||||
* @class
|
||||
* @hideconstructor
|
||||
*
|
||||
* @param {Storage} storage A {@link Storage} instance.
|
||||
* @param {string} name The name of the bucket.
|
||||
* @param {object} [options] Configuration object.
|
||||
* @param {string} [options.userProject] User project.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
* ```
|
||||
*/
|
||||
declare class Bucket extends ServiceObject {
|
||||
metadata: Metadata;
|
||||
name: string;
|
||||
/**
|
||||
* A reference to the {@link Storage} associated with this {@link Bucket}
|
||||
* instance.
|
||||
* @name Bucket#storage
|
||||
* @type {Storage}
|
||||
*/
|
||||
storage: Storage;
|
||||
/**
|
||||
* A user project to apply to each request from this bucket.
|
||||
* @name Bucket#userProject
|
||||
* @type {string}
|
||||
*/
|
||||
userProject?: string;
|
||||
acl: Acl;
|
||||
iam: Iam;
|
||||
getFilesStream(query?: GetFilesOptions): Readable;
|
||||
signer?: URLSigner;
|
||||
private instanceRetryValue?;
|
||||
private instancePreconditionOpts?;
|
||||
constructor(storage: Storage, name: string, options?: BucketOptions);
|
||||
addLifecycleRule(rule: LifecycleRule, options?: AddLifecycleRuleOptions): Promise<SetBucketMetadataResponse>;
|
||||
addLifecycleRule(rule: LifecycleRule, options: AddLifecycleRuleOptions, callback: SetBucketMetadataCallback): void;
|
||||
addLifecycleRule(rule: LifecycleRule, callback: SetBucketMetadataCallback): void;
|
||||
combine(sources: string[] | File[], destination: string | File, options?: CombineOptions): Promise<CombineResponse>;
|
||||
combine(sources: string[] | File[], destination: string | File, options: CombineOptions, callback: CombineCallback): void;
|
||||
combine(sources: string[] | File[], destination: string | File, callback: CombineCallback): void;
|
||||
createChannel(id: string, config: CreateChannelConfig, options?: CreateChannelOptions): Promise<CreateChannelResponse>;
|
||||
createChannel(id: string, config: CreateChannelConfig, callback: CreateChannelCallback): void;
|
||||
createChannel(id: string, config: CreateChannelConfig, options: CreateChannelOptions, callback: CreateChannelCallback): void;
|
||||
createNotification(topic: string, options?: CreateNotificationOptions): Promise<CreateNotificationResponse>;
|
||||
createNotification(topic: string, options: CreateNotificationOptions, callback: CreateNotificationCallback): void;
|
||||
createNotification(topic: string, callback: CreateNotificationCallback): void;
|
||||
deleteFiles(query?: DeleteFilesOptions): Promise<void>;
|
||||
deleteFiles(callback: DeleteFilesCallback): void;
|
||||
deleteFiles(query: DeleteFilesOptions, callback: DeleteFilesCallback): void;
|
||||
deleteLabels(labels?: string | string[]): Promise<DeleteLabelsResponse>;
|
||||
deleteLabels(callback: DeleteLabelsCallback): void;
|
||||
deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void;
|
||||
disableRequesterPays(): Promise<DisableRequesterPaysResponse>;
|
||||
disableRequesterPays(callback: DisableRequesterPaysCallback): void;
|
||||
enableLogging(config: EnableLoggingOptions): Promise<SetBucketMetadataResponse>;
|
||||
enableLogging(config: EnableLoggingOptions, callback: SetBucketMetadataCallback): void;
|
||||
enableRequesterPays(): Promise<EnableRequesterPaysResponse>;
|
||||
enableRequesterPays(callback: EnableRequesterPaysCallback): void;
|
||||
/**
|
||||
* Create a {@link File} object. See {@link File} to see how to handle
|
||||
* the different use cases you may have.
|
||||
*
|
||||
* @param {string} name The name of the file in this bucket.
|
||||
* @param {FileOptions} [options] Configuration options.
|
||||
* @param {string|number} [options.generation] Only use a specific revision of
|
||||
* this file.
|
||||
* @param {string} [options.encryptionKey] A custom encryption key. See
|
||||
* {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
|
||||
* @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
|
||||
* be used to encrypt the object. Must be in the format:
|
||||
* `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
|
||||
* KMS key ring must use the same location as the bucket.
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for all requests made from File object.
|
||||
* @returns {File}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
* const file = bucket.file('my-existing-file.png');
|
||||
* ```
|
||||
*/
|
||||
file(name: string, options?: FileOptions): File;
|
||||
getFiles(query?: GetFilesOptions): Promise<GetFilesResponse>;
|
||||
getFiles(query: GetFilesOptions, callback: GetFilesCallback): void;
|
||||
getFiles(callback: GetFilesCallback): void;
|
||||
getLabels(options?: GetLabelsOptions): Promise<GetLabelsResponse>;
|
||||
getLabels(callback: GetLabelsCallback): void;
|
||||
getLabels(options: GetLabelsOptions, callback: GetLabelsCallback): void;
|
||||
getNotifications(options?: GetNotificationsOptions): Promise<GetNotificationsResponse>;
|
||||
getNotifications(callback: GetNotificationsCallback): void;
|
||||
getNotifications(options: GetNotificationsOptions, callback: GetNotificationsCallback): void;
|
||||
getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise<GetSignedUrlResponse>;
|
||||
getSignedUrl(cfg: GetBucketSignedUrlConfig, callback: GetSignedUrlCallback): void;
|
||||
lock(metageneration: number | string): Promise<BucketLockResponse>;
|
||||
lock(metageneration: number | string, callback: BucketLockCallback): void;
|
||||
makePrivate(options?: MakeBucketPrivateOptions): Promise<MakeBucketPrivateResponse>;
|
||||
makePrivate(callback: MakeBucketPrivateCallback): void;
|
||||
makePrivate(options: MakeBucketPrivateOptions, callback: MakeBucketPrivateCallback): void;
|
||||
makePublic(options?: MakeBucketPublicOptions): Promise<MakeBucketPublicResponse>;
|
||||
makePublic(callback: MakeBucketPublicCallback): void;
|
||||
makePublic(options: MakeBucketPublicOptions, callback: MakeBucketPublicCallback): void;
|
||||
/**
|
||||
* Get a reference to a Cloud Pub/Sub Notification.
|
||||
*
|
||||
* @param {string} id ID of notification.
|
||||
* @returns {Notification}
|
||||
* @see Notification
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
* const notification = bucket.notification('1');
|
||||
* ```
|
||||
*/
|
||||
notification(id: string): Notification;
|
||||
removeRetentionPeriod(): Promise<SetBucketMetadataResponse>;
|
||||
removeRetentionPeriod(callback: SetBucketMetadataCallback): void;
|
||||
request(reqOpts: DecorateRequestOptions): Promise<[ResponseBody, Metadata]>;
|
||||
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
|
||||
setLabels(labels: Labels, options?: SetLabelsOptions): Promise<SetLabelsResponse>;
|
||||
setLabels(labels: Labels, callback: SetLabelsCallback): void;
|
||||
setLabels(labels: Labels, options: SetLabelsOptions, callback: SetLabelsCallback): void;
|
||||
setRetentionPeriod(duration: number): Promise<SetBucketMetadataResponse>;
|
||||
setRetentionPeriod(duration: number, callback: SetBucketMetadataCallback): void;
|
||||
setCorsConfiguration(corsConfiguration: Cors[]): Promise<SetBucketMetadataResponse>;
|
||||
setCorsConfiguration(corsConfiguration: Cors[], callback: SetBucketMetadataCallback): void;
|
||||
setStorageClass(storageClass: string, options?: SetBucketStorageClassOptions): Promise<SetBucketMetadataResponse>;
|
||||
setStorageClass(storageClass: string, callback: SetBucketStorageClassCallback): void;
|
||||
setStorageClass(storageClass: string, options: SetBucketStorageClassOptions, callback: SetBucketStorageClassCallback): void;
|
||||
/**
|
||||
* Set a user project to be billed for all requests made from this Bucket
|
||||
* object and any files referenced from this Bucket object.
|
||||
*
|
||||
* @param {string} userProject The user project.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
*
|
||||
* bucket.setUserProject('grape-spaceship-123');
|
||||
* ```
|
||||
*/
|
||||
setUserProject(userProject: string): void;
|
||||
upload(pathString: string, options?: UploadOptions): Promise<UploadResponse>;
|
||||
upload(pathString: string, options: UploadOptions, callback: UploadCallback): void;
|
||||
upload(pathString: string, callback: UploadCallback): void;
|
||||
makeAllFilesPublicPrivate_(options?: MakeAllFilesPublicPrivateOptions): Promise<MakeAllFilesPublicPrivateResponse>;
|
||||
makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void;
|
||||
makeAllFilesPublicPrivate_(options: MakeAllFilesPublicPrivateOptions, callback: MakeAllFilesPublicPrivateCallback): void;
|
||||
getId(): string;
|
||||
disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods): void;
|
||||
}
|
||||
/**
|
||||
* Reference to the {@link Bucket} class.
|
||||
* @name module:@google-cloud/storage.Bucket
|
||||
* @see Bucket
|
||||
*/
|
||||
export { Bucket };
|
||||
+3326
File diff suppressed because it is too large
Load Diff
+33
@@ -0,0 +1,33 @@
|
||||
import { Metadata, ServiceObject } from '@google-cloud/common';
|
||||
import { Storage } from './storage';
|
||||
export interface StopCallback {
|
||||
(err: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* Create a channel object to interact with a Cloud Storage channel.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification}
|
||||
*
|
||||
* @class
|
||||
*
|
||||
* @param {string} id The ID of the channel.
|
||||
* @param {string} resourceId The resource ID of the channel.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const channel = storage.channel('id', 'resource-id');
|
||||
* ```
|
||||
*/
|
||||
declare class Channel extends ServiceObject {
|
||||
constructor(storage: Storage, id: string, resourceId: string);
|
||||
stop(): Promise<Metadata>;
|
||||
stop(callback: StopCallback): void;
|
||||
}
|
||||
/**
|
||||
* Reference to the {@link Channel} class.
|
||||
* @name module:@google-cloud/storage.Channel
|
||||
* @see Channel
|
||||
*/
|
||||
export { Channel };
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Channel = void 0;
|
||||
const common_1 = require("@google-cloud/common");
|
||||
const promisify_1 = require("@google-cloud/promisify");
|
||||
/**
|
||||
* Create a channel object to interact with a Cloud Storage channel.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification}
|
||||
*
|
||||
* @class
|
||||
*
|
||||
* @param {string} id The ID of the channel.
|
||||
* @param {string} resourceId The resource ID of the channel.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const channel = storage.channel('id', 'resource-id');
|
||||
* ```
|
||||
*/
|
||||
class Channel extends common_1.ServiceObject {
|
||||
constructor(storage, id, resourceId) {
|
||||
const config = {
|
||||
parent: storage,
|
||||
baseUrl: '/channels',
|
||||
// An ID shouldn't be included in the API requests.
|
||||
// RE:
|
||||
// https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145
|
||||
id: '',
|
||||
methods: {
|
||||
// Only need `request`.
|
||||
},
|
||||
};
|
||||
super(config);
|
||||
// TODO: remove type cast to any once ServiceObject's type declaration has
|
||||
// been fixed. https://github.com/googleapis/nodejs-common/issues/176
|
||||
const metadata = this.metadata;
|
||||
metadata.id = id;
|
||||
metadata.resourceId = resourceId;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} StopResponse
|
||||
* @property {object} 0 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback StopCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Stop this channel.
|
||||
*
|
||||
* @param {StopCallback} [callback] Callback function.
|
||||
* @returns {Promise<StopResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const channel = storage.channel('id', 'resource-id');
|
||||
* channel.stop(function(err, apiResponse) {
|
||||
* if (!err) {
|
||||
* // Channel stopped successfully.
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* channel.stop().then(function(data) {
|
||||
* const apiResponse = data[0];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
stop(callback) {
|
||||
callback = callback || common_1.util.noop;
|
||||
this.request({
|
||||
method: 'POST',
|
||||
uri: '/stop',
|
||||
json: this.metadata,
|
||||
}, (err, apiResponse) => {
|
||||
callback(err, apiResponse);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Channel = Channel;
|
||||
/*! Developer Documentation
|
||||
*
|
||||
* All async methods (except for streams) will return a Promise in the event
|
||||
* that a callback is omitted.
|
||||
*/
|
||||
promisify_1.promisifyAll(Channel);
|
||||
//# sourceMappingURL=channel.js.map
|
||||
+795
@@ -0,0 +1,795 @@
|
||||
/// <reference types="node" />
|
||||
import { BodyResponseCallback, DecorateRequestOptions, GetConfig, Metadata, ServiceObject } from '@google-cloud/common';
|
||||
import { Writable, Readable } from 'stream';
|
||||
import * as http from 'http';
|
||||
import { PreconditionOptions, Storage } from './storage';
|
||||
import { AvailableServiceObjectMethods, Bucket } from './bucket';
|
||||
import { Acl } from './acl';
|
||||
import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, Query } from './signer';
|
||||
import { ResponseBody, Duplexify } from '@google-cloud/common/build/src/util';
|
||||
export declare type GetExpirationDateResponse = [Date];
|
||||
export interface GetExpirationDateCallback {
|
||||
(err: Error | null, expirationDate?: Date | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface PolicyDocument {
|
||||
string: string;
|
||||
base64: string;
|
||||
signature: string;
|
||||
}
|
||||
export declare type GetSignedPolicyResponse = [PolicyDocument];
|
||||
export interface GetSignedPolicyCallback {
|
||||
(err: Error | null, policy?: PolicyDocument): void;
|
||||
}
|
||||
export interface GetSignedPolicyOptions {
|
||||
equals?: string[] | string[][];
|
||||
expires: string | number | Date;
|
||||
startsWith?: string[] | string[][];
|
||||
acl?: string;
|
||||
successRedirect?: string;
|
||||
successStatus?: string;
|
||||
contentLengthRange?: {
|
||||
min?: number;
|
||||
max?: number;
|
||||
};
|
||||
}
|
||||
export declare type GenerateSignedPostPolicyV2Options = GetSignedPolicyOptions;
|
||||
export declare type GenerateSignedPostPolicyV2Response = GetSignedPolicyResponse;
|
||||
export declare type GenerateSignedPostPolicyV2Callback = GetSignedPolicyCallback;
|
||||
export interface PolicyFields {
|
||||
[key: string]: string;
|
||||
}
|
||||
export interface GenerateSignedPostPolicyV4Options {
|
||||
expires: string | number | Date;
|
||||
bucketBoundHostname?: string;
|
||||
virtualHostedStyle?: boolean;
|
||||
conditions?: object[];
|
||||
fields?: PolicyFields;
|
||||
}
|
||||
export interface GenerateSignedPostPolicyV4Callback {
|
||||
(err: Error | null, output?: SignedPostPolicyV4Output): void;
|
||||
}
|
||||
export declare type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output];
|
||||
export interface SignedPostPolicyV4Output {
|
||||
url: string;
|
||||
fields: PolicyFields;
|
||||
}
|
||||
export interface GetSignedUrlConfig {
|
||||
action: 'read' | 'write' | 'delete' | 'resumable';
|
||||
version?: 'v2' | 'v4';
|
||||
virtualHostedStyle?: boolean;
|
||||
cname?: string;
|
||||
contentMd5?: string;
|
||||
contentType?: string;
|
||||
expires: string | number | Date;
|
||||
accessibleAt?: string | number | Date;
|
||||
extensionHeaders?: http.OutgoingHttpHeaders;
|
||||
promptSaveAs?: string;
|
||||
responseDisposition?: string;
|
||||
responseType?: string;
|
||||
queryParams?: Query;
|
||||
}
|
||||
export interface GetFileMetadataOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type GetFileMetadataResponse = [Metadata, Metadata];
|
||||
export interface GetFileMetadataCallback {
|
||||
(err: Error | null, metadata?: Metadata, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface GetFileOptions extends GetConfig {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type GetFileResponse = [File, Metadata];
|
||||
export interface GetFileCallback {
|
||||
(err: Error | null, file?: File, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface FileExistsOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type FileExistsResponse = [boolean];
|
||||
export interface FileExistsCallback {
|
||||
(err: Error | null, exists?: boolean): void;
|
||||
}
|
||||
export interface DeleteFileOptions {
|
||||
ignoreNotFound?: boolean;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type DeleteFileResponse = [Metadata];
|
||||
export interface DeleteFileCallback {
|
||||
(err: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
|
||||
export interface CreateResumableUploadOptions {
|
||||
configPath?: string;
|
||||
metadata?: Metadata;
|
||||
origin?: string;
|
||||
offset?: number;
|
||||
predefinedAcl?: PredefinedAcl;
|
||||
private?: boolean;
|
||||
public?: boolean;
|
||||
uri?: string;
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export declare type CreateResumableUploadResponse = [string];
|
||||
export interface CreateResumableUploadCallback {
|
||||
(err: Error | null, uri?: string): void;
|
||||
}
|
||||
export interface CreateWriteStreamOptions extends CreateResumableUploadOptions {
|
||||
contentType?: string;
|
||||
gzip?: string | boolean;
|
||||
resumable?: boolean;
|
||||
timeout?: number;
|
||||
validation?: string | boolean;
|
||||
}
|
||||
export interface MakeFilePrivateOptions {
|
||||
metadata?: Metadata;
|
||||
strict?: boolean;
|
||||
userProject?: string;
|
||||
}
|
||||
export declare type MakeFilePrivateResponse = [Metadata];
|
||||
export declare type MakeFilePrivateCallback = SetFileMetadataCallback;
|
||||
export interface IsPublicCallback {
|
||||
(err: Error | null, resp?: boolean): void;
|
||||
}
|
||||
export declare type IsPublicResponse = [boolean];
|
||||
export declare type MakeFilePublicResponse = [Metadata];
|
||||
export interface MakeFilePublicCallback {
|
||||
(err?: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type MoveResponse = [Metadata];
|
||||
export interface MoveCallback {
|
||||
(err: Error | null, destinationFile?: File | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface MoveOptions {
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export declare type RenameOptions = MoveOptions;
|
||||
export declare type RenameResponse = MoveResponse;
|
||||
export declare type RenameCallback = MoveCallback;
|
||||
export declare type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions;
|
||||
export interface EncryptionKeyOptions {
|
||||
encryptionKey?: string | Buffer;
|
||||
kmsKeyName?: string;
|
||||
}
|
||||
export declare type RotateEncryptionKeyCallback = CopyCallback;
|
||||
export declare type RotateEncryptionKeyResponse = CopyResponse;
|
||||
export declare enum ActionToHTTPMethod {
|
||||
read = "GET",
|
||||
write = "PUT",
|
||||
delete = "DELETE",
|
||||
resumable = "POST"
|
||||
}
|
||||
/**
|
||||
* @const {string}
|
||||
* @private
|
||||
*/
|
||||
export declare const STORAGE_POST_POLICY_BASE_URL = "https://storage.googleapis.com";
|
||||
export interface FileOptions {
|
||||
encryptionKey?: string | Buffer;
|
||||
generation?: number | string;
|
||||
kmsKeyName?: string;
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export interface CopyOptions {
|
||||
cacheControl?: string;
|
||||
contentEncoding?: string;
|
||||
contentType?: string;
|
||||
contentDisposition?: string;
|
||||
destinationKmsKeyName?: string;
|
||||
metadata?: Metadata;
|
||||
predefinedAcl?: string;
|
||||
token?: string;
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export declare type CopyResponse = [File, Metadata];
|
||||
export interface CopyCallback {
|
||||
(err: Error | null, file?: File | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type DownloadResponse = [Buffer];
|
||||
export declare type DownloadCallback = (err: RequestError | null, contents: Buffer) => void;
|
||||
export interface DownloadOptions extends CreateReadStreamOptions {
|
||||
destination?: string;
|
||||
}
|
||||
export interface CreateReadStreamOptions {
|
||||
userProject?: string;
|
||||
validation?: 'md5' | 'crc32c' | false | true;
|
||||
start?: number;
|
||||
end?: number;
|
||||
decompress?: boolean;
|
||||
}
|
||||
export interface SaveOptions extends CreateWriteStreamOptions {
|
||||
onUploadProgress?: (progressEvent: any) => void;
|
||||
}
|
||||
export interface SaveCallback {
|
||||
(err?: Error | null): void;
|
||||
}
|
||||
export interface SetFileMetadataOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface SetFileMetadataCallback {
|
||||
(err?: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type SetFileMetadataResponse = [Metadata];
|
||||
export declare type SetStorageClassResponse = [Metadata];
|
||||
export interface SetStorageClassOptions {
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export interface SetStorageClassCallback {
|
||||
(err?: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
declare class RequestError extends Error {
|
||||
code?: string;
|
||||
errors?: Error[];
|
||||
}
|
||||
/**
|
||||
* A File object is created from your {@link Bucket} object using
|
||||
* {@link Bucket#file}.
|
||||
*
|
||||
* @class
|
||||
*/
|
||||
declare class File extends ServiceObject<File> {
|
||||
acl: Acl;
|
||||
bucket: Bucket;
|
||||
storage: Storage;
|
||||
kmsKeyName?: string;
|
||||
userProject?: string;
|
||||
signer?: URLSigner;
|
||||
metadata: Metadata;
|
||||
name: string;
|
||||
generation?: number;
|
||||
parent: Bucket;
|
||||
private encryptionKey?;
|
||||
private encryptionKeyBase64?;
|
||||
private encryptionKeyHash?;
|
||||
private encryptionKeyInterceptor?;
|
||||
private instanceRetryValue?;
|
||||
instancePreconditionOpts?: PreconditionOptions;
|
||||
/**
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share objects with other
|
||||
* users and allow other users to access your buckets and objects.
|
||||
*
|
||||
* An ACL consists of one or more entries, where each entry grants permissions
|
||||
* to an entity. Permissions define the actions that can be performed against
|
||||
* an object or bucket (for example, `READ` or `WRITE`); the entity defines
|
||||
* who the permission applies to (for example, a specific user or group of
|
||||
* users).
|
||||
*
|
||||
* The `acl` object on a File instance provides methods to get you a list of
|
||||
* the ACLs defined on your bucket, as well as set, update, and delete them.
|
||||
*
|
||||
* See {@link http://goo.gl/6qBBPO| About Access Control lists}
|
||||
*
|
||||
* @name File#acl
|
||||
* @mixes Acl
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const file = myBucket.file('my-file');
|
||||
* //-
|
||||
* // Make a file publicly readable.
|
||||
* //-
|
||||
* const options = {
|
||||
* entity: 'allUsers',
|
||||
* role: storage.acl.READER_ROLE
|
||||
* };
|
||||
*
|
||||
* file.acl.add(options, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* file.acl.add(options).then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* The API-formatted resource description of the file.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name File#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* The file's name.
|
||||
* @name File#name
|
||||
* @type {string}
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} FileOptions Options passed to the File constructor.
|
||||
* @property {string} [encryptionKey] A custom encryption key.
|
||||
* @property {number} [generation] Generation to scope the file to.
|
||||
* @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
|
||||
* object, if the object is encrypted by such a key. Limited availability;
|
||||
* usable only by enabled projects.
|
||||
* @property {string} [userProject] The ID of the project which will be
|
||||
* billed for all requests made from File object.
|
||||
*/
|
||||
/**
|
||||
* Constructs a file object.
|
||||
*
|
||||
* @param {Bucket} bucket The Bucket instance this file is
|
||||
* attached to.
|
||||
* @param {string} name The name of the remote file.
|
||||
* @param {FileOptions} [options] Configuration options.
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const file = myBucket.file('my-file');
|
||||
* ```
|
||||
*/
|
||||
constructor(bucket: Bucket, name: string, options?: FileOptions);
|
||||
/**
|
||||
* A helper method for determining if a request should be retried based on preconditions.
|
||||
* This should only be used for methods where the idempotency is determined by
|
||||
* `ifGenerationMatch`
|
||||
*
|
||||
* A request should not be retried under the following conditions:
|
||||
* - if precondition option `ifGenerationMatch` is not set OR
|
||||
* - if `idempotencyStrategy` is set to `RetryNever`
|
||||
*/
|
||||
private shouldRetryBasedOnPreconditionAndIdempotencyStrat;
|
||||
copy(destination: string | Bucket | File, options?: CopyOptions): Promise<CopyResponse>;
|
||||
copy(destination: string | Bucket | File, callback: CopyCallback): void;
|
||||
copy(destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback): void;
|
||||
/**
|
||||
* @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream.
|
||||
* @property {string} [userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @property {string|boolean} [validation] Possible values: `"md5"`,
|
||||
* `"crc32c"`, or `false`. By default, data integrity is validated with a
|
||||
* CRC32c checksum. You may use MD5 if preferred, but that hash is not
|
||||
* supported for composite objects. An error will be raised if MD5 is
|
||||
* specified but is not available. You may also choose to skip validation
|
||||
* completely, however this is **not recommended**.
|
||||
* @property {number} [start] A byte offset to begin the file's download
|
||||
* from. Default is 0. NOTE: Byte ranges are inclusive; that is,
|
||||
* `options.start = 0` and `options.end = 999` represent the first 1000
|
||||
* bytes in a file or object. NOTE: when specifying a byte range, data
|
||||
* integrity is not available.
|
||||
* @property {number} [end] A byte offset to stop reading the file at.
|
||||
* NOTE: Byte ranges are inclusive; that is, `options.start = 0` and
|
||||
* `options.end = 999` represent the first 1000 bytes in a file or object.
|
||||
* NOTE: when specifying a byte range, data integrity is not available.
|
||||
* @property {boolean} [decompress=true] Disable auto decompression of the
|
||||
* received data. By default this option is set to `true`.
|
||||
* Applicable in cases where the data was uploaded with
|
||||
* `gzip: true` option. See {@link File#createWriteStream}.
|
||||
*/
|
||||
/**
|
||||
* Create a readable stream to read the contents of the remote file. It can be
|
||||
* piped to a writable stream or listened to for 'data' events to read a
|
||||
* file's contents.
|
||||
*
|
||||
* In the unlikely event there is a mismatch between what you downloaded and
|
||||
* the version in your Bucket, your error handler will receive an error with
|
||||
* code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best
|
||||
* recourse is to try downloading the file again.
|
||||
*
|
||||
* For faster crc32c computation, you must manually install
|
||||
* {@link https://www.npmjs.com/package/fast-crc32c| `fast-crc32c`}:
|
||||
*
|
||||
* $ npm install --save fast-crc32c
|
||||
*
|
||||
* NOTE: Readable streams will emit the `end` event when the file is fully
|
||||
* downloaded.
|
||||
*
|
||||
* @param {CreateReadStreamOptions} [options] Configuration options.
|
||||
* @returns {ReadableStream}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* //-
|
||||
* // <h4>Downloading a File</h4>
|
||||
* //
|
||||
* // The example below demonstrates how we can reference a remote file, then
|
||||
* // pipe its contents to a local file. This is effectively creating a local
|
||||
* // backup of your remote data.
|
||||
* //-
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const fs = require('fs');
|
||||
* const remoteFile = bucket.file('image.png');
|
||||
* const localFilename = '/Users/stephen/Photos/image.png';
|
||||
*
|
||||
* remoteFile.createReadStream()
|
||||
* .on('error', function(err) {})
|
||||
* .on('response', function(response) {
|
||||
* // Server connected and responded with the specified status and headers.
|
||||
* })
|
||||
* .on('end', function() {
|
||||
* // The file is fully downloaded.
|
||||
* })
|
||||
* .pipe(fs.createWriteStream(localFilename));
|
||||
*
|
||||
* //-
|
||||
* // To limit the downloaded data to only a byte range, pass an options
|
||||
* // object.
|
||||
* //-
|
||||
* const logFile = myBucket.file('access_log');
|
||||
* logFile.createReadStream({
|
||||
* start: 10000,
|
||||
* end: 20000
|
||||
* })
|
||||
* .on('error', function(err) {})
|
||||
* .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
|
||||
*
|
||||
* //-
|
||||
* // To read a tail byte range, specify only `options.end` as a negative
|
||||
* // number.
|
||||
* //-
|
||||
* const logFile = myBucket.file('access_log');
|
||||
* logFile.createReadStream({
|
||||
* end: -100
|
||||
* })
|
||||
* .on('error', function(err) {})
|
||||
* .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
|
||||
* ```
|
||||
*/
|
||||
createReadStream(options?: CreateReadStreamOptions): Readable;
|
||||
createResumableUpload(options?: CreateResumableUploadOptions): Promise<CreateResumableUploadResponse>;
|
||||
createResumableUpload(options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback): void;
|
||||
createResumableUpload(callback: CreateResumableUploadCallback): void;
|
||||
/**
|
||||
* @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream().
|
||||
* @property {string} [configPath] **This only applies to resumable
|
||||
* uploads.** A full JSON file path to use with `gcs-resumable-upload`.
|
||||
* This maps to the {@link https://github.com/yeoman/configstore/tree/0df1ec950d952b1f0dfb39ce22af8e505dffc71a#configpath| configstore option by the same name}.
|
||||
* @property {string} [contentType] Alias for
|
||||
* `options.metadata.contentType`. If set to `auto`, the file name is used
|
||||
* to determine the contentType.
|
||||
* @property {string|boolean} [gzip] If true, automatically gzip the file.
|
||||
* If set to `auto`, the contentType is used to determine if the file
|
||||
* should be gzipped. This will set `options.metadata.contentEncoding` to
|
||||
* `gzip` if necessary.
|
||||
* @property {object} [metadata] See the examples below or
|
||||
* {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}
|
||||
* for more details.
|
||||
* @property {number} [offset] The starting byte of the upload stream, for
|
||||
* resuming an interrupted upload. Defaults to 0.
|
||||
* @property {string} [predefinedAcl] Apply a predefined set of access
|
||||
* controls to this object.
|
||||
*
|
||||
* Acceptable values are:
|
||||
* - **`authenticatedRead`** - Object owner gets `OWNER` access, and
|
||||
* `allAuthenticatedUsers` get `READER` access.
|
||||
*
|
||||
* - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
|
||||
* project team owners get `OWNER` access.
|
||||
*
|
||||
* - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
|
||||
* team owners get `READER` access.
|
||||
*
|
||||
* - **`private`** - Object owner gets `OWNER` access.
|
||||
*
|
||||
* - **`projectPrivate`** - Object owner gets `OWNER` access, and project
|
||||
* team members get access according to their roles.
|
||||
*
|
||||
* - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
|
||||
* get `READER` access.
|
||||
* @property {boolean} [private] Make the uploaded file private. (Alias for
|
||||
* `options.predefinedAcl = 'private'`)
|
||||
* @property {boolean} [public] Make the uploaded file public. (Alias for
|
||||
* `options.predefinedAcl = 'publicRead'`)
|
||||
* @property {boolean} [resumable] Force a resumable upload. NOTE: When
|
||||
* working with streams, the file format and size is unknown until it's
|
||||
* completely consumed. Because of this, it's best for you to be explicit
|
||||
* for what makes sense given your input.
|
||||
* @property {number} [timeout=60000] Set the HTTP request timeout in
|
||||
* milliseconds. This option is not available for resumable uploads.
|
||||
* Default: `60000`
|
||||
* @property {string} [uri] The URI for an already-created resumable
|
||||
* upload. See {@link File#createResumableUpload}.
|
||||
* @property {string} [userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @property {string|boolean} [validation] Possible values: `"md5"`,
|
||||
* `"crc32c"`, or `false`. By default, data integrity is validated with a
|
||||
* CRC32c checksum. You may use MD5 if preferred, but that hash is not
|
||||
* supported for composite objects. An error will be raised if MD5 is
|
||||
* specified but is not available. You may also choose to skip validation
|
||||
* completely, however this is **not recommended**.
|
||||
* NOTE: Validation is automatically skipped for objects that were
|
||||
* uploaded using the `gzip` option and have already compressed content.
|
||||
*/
|
||||
/**
|
||||
* Create a writable stream to overwrite the contents of the file in your
|
||||
* bucket.
|
||||
*
|
||||
* A File object can also be used to create files for the first time.
|
||||
*
|
||||
* Resumable uploads are automatically enabled and must be shut off explicitly
|
||||
* by setting `options.resumable` to `false`.
|
||||
*
|
||||
* Resumable uploads require write access to the $HOME directory. Through
|
||||
* {@link https://www.npmjs.com/package/configstore| `config-store`}, some metadata
|
||||
* is stored. By default, if the directory is not writable, we will fall back
|
||||
* to a simple upload. However, if you explicitly request a resumable upload,
|
||||
* and we cannot write to the config directory, we will return a
|
||||
* `ResumableUploadError`.
|
||||
*
|
||||
* <p class="notice">
|
||||
* There is some overhead when using a resumable upload that can cause
|
||||
* noticeable performance degradation while uploading a series of small
|
||||
* files. When uploading files less than 10MB, it is recommended that the
|
||||
* resumable feature is disabled.
|
||||
* </p>
|
||||
*
|
||||
* For faster crc32c computation, you must manually install
|
||||
* {@link https://www.npmjs.com/package/fast-crc32c| `fast-crc32c`}:
|
||||
*
|
||||
* $ npm install --save fast-crc32c
|
||||
*
|
||||
* NOTE: Writable streams will emit the `finish` event when the file is fully
|
||||
* uploaded.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload| Upload Options (Simple or Resumable)}
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation}
|
||||
*
|
||||
* @param {CreateWriteStreamOptions} [options] Configuration options.
|
||||
* @returns {WritableStream}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const fs = require('fs');
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const file = myBucket.file('my-file');
|
||||
*
|
||||
* //-
|
||||
* // <h4>Uploading a File</h4>
|
||||
* //
|
||||
* // Now, consider a case where we want to upload a file to your bucket. You
|
||||
* // have the option of using {@link Bucket#upload}, but that is just
|
||||
* // a convenience method which will do the following.
|
||||
* //-
|
||||
* fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
|
||||
* .pipe(file.createWriteStream())
|
||||
* .on('error', function(err) {})
|
||||
* .on('finish', function() {
|
||||
* // The file upload is complete.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // <h4>Uploading a File with gzip compression</h4>
|
||||
* //-
|
||||
* fs.createReadStream('/Users/stephen/site/index.html')
|
||||
* .pipe(file.createWriteStream({ gzip: true }))
|
||||
* .on('error', function(err) {})
|
||||
* .on('finish', function() {
|
||||
* // The file upload is complete.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // Downloading the file with `createReadStream` will automatically decode
|
||||
* // the file.
|
||||
* //-
|
||||
*
|
||||
* //-
|
||||
* // <h4>Uploading a File with Metadata</h4>
|
||||
* //
|
||||
* // One last case you may run into is when you want to upload a file to your
|
||||
* // bucket and set its metadata at the same time. Like above, you can use
|
||||
* // {@link Bucket#upload} to do this, which is just a wrapper around
|
||||
* // the following.
|
||||
* //-
|
||||
* fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
|
||||
* .pipe(file.createWriteStream({
|
||||
* metadata: {
|
||||
* contentType: 'image/jpeg',
|
||||
* metadata: {
|
||||
* custom: 'metadata'
|
||||
* }
|
||||
* }
|
||||
* }))
|
||||
* .on('error', function(err) {})
|
||||
* .on('finish', function() {
|
||||
* // The file upload is complete.
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
createWriteStream(options?: CreateWriteStreamOptions): Writable;
|
||||
/**
|
||||
* Delete failed resumable upload file cache.
|
||||
*
|
||||
* Resumable file upload cache the config file to restart upload in case of
|
||||
* failure. In certain scenarios, the resumable upload will not works and
|
||||
* upload file cache needs to be deleted to upload the same file.
|
||||
*
|
||||
* Following are some of the scenarios.
|
||||
*
|
||||
* Resumable file upload failed even though the file is successfully saved
|
||||
* on the google storage and need to clean up a resumable file cache to
|
||||
* update the same file.
|
||||
*
|
||||
* Resumable file upload failed due to pre-condition
|
||||
* (i.e generation number is not matched) and want to upload a same
|
||||
* file with the new generation number.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const file = myBucket.file('my-file', { generation: 0 });
|
||||
* const contents = 'This is the contents of the file.';
|
||||
*
|
||||
* file.save(contents, function(err) {
|
||||
* if (err) {
|
||||
* file.deleteResumableCache();
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
*/
|
||||
deleteResumableCache(): void;
|
||||
download(options?: DownloadOptions): Promise<DownloadResponse>;
|
||||
download(options: DownloadOptions, callback: DownloadCallback): void;
|
||||
download(callback: DownloadCallback): void;
|
||||
/**
|
||||
* The Storage API allows you to use a custom key for server-side encryption.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}
|
||||
*
|
||||
* @param {string|buffer} encryptionKey An AES-256 encryption key.
|
||||
* @returns {File}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const crypto = require('crypto');
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const encryptionKey = crypto.randomBytes(32);
|
||||
*
|
||||
* const fileWithCustomEncryption = myBucket.file('my-file');
|
||||
* fileWithCustomEncryption.setEncryptionKey(encryptionKey);
|
||||
*
|
||||
* const fileWithoutCustomEncryption = myBucket.file('my-file');
|
||||
*
|
||||
* fileWithCustomEncryption.save('data', function(err) {
|
||||
* // Try to download with the File object that hasn't had
|
||||
* // `setEncryptionKey()` called:
|
||||
* fileWithoutCustomEncryption.download(function(err) {
|
||||
* // We will receive an error:
|
||||
* // err.message === 'Bad Request'
|
||||
*
|
||||
* // Try again with the File object we called `setEncryptionKey()` on:
|
||||
* fileWithCustomEncryption.download(function(err, contents) {
|
||||
* // contents.toString() === 'data'
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/encryption.js</caption>
|
||||
* region_tag:storage_upload_encrypted_file
|
||||
* Example of uploading an encrypted file:
|
||||
*
|
||||
* @example <caption>include:samples/encryption.js</caption>
|
||||
* region_tag:storage_download_encrypted_file
|
||||
* Example of downloading an encrypted file:
|
||||
*/
|
||||
setEncryptionKey(encryptionKey: string | Buffer): this;
|
||||
getExpirationDate(): Promise<GetExpirationDateResponse>;
|
||||
getExpirationDate(callback: GetExpirationDateCallback): void;
|
||||
getSignedPolicy(options: GetSignedPolicyOptions): Promise<GetSignedPolicyResponse>;
|
||||
getSignedPolicy(options: GetSignedPolicyOptions, callback: GetSignedPolicyCallback): void;
|
||||
getSignedPolicy(callback: GetSignedPolicyCallback): void;
|
||||
generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options): Promise<GenerateSignedPostPolicyV2Response>;
|
||||
generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback): void;
|
||||
generateSignedPostPolicyV2(callback: GenerateSignedPostPolicyV2Callback): void;
|
||||
generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options): Promise<GenerateSignedPostPolicyV4Response>;
|
||||
generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback): void;
|
||||
generateSignedPostPolicyV4(callback: GenerateSignedPostPolicyV4Callback): void;
|
||||
getSignedUrl(cfg: GetSignedUrlConfig): Promise<GetSignedUrlResponse>;
|
||||
getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void;
|
||||
isPublic(): Promise<IsPublicResponse>;
|
||||
isPublic(callback: IsPublicCallback): void;
|
||||
makePrivate(options?: MakeFilePrivateOptions): Promise<MakeFilePrivateResponse>;
|
||||
makePrivate(callback: MakeFilePrivateCallback): void;
|
||||
makePrivate(options: MakeFilePrivateOptions, callback: MakeFilePrivateCallback): void;
|
||||
makePublic(): Promise<MakeFilePublicResponse>;
|
||||
makePublic(callback: MakeFilePublicCallback): void;
|
||||
/**
|
||||
* The public URL of this File
|
||||
* Use {@link File#makePublic} to enable anonymous access via the returned URL.
|
||||
*
|
||||
* @returns {string}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
* const file = bucket.file('my-file');
|
||||
*
|
||||
* // publicUrl will be "https://storage.googleapis.com/albums/my-file"
|
||||
* const publicUrl = file.publicUrl();
|
||||
* ```
|
||||
*/
|
||||
publicUrl(): string;
|
||||
move(destination: string | Bucket | File, options?: MoveOptions): Promise<MoveResponse>;
|
||||
move(destination: string | Bucket | File, callback: MoveCallback): void;
|
||||
move(destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback): void;
|
||||
rename(destinationFile: string | File, options?: RenameOptions): Promise<RenameResponse>;
|
||||
rename(destinationFile: string | File, callback: RenameCallback): void;
|
||||
rename(destinationFile: string | File, options: RenameOptions, callback: RenameCallback): void;
|
||||
request(reqOpts: DecorateRequestOptions): Promise<[ResponseBody, Metadata]>;
|
||||
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
|
||||
rotateEncryptionKey(options?: RotateEncryptionKeyOptions): Promise<RotateEncryptionKeyResponse>;
|
||||
rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void;
|
||||
rotateEncryptionKey(options: RotateEncryptionKeyOptions, callback: RotateEncryptionKeyCallback): void;
|
||||
save(data: string | Buffer, options?: SaveOptions): Promise<void>;
|
||||
save(data: string | Buffer, callback: SaveCallback): void;
|
||||
save(data: string | Buffer, options: SaveOptions, callback: SaveCallback): void;
|
||||
setStorageClass(storageClass: string, options?: SetStorageClassOptions): Promise<SetStorageClassResponse>;
|
||||
setStorageClass(storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback): void;
|
||||
setStorageClass(storageClass: string, callback?: SetStorageClassCallback): void;
|
||||
/**
|
||||
* Set a user project to be billed for all requests made from this File
|
||||
* object.
|
||||
*
|
||||
* @param {string} userProject The user project.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('albums');
|
||||
* const file = bucket.file('my-file');
|
||||
*
|
||||
* file.setUserProject('grape-spaceship-123');
|
||||
* ```
|
||||
*/
|
||||
setUserProject(userProject: string): void;
|
||||
/**
|
||||
* This creates a gcs-resumable-upload upload stream.
|
||||
*
|
||||
* See {@link https://github.com/googleapis/gcs-resumable-upload| gcs-resumable-upload}
|
||||
*
|
||||
* @param {Duplexify} stream - Duplexify stream of data to pipe to the file.
|
||||
* @param {object=} options - Configuration object.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
startResumableUpload_(dup: Duplexify, options: CreateResumableUploadOptions): void;
|
||||
/**
|
||||
* Takes a readable stream and pipes it to a remote file. Unlike
|
||||
* `startResumableUpload_`, which uses the resumable upload technique, this
|
||||
* method uses a simple upload (all or nothing).
|
||||
*
|
||||
* @param {Duplexify} dup - Duplexify stream of data to pipe to the file.
|
||||
* @param {object=} options - Configuration object.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
startSimpleUpload_(dup: Duplexify, options?: CreateWriteStreamOptions): void;
|
||||
disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods): void;
|
||||
}
|
||||
/**
|
||||
* Reference to the {@link File} class.
|
||||
* @name module:@google-cloud/storage.File
|
||||
* @see File
|
||||
*/
|
||||
export { File };
|
||||
+3269
File diff suppressed because it is too large
Load Diff
+74
@@ -0,0 +1,74 @@
|
||||
import { Metadata, ServiceObject } from '@google-cloud/common';
|
||||
import { Storage } from './storage';
|
||||
export interface HmacKeyOptions {
|
||||
projectId?: string;
|
||||
}
|
||||
export interface HmacKeyMetadata {
|
||||
accessId: string;
|
||||
etag?: string;
|
||||
id?: string;
|
||||
projectId?: string;
|
||||
serviceAccountEmail?: string;
|
||||
state?: string;
|
||||
timeCreated?: string;
|
||||
updated?: string;
|
||||
}
|
||||
export interface SetHmacKeyMetadataOptions {
|
||||
/**
|
||||
* This parameter is currently ignored.
|
||||
*/
|
||||
userProject?: string;
|
||||
}
|
||||
export interface SetHmacKeyMetadata {
|
||||
state?: 'ACTIVE' | 'INACTIVE';
|
||||
etag?: string;
|
||||
}
|
||||
export interface HmacKeyMetadataCallback {
|
||||
(err: Error | null, metadata?: HmacKeyMetadata, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type HmacKeyMetadataResponse = [HmacKeyMetadata, Metadata];
|
||||
/**
|
||||
* The API-formatted resource description of the HMAC key.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name HmacKey#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* An HmacKey object contains metadata of an HMAC key created from a
|
||||
* service account through the {@link Storage} client using
|
||||
* {@link Storage#createHmacKey}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation}
|
||||
*
|
||||
* @class
|
||||
*/
|
||||
export declare class HmacKey extends ServiceObject<HmacKeyMetadata | undefined> {
|
||||
metadata: HmacKeyMetadata | undefined;
|
||||
/**
|
||||
* @typedef {object} HmacKeyOptions
|
||||
* @property {string} [projectId] The project ID of the project that owns
|
||||
* the service account of the requested HMAC key. If not provided,
|
||||
* the project ID used to instantiate the Storage client will be used.
|
||||
*/
|
||||
/**
|
||||
* Constructs an HmacKey object.
|
||||
*
|
||||
* Note: this only create a local reference to an HMAC key, to create
|
||||
* an HMAC key, use {@link Storage#createHmacKey}.
|
||||
*
|
||||
* @param {Storage} storage The Storage instance this HMAC key is
|
||||
* attached to.
|
||||
* @param {string} accessId The unique accessId for this HMAC key.
|
||||
* @param {HmacKeyOptions} options Constructor configurations.
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const hmacKey = storage.hmacKey('access-id');
|
||||
* ```
|
||||
*/
|
||||
constructor(storage: Storage, accessId: string, options?: HmacKeyOptions);
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.HmacKey = void 0;
|
||||
const common_1 = require("@google-cloud/common");
|
||||
/**
|
||||
* The API-formatted resource description of the HMAC key.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name HmacKey#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* An HmacKey object contains metadata of an HMAC key created from a
|
||||
* service account through the {@link Storage} client using
|
||||
* {@link Storage#createHmacKey}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation}
|
||||
*
|
||||
* @class
|
||||
*/
|
||||
class HmacKey extends common_1.ServiceObject {
|
||||
/**
|
||||
* @typedef {object} HmacKeyOptions
|
||||
* @property {string} [projectId] The project ID of the project that owns
|
||||
* the service account of the requested HMAC key. If not provided,
|
||||
* the project ID used to instantiate the Storage client will be used.
|
||||
*/
|
||||
/**
|
||||
* Constructs an HmacKey object.
|
||||
*
|
||||
* Note: this only create a local reference to an HMAC key, to create
|
||||
* an HMAC key, use {@link Storage#createHmacKey}.
|
||||
*
|
||||
* @param {Storage} storage The Storage instance this HMAC key is
|
||||
* attached to.
|
||||
* @param {string} accessId The unique accessId for this HMAC key.
|
||||
* @param {HmacKeyOptions} options Constructor configurations.
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const hmacKey = storage.hmacKey('access-id');
|
||||
* ```
|
||||
*/
|
||||
constructor(storage, accessId, options) {
|
||||
const methods = {
|
||||
/**
|
||||
* @typedef {object} DeleteHmacKeyOptions
|
||||
* @property {string} [userProject] This parameter is currently ignored.
|
||||
*/
|
||||
/**
|
||||
* @typedef {array} DeleteHmacKeyResponse
|
||||
* @property {object} 0 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback DeleteHmacKeyCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Deletes an HMAC key.
|
||||
* Key state must be set to `INACTIVE` prior to deletion.
|
||||
* Caution: HMAC keys cannot be recovered once you delete them.
|
||||
*
|
||||
* The authenticated user must have `storage.hmacKeys.delete` permission for the project in which the key exists.
|
||||
*
|
||||
* @method HmacKey#delete
|
||||
* @param {DeleteHmacKeyOptions} [options] Configuration options.
|
||||
* @param {DeleteHmacKeyCallback} [callback] Callback function.
|
||||
* @returns {Promise<DeleteHmacKeyResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
*
|
||||
* //-
|
||||
* // Delete HMAC key after making the key inactive.
|
||||
* //-
|
||||
* const hmacKey = storage.hmacKey('ACCESS_ID');
|
||||
* hmacKey.setMetadata({state: 'INACTIVE'}, (err, hmacKeyMetadata) => {
|
||||
* if (err) {
|
||||
* // The request was an error.
|
||||
* console.error(err);
|
||||
* return;
|
||||
* }
|
||||
* hmacKey.delete((err) => {
|
||||
* if (err) {
|
||||
* console.error(err);
|
||||
* return;
|
||||
* }
|
||||
* // The HMAC key is deleted.
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, a promise is returned.
|
||||
* //-
|
||||
* const hmacKey = storage.hmacKey('ACCESS_ID');
|
||||
* hmacKey
|
||||
* .setMetadata({state: 'INACTIVE'})
|
||||
* .then(() => {
|
||||
* return hmacKey.delete();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
delete: true,
|
||||
/**
|
||||
* @callback GetHmacKeyCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {HmacKey} hmacKey this {@link HmacKey} instance.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* @typedef {array} GetHmacKeyResponse
|
||||
* @property {HmacKey} 0 This {@link HmacKey} instance.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} GetHmacKeyOptions
|
||||
* @property {string} [userProject] This parameter is currently ignored.
|
||||
*/
|
||||
/**
|
||||
* Retrieves and populate an HMAC key's metadata, and return
|
||||
* this {@link HmacKey} instance.
|
||||
*
|
||||
* HmacKey.get() does not give the HMAC key secret, as
|
||||
* it is only returned on creation.
|
||||
*
|
||||
* The authenticated user must have `storage.hmacKeys.get` permission
|
||||
* for the project in which the key exists.
|
||||
*
|
||||
* @method HmacKey#get
|
||||
* @param {GetHmacKeyOptions} [options] Configuration options.
|
||||
* @param {GetHmacKeyCallback} [callback] Callback function.
|
||||
* @returns {Promise<GetHmacKeyResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
*
|
||||
* //-
|
||||
* // Get the HmacKey's Metadata.
|
||||
* //-
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .get((err, hmacKey) => {
|
||||
* if (err) {
|
||||
* // The request was an error.
|
||||
* console.error(err);
|
||||
* return;
|
||||
* }
|
||||
* // do something with the returned HmacKey object.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, a promise is returned.
|
||||
* //-
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .get()
|
||||
* .then((data) => {
|
||||
* const hmacKey = data[0];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get: true,
|
||||
/**
|
||||
* @typedef {object} GetHmacKeyMetadataOptions
|
||||
* @property {string} [userProject] This parameter is currently ignored.
|
||||
*/
|
||||
/**
|
||||
* Retrieves and populate an HMAC key's metadata, and return
|
||||
* the HMAC key's metadata as an object.
|
||||
*
|
||||
* HmacKey.getMetadata() does not give the HMAC key secret, as
|
||||
* it is only returned on creation.
|
||||
*
|
||||
* The authenticated user must have `storage.hmacKeys.get` permission
|
||||
* for the project in which the key exists.
|
||||
*
|
||||
* @method HmacKey#getMetadata
|
||||
* @param {GetHmacKeyMetadataOptions} [options] Configuration options.
|
||||
* @param {HmacKeyMetadataCallback} [callback] Callback function.
|
||||
* @returns {Promise<HmacKeyMetadataResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
*
|
||||
* //-
|
||||
* // Get the HmacKey's metadata and populate to the metadata property.
|
||||
* //-
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .getMetadata((err, hmacKeyMetadata) => {
|
||||
* if (err) {
|
||||
* // The request was an error.
|
||||
* console.error(err);
|
||||
* return;
|
||||
* }
|
||||
* console.log(hmacKeyMetadata);
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, a promise is returned.
|
||||
* //-
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .getMetadata()
|
||||
* .then((data) => {
|
||||
* const hmacKeyMetadata = data[0];
|
||||
* console.log(hmacKeyMetadata);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
getMetadata: true,
|
||||
/**
|
||||
* @typedef {object} SetHmacKeyMetadata Subset of {@link HmacKeyMetadata} to update.
|
||||
* @property {string} state New state of the HmacKey. Either 'ACTIVE' or 'INACTIVE'.
|
||||
* @property {string} [etag] Include an etag from a previous get HMAC key request
|
||||
* to perform safe read-modify-write.
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} SetHmacKeyMetadataOptions
|
||||
* @property {string} [userProject] This parameter is currently ignored.
|
||||
*/
|
||||
/**
|
||||
* @callback HmacKeyMetadataCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {HmacKeyMetadata} metadata The updated {@link HmacKeyMetadata} object.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* @typedef {array} HmacKeyMetadataResponse
|
||||
* @property {HmacKeyMetadata} 0 The updated {@link HmacKeyMetadata} object.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* Updates the state of an HMAC key. See {@link SetHmacKeyMetadata} for
|
||||
* valid states.
|
||||
*
|
||||
* @method HmacKey#setMetadata
|
||||
* @param {SetHmacKeyMetadata} metadata The new metadata.
|
||||
* @param {SetHmacKeyMetadataOptions} [options] Configuration options.
|
||||
* @param {HmacKeyMetadataCallback} [callback] Callback function.
|
||||
* @returns {Promise<HmacKeyMetadataResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
*
|
||||
* const metadata = {
|
||||
* state: 'INACTIVE',
|
||||
* };
|
||||
*
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .setMetadata(metadata, (err, hmacKeyMetadata) => {
|
||||
* if (err) {
|
||||
* // The request was an error.
|
||||
* console.error(err);
|
||||
* return;
|
||||
* }
|
||||
* console.log(hmacKeyMetadata);
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, a promise is returned.
|
||||
* //-
|
||||
* storage.hmacKey('ACCESS_ID')
|
||||
* .setMetadata(metadata)
|
||||
* .then((data) => {
|
||||
* const hmacKeyMetadata = data[0];
|
||||
* console.log(hmacKeyMetadata);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
setMetadata: {
|
||||
reqOpts: {
|
||||
method: 'PUT',
|
||||
},
|
||||
},
|
||||
};
|
||||
const projectId = (options && options.projectId) || storage.projectId;
|
||||
super({
|
||||
parent: storage,
|
||||
id: accessId,
|
||||
baseUrl: `/projects/${projectId}/hmacKeys`,
|
||||
methods,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.HmacKey = HmacKey;
|
||||
//# sourceMappingURL=hmacKey.js.map
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { Metadata } from '@google-cloud/common';
|
||||
import { Bucket } from './bucket';
|
||||
export interface GetPolicyOptions {
|
||||
userProject?: string;
|
||||
requestedPolicyVersion?: number;
|
||||
}
|
||||
export declare type GetPolicyResponse = [Policy, Metadata];
|
||||
/**
|
||||
* @callback GetPolicyCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} acl The policy.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface GetPolicyCallback {
|
||||
(err?: Error | null, acl?: Policy, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* @typedef {object} SetPolicyOptions
|
||||
* @param {string} [userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
*/
|
||||
export interface SetPolicyOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} SetPolicyResponse
|
||||
* @property {object} 0 The policy.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
export declare type SetPolicyResponse = [Policy, Metadata];
|
||||
/**
|
||||
* @callback SetPolicyCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} acl The policy.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface SetPolicyCallback {
|
||||
(err?: Error | null, acl?: Policy, apiResponse?: object): void;
|
||||
}
|
||||
export interface Policy {
|
||||
bindings: PolicyBinding[];
|
||||
version?: number;
|
||||
etag?: string;
|
||||
}
|
||||
export interface PolicyBinding {
|
||||
role: string;
|
||||
members: string[];
|
||||
condition?: Expr;
|
||||
}
|
||||
export interface Expr {
|
||||
title?: string;
|
||||
description?: string;
|
||||
expression: string;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} TestIamPermissionsResponse
|
||||
* @property {object} 0 A subset of permissions that the caller is allowed.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
export declare type TestIamPermissionsResponse = [{
|
||||
[key: string]: boolean;
|
||||
}, Metadata];
|
||||
/**
|
||||
* @callback TestIamPermissionsCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} acl A subset of permissions that the caller is allowed.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface TestIamPermissionsCallback {
|
||||
(err?: Error | null, acl?: {
|
||||
[key: string]: boolean;
|
||||
} | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* @typedef {object} TestIamPermissionsOptions Configuration options for Iam#testPermissions().
|
||||
* @param {string} [userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
*/
|
||||
export interface TestIamPermissionsOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
/**
|
||||
* Get and set IAM policies for your Cloud Storage bucket.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
|
||||
* See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
|
||||
* See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
|
||||
*
|
||||
* @constructor Iam
|
||||
*
|
||||
* @param {Bucket} bucket The parent instance.
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
* // bucket.iam
|
||||
* ```
|
||||
*/
|
||||
declare class Iam {
|
||||
private request_;
|
||||
private resourceId_;
|
||||
constructor(bucket: Bucket);
|
||||
getPolicy(options?: GetPolicyOptions): Promise<GetPolicyResponse>;
|
||||
getPolicy(options: GetPolicyOptions, callback: GetPolicyCallback): void;
|
||||
getPolicy(callback: GetPolicyCallback): void;
|
||||
setPolicy(policy: Policy, options?: SetPolicyOptions): Promise<SetPolicyResponse>;
|
||||
setPolicy(policy: Policy, callback: SetPolicyCallback): void;
|
||||
setPolicy(policy: Policy, options: SetPolicyOptions, callback: SetPolicyCallback): void;
|
||||
testPermissions(permissions: string | string[], options?: TestIamPermissionsOptions): Promise<TestIamPermissionsResponse>;
|
||||
testPermissions(permissions: string | string[], callback: TestIamPermissionsCallback): void;
|
||||
testPermissions(permissions: string | string[], options: TestIamPermissionsOptions, callback: TestIamPermissionsCallback): void;
|
||||
}
|
||||
export { Iam };
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Iam = void 0;
|
||||
const promisify_1 = require("@google-cloud/promisify");
|
||||
const arrify = require("arrify");
|
||||
const util_1 = require("./util");
|
||||
/**
|
||||
* Get and set IAM policies for your Cloud Storage bucket.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
|
||||
* See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
|
||||
* See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
|
||||
*
|
||||
* @constructor Iam
|
||||
*
|
||||
* @param {Bucket} bucket The parent instance.
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
* // bucket.iam
|
||||
* ```
|
||||
*/
|
||||
class Iam {
|
||||
constructor(bucket) {
|
||||
this.request_ = bucket.request.bind(bucket);
|
||||
this.resourceId_ = 'buckets/' + bucket.getId();
|
||||
}
|
||||
/**
|
||||
* @typedef {object} GetPolicyOptions Requested options for IAM#getPolicy().
|
||||
* @property {number} [requestedPolicyVersion] The version of IAM policies to
|
||||
* request. If a policy with a condition is requested without setting
|
||||
* this, the server will return an error. This must be set to a value
|
||||
* of 3 to retrieve IAM policies containing conditions. This is to
|
||||
* prevent client code that isn't aware of IAM conditions from
|
||||
* interpreting and modifying policies incorrectly. The service might
|
||||
* return a policy with version lower than the one that was requested,
|
||||
* based on the feature syntax in the policy fetched.
|
||||
* See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions}
|
||||
* @property {string} [userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
*/
|
||||
/**
|
||||
* @typedef {array} GetPolicyResponse
|
||||
* @property {Policy} 0 The policy.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} Policy
|
||||
* @property {PolicyBinding[]} policy.bindings Bindings associate members with roles.
|
||||
* @property {string} [policy.etag] Etags are used to perform a read-modify-write.
|
||||
* @property {number} [policy.version] The syntax schema version of the Policy.
|
||||
* To set an IAM policy with conditional binding, this field must be set to
|
||||
* 3 or greater.
|
||||
* See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions}
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} PolicyBinding
|
||||
* @property {string} role Role that is assigned to members.
|
||||
* @property {string[]} members Specifies the identities requesting access for the bucket.
|
||||
* @property {Expr} [condition] The condition that is associated with this binding.
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} Expr
|
||||
* @property {string} [title] An optional title for the expression, i.e. a
|
||||
* short string describing its purpose. This can be used e.g. in UIs
|
||||
* which allow to enter the expression.
|
||||
* @property {string} [description] An optional description of the
|
||||
* expression. This is a longer text which describes the expression,
|
||||
* e.g. when hovered over it in a UI.
|
||||
* @property {string} expression Textual representation of an expression in
|
||||
* Common Expression Language syntax. The application context of the
|
||||
* containing message determines which well-known feature set of CEL
|
||||
* is supported.The condition that is associated with this binding.
|
||||
*
|
||||
* @see [Condition] https://cloud.google.com/storage/docs/access-control/iam#conditions
|
||||
*/
|
||||
/**
|
||||
* Get the IAM policy.
|
||||
*
|
||||
* @param {GetPolicyOptions} [options] Request options.
|
||||
* @param {GetPolicyCallback} [callback] Callback function.
|
||||
* @returns {Promise<GetPolicyResponse>}
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy| Buckets: setIamPolicy API Documentation}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* bucket.iam.getPolicy(
|
||||
* {requestedPolicyVersion: 3},
|
||||
* function(err, policy, apiResponse) {
|
||||
*
|
||||
* },
|
||||
* );
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* bucket.iam.getPolicy({requestedPolicyVersion: 3})
|
||||
* .then(function(data) {
|
||||
* const policy = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_view_bucket_iam_members
|
||||
* Example of retrieving a bucket's IAM policy:
|
||||
*/
|
||||
getPolicy(optionsOrCallback, callback) {
|
||||
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
|
||||
const qs = {};
|
||||
if (options.userProject) {
|
||||
qs.userProject = options.userProject;
|
||||
}
|
||||
if (options.requestedPolicyVersion !== null &&
|
||||
options.requestedPolicyVersion !== undefined) {
|
||||
qs.optionsRequestedPolicyVersion = options.requestedPolicyVersion;
|
||||
}
|
||||
this.request_({
|
||||
uri: '/iam',
|
||||
qs,
|
||||
}, cb);
|
||||
}
|
||||
/**
|
||||
* Set the IAM policy.
|
||||
*
|
||||
* @throws {Error} If no policy is provided.
|
||||
*
|
||||
* @param {Policy} policy The policy.
|
||||
* @param {SetPolicyOptions} [options] Configuration opbject.
|
||||
* @param {SetPolicyCallback} callback Callback function.
|
||||
* @returns {Promise<SetPolicyResponse>}
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy| Buckets: setIamPolicy API Documentation}
|
||||
* See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const myPolicy = {
|
||||
* bindings: [
|
||||
* {
|
||||
* role: 'roles/storage.admin',
|
||||
* members:
|
||||
* ['serviceAccount:[email protected]']
|
||||
* }
|
||||
* ]
|
||||
* };
|
||||
*
|
||||
* bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* bucket.iam.setPolicy(myPolicy).then(function(data) {
|
||||
* const policy = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_add_bucket_iam_member
|
||||
* Example of adding to a bucket's IAM policy:
|
||||
*
|
||||
* @example <caption>include:samples/iam.js</caption>
|
||||
* region_tag:storage_remove_bucket_iam_member
|
||||
* Example of removing from a bucket's IAM policy:
|
||||
*/
|
||||
setPolicy(policy, optionsOrCallback, callback) {
|
||||
if (policy === null || typeof policy !== 'object') {
|
||||
throw new Error('A policy object is required.');
|
||||
}
|
||||
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
|
||||
this.request_({
|
||||
method: 'PUT',
|
||||
uri: '/iam',
|
||||
json: Object.assign({
|
||||
resourceId: this.resourceId_,
|
||||
}, policy),
|
||||
qs: options,
|
||||
}, cb);
|
||||
}
|
||||
/**
|
||||
* Test a set of permissions for a resource.
|
||||
*
|
||||
* @throws {Error} If permissions are not provided.
|
||||
*
|
||||
* @param {string|string[]} permissions The permission(s) to test for.
|
||||
* @param {TestIamPermissionsOptions} [options] Configuration object.
|
||||
* @param {TestIamPermissionsCallback} [callback] Callback function.
|
||||
* @returns {Promise<TestIamPermissionsResponse>}
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions| Buckets: testIamPermissions API Documentation}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const bucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* //-
|
||||
* // Test a single permission.
|
||||
* //-
|
||||
* const test = 'storage.buckets.delete';
|
||||
*
|
||||
* bucket.iam.testPermissions(test, function(err, permissions, apiResponse) {
|
||||
* console.log(permissions);
|
||||
* // {
|
||||
* // "storage.buckets.delete": true
|
||||
* // }
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // Test several permissions at once.
|
||||
* //-
|
||||
* const tests = [
|
||||
* 'storage.buckets.delete',
|
||||
* 'storage.buckets.get'
|
||||
* ];
|
||||
*
|
||||
* bucket.iam.testPermissions(tests, function(err, permissions) {
|
||||
* console.log(permissions);
|
||||
* // {
|
||||
* // "storage.buckets.delete": false,
|
||||
* // "storage.buckets.get": true
|
||||
* // }
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* bucket.iam.testPermissions(test).then(function(data) {
|
||||
* const permissions = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
testPermissions(permissions, optionsOrCallback, callback) {
|
||||
if (!Array.isArray(permissions) && typeof permissions !== 'string') {
|
||||
throw new Error('Permissions are required.');
|
||||
}
|
||||
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
|
||||
const permissionsArray = arrify(permissions);
|
||||
const req = Object.assign({
|
||||
permissions: permissionsArray,
|
||||
}, options);
|
||||
this.request_({
|
||||
uri: '/iam/testPermissions',
|
||||
qs: req,
|
||||
useQuerystring: true,
|
||||
}, (err, resp) => {
|
||||
if (err) {
|
||||
cb(err, null, resp);
|
||||
return;
|
||||
}
|
||||
const availablePermissions = arrify(resp.permissions);
|
||||
const permissionsHash = permissionsArray.reduce((acc, permission) => {
|
||||
acc[permission] = availablePermissions.indexOf(permission) > -1;
|
||||
return acc;
|
||||
}, {});
|
||||
cb(null, permissionsHash, resp);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Iam = Iam;
|
||||
/*! Developer Documentation
|
||||
*
|
||||
* All async methods (except for streams) will return a Promise in the event
|
||||
* that a callback is omitted.
|
||||
*/
|
||||
promisify_1.promisifyAll(Iam);
|
||||
//# sourceMappingURL=iam.js.map
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* The `@google-cloud/storage` package has a single named export which is the
|
||||
* {@link Storage} (ES6) class, which should be instantiated with `new`.
|
||||
*
|
||||
* See {@link Storage} and {@link ClientConfig} for client methods and
|
||||
* configuration options.
|
||||
*
|
||||
* @module {Storage} @google-cloud/storage
|
||||
* @alias nodejs-storage
|
||||
*
|
||||
* @example
|
||||
* Install the client library with <a href="https://www.npmjs.com/">npm</a>:
|
||||
* ```
|
||||
* npm install --save @google-cloud/storage
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* Import the client library
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* Create a client that uses <a
|
||||
* href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
|
||||
* Default Credentials (ADC)</a>:
|
||||
* ```
|
||||
* const storage = new Storage();
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* Create a client with <a
|
||||
* href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
|
||||
* credentials</a>:
|
||||
* ```
|
||||
* const storage = new Storage({ projectId:
|
||||
* 'your-project-id', keyFilename: '/path/to/keyfile.json'
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example <caption>include:samples/quickstart.js</caption>
|
||||
* region_tag:storage_quickstart
|
||||
* Full quickstart example:
|
||||
*/
|
||||
export { AccessControlObject, AclOptions, AddAclCallback, AddAclOptions, AddAclResponse, GetAclCallback, GetAclOptions, GetAclResponse, RemoveAclCallback, RemoveAclOptions, RemoveAclResponse, UpdateAclCallback, UpdateAclOptions, UpdateAclResponse, } from './acl';
|
||||
export { Bucket, BucketExistsCallback, BucketExistsOptions, BucketExistsResponse, BucketLockCallback, BucketLockResponse, CombineCallback, CombineOptions, CombineResponse, CreateChannelCallback, CreateChannelConfig, CreateChannelOptions, CreateChannelResponse, CreateNotificationCallback, CreateNotificationOptions, CreateNotificationResponse, DeleteBucketCallback, DeleteBucketOptions, DeleteBucketResponse, DeleteFilesCallback, DeleteFilesOptions, DeleteLabelsCallback, DeleteLabelsResponse, DisableRequesterPaysCallback, DisableRequesterPaysResponse, EnableRequesterPaysCallback, EnableRequesterPaysResponse, GetBucketCallback, GetBucketMetadataCallback, GetBucketMetadataOptions, GetBucketMetadataResponse, GetBucketOptions, GetBucketResponse, GetBucketSignedUrlConfig, GetFilesCallback, GetFilesOptions, GetFilesResponse, GetLabelsCallback, GetLabelsOptions, GetLabelsResponse, GetNotificationsCallback, GetNotificationsOptions, GetNotificationsResponse, Labels, MakeBucketPrivateCallback, MakeBucketPrivateOptions, MakeBucketPrivateResponse, MakeBucketPublicCallback, MakeBucketPublicOptions, MakeBucketPublicResponse, SetBucketMetadataCallback, SetBucketMetadataOptions, SetBucketMetadataResponse, SetBucketStorageClassCallback, SetBucketStorageClassOptions, SetLabelsCallback, SetLabelsOptions, SetLabelsResponse, UploadCallback, UploadOptions, UploadResponse, } from './bucket';
|
||||
export { Channel, StopCallback } from './channel';
|
||||
export { CopyCallback, CopyOptions, CopyResponse, CreateReadStreamOptions, CreateResumableUploadCallback, CreateResumableUploadOptions, CreateResumableUploadResponse, CreateWriteStreamOptions, DeleteFileCallback, DeleteFileOptions, DeleteFileResponse, DownloadCallback, DownloadOptions, DownloadResponse, EncryptionKeyOptions, File, FileExistsCallback, FileExistsOptions, FileExistsResponse, FileOptions, GetExpirationDateCallback, GetExpirationDateResponse, GetFileCallback, GetFileMetadataCallback, GetFileMetadataOptions, GetFileMetadataResponse, GetFileOptions, GetFileResponse, GetSignedPolicyCallback, GetSignedPolicyOptions, GetSignedPolicyResponse, GenerateSignedPostPolicyV2Callback, GenerateSignedPostPolicyV2Options, GenerateSignedPostPolicyV2Response, GenerateSignedPostPolicyV4Callback, GenerateSignedPostPolicyV4Options, GenerateSignedPostPolicyV4Response, GetSignedUrlConfig, MakeFilePrivateCallback, MakeFilePrivateOptions, MakeFilePrivateResponse, MakeFilePublicCallback, MakeFilePublicResponse, MoveCallback, MoveOptions, MoveResponse, PolicyDocument, PolicyFields, PredefinedAcl, RotateEncryptionKeyCallback, RotateEncryptionKeyOptions, RotateEncryptionKeyResponse, SaveCallback, SaveOptions, SetFileMetadataCallback, SetFileMetadataOptions, SetFileMetadataResponse, SetStorageClassCallback, SetStorageClassOptions, SetStorageClassResponse, SignedPostPolicyV4Output, } from './file';
|
||||
export { HmacKey, HmacKeyMetadata, HmacKeyMetadataCallback, HmacKeyMetadataResponse, SetHmacKeyMetadata, SetHmacKeyMetadataOptions, } from './hmacKey';
|
||||
export { GetPolicyCallback, GetPolicyOptions, GetPolicyResponse, Iam, Policy, SetPolicyCallback, SetPolicyOptions, SetPolicyResponse, TestIamPermissionsCallback, TestIamPermissionsOptions, TestIamPermissionsResponse, } from './iam';
|
||||
export { DeleteNotificationCallback, DeleteNotificationOptions, GetNotificationCallback, GetNotificationMetadataCallback, GetNotificationMetadataOptions, GetNotificationMetadataResponse, GetNotificationOptions, GetNotificationResponse, Notification, } from './notification';
|
||||
export { BucketCallback, BucketOptions, CreateBucketQuery, CreateBucketRequest, CreateBucketResponse, CreateHmacKeyCallback, CreateHmacKeyOptions, CreateHmacKeyResponse, GetBucketsCallback, GetBucketsRequest, GetBucketsResponse, GetHmacKeysCallback, GetHmacKeysOptions, GetHmacKeysResponse, GetServiceAccountCallback, GetServiceAccountOptions, GetServiceAccountResponse, HmacKeyResourceResponse, ServiceAccount, Storage, StorageOptions, } from './storage';
|
||||
export { GetSignedUrlCallback, GetSignedUrlResponse } from './signer';
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var bucket_1 = require("./bucket");
|
||||
Object.defineProperty(exports, "Bucket", { enumerable: true, get: function () { return bucket_1.Bucket; } });
|
||||
var channel_1 = require("./channel");
|
||||
Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return channel_1.Channel; } });
|
||||
var file_1 = require("./file");
|
||||
Object.defineProperty(exports, "File", { enumerable: true, get: function () { return file_1.File; } });
|
||||
var hmacKey_1 = require("./hmacKey");
|
||||
Object.defineProperty(exports, "HmacKey", { enumerable: true, get: function () { return hmacKey_1.HmacKey; } });
|
||||
var iam_1 = require("./iam");
|
||||
Object.defineProperty(exports, "Iam", { enumerable: true, get: function () { return iam_1.Iam; } });
|
||||
var notification_1 = require("./notification");
|
||||
Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return notification_1.Notification; } });
|
||||
var storage_1 = require("./storage");
|
||||
Object.defineProperty(exports, "Storage", { enumerable: true, get: function () { return storage_1.Storage; } });
|
||||
//# sourceMappingURL=index.js.map
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import { Metadata, MetadataCallback, ServiceObject } from '@google-cloud/common';
|
||||
import { ResponseBody } from '@google-cloud/common/build/src/util';
|
||||
import { Bucket } from './bucket';
|
||||
export interface DeleteNotificationOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface GetNotificationMetadataOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} GetNotificationMetadataResponse
|
||||
* @property {object} 0 The notification metadata.
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
export declare type GetNotificationMetadataResponse = [ResponseBody, Metadata];
|
||||
/**
|
||||
* @callback GetNotificationMetadataCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} files The notification metadata.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface GetNotificationMetadataCallback {
|
||||
(err: Error | null, metadata?: ResponseBody, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* @typedef {array} GetNotificationResponse
|
||||
* @property {Notification} 0 The {@link Notification}
|
||||
* @property {object} 1 The full API response.
|
||||
*/
|
||||
export declare type GetNotificationResponse = [Notification, Metadata];
|
||||
export interface GetNotificationOptions {
|
||||
/**
|
||||
* Automatically create the object if it does not exist. Default: `false`.
|
||||
*/
|
||||
autoCreate?: boolean;
|
||||
/**
|
||||
* The ID of the project which will be billed for the request.
|
||||
*/
|
||||
userProject?: string;
|
||||
}
|
||||
/**
|
||||
* @callback GetNotificationCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {Notification} notification The {@link Notification}.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface GetNotificationCallback {
|
||||
(err: Error | null, notification?: Notification | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* @callback DeleteNotificationCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
export interface DeleteNotificationCallback {
|
||||
(err: Error | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
/**
|
||||
* The API-formatted resource description of the notification.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name Notification#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* A Notification object is created from your {@link Bucket} object using
|
||||
* {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub
|
||||
* notifications.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage}
|
||||
*
|
||||
* @class
|
||||
* @hideconstructor
|
||||
*
|
||||
* @param {Bucket} bucket The bucket instance this notification is attached to.
|
||||
* @param {string} id The ID of the notification.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const notification = myBucket.notification('1');
|
||||
* ```
|
||||
*/
|
||||
declare class Notification extends ServiceObject {
|
||||
constructor(bucket: Bucket, id: string);
|
||||
delete(options?: DeleteNotificationOptions): Promise<[Metadata]>;
|
||||
delete(options: DeleteNotificationOptions, callback: DeleteNotificationCallback): void;
|
||||
delete(callback: DeleteNotificationCallback): void;
|
||||
get(options?: GetNotificationOptions): Promise<GetNotificationResponse>;
|
||||
get(options: GetNotificationOptions, callback: GetNotificationCallback): void;
|
||||
get(callback: GetNotificationCallback): void;
|
||||
getMetadata(options?: GetNotificationMetadataOptions): Promise<GetNotificationMetadataResponse>;
|
||||
getMetadata(options: GetNotificationMetadataOptions, callback: MetadataCallback): void;
|
||||
getMetadata(callback: MetadataCallback): void;
|
||||
}
|
||||
/**
|
||||
* Reference to the {@link Notification} class.
|
||||
* @name module:@google-cloud/storage.Notification
|
||||
* @see Notification
|
||||
*/
|
||||
export { Notification };
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Notification = void 0;
|
||||
const common_1 = require("@google-cloud/common");
|
||||
const promisify_1 = require("@google-cloud/promisify");
|
||||
/**
|
||||
* The API-formatted resource description of the notification.
|
||||
*
|
||||
* Note: This is not guaranteed to be up-to-date when accessed. To get the
|
||||
* latest record, call the `getMetadata()` method.
|
||||
*
|
||||
* @name Notification#metadata
|
||||
* @type {object}
|
||||
*/
|
||||
/**
|
||||
* A Notification object is created from your {@link Bucket} object using
|
||||
* {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub
|
||||
* notifications.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage}
|
||||
*
|
||||
* @class
|
||||
* @hideconstructor
|
||||
*
|
||||
* @param {Bucket} bucket The bucket instance this notification is attached to.
|
||||
* @param {string} id The ID of the notification.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
*
|
||||
* const notification = myBucket.notification('1');
|
||||
* ```
|
||||
*/
|
||||
class Notification extends common_1.ServiceObject {
|
||||
constructor(bucket, id) {
|
||||
const methods = {
|
||||
/**
|
||||
* Creates a notification subscription for the bucket.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert}
|
||||
* @method Notification#create
|
||||
*
|
||||
* @param {Topic|string} topic The Cloud PubSub topic to which this
|
||||
* subscription publishes. If the project ID is omitted, the current
|
||||
* project ID will be used.
|
||||
*
|
||||
* Acceptable formats are:
|
||||
* - `projects/grape-spaceship-123/topics/my-topic`
|
||||
*
|
||||
* - `my-topic`
|
||||
* @param {CreateNotificationRequest} [options] Metadata to set for
|
||||
* the notification.
|
||||
* @param {CreateNotificationCallback} [callback] Callback function.
|
||||
* @returns {Promise<CreateNotificationResponse>}
|
||||
* @throws {Error} If a valid topic is not provided.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const notification = myBucket.notification('1');
|
||||
*
|
||||
* notification.create(function(err, notification, apiResponse) {
|
||||
* if (!err) {
|
||||
* // The notification was created successfully.
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* notification.create().then(function(data) {
|
||||
* const notification = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
create: true,
|
||||
/**
|
||||
* @typedef {array} NotificationExistsResponse
|
||||
* @property {boolean} 0 Whether the notification exists or not.
|
||||
*/
|
||||
/**
|
||||
* @callback NotificationExistsCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {boolean} exists Whether the notification exists or not.
|
||||
*/
|
||||
/**
|
||||
* Check if the notification exists.
|
||||
*
|
||||
* @method Notification#exists
|
||||
* @param {NotificationExistsCallback} [callback] Callback function.
|
||||
* @returns {Promise<NotificationExistsResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const notification = myBucket.notification('1');
|
||||
*
|
||||
* notification.exists(function(err, exists) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* notification.exists().then(function(data) {
|
||||
* const exists = data[0];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
exists: true,
|
||||
};
|
||||
super({
|
||||
parent: bucket,
|
||||
baseUrl: '/notificationConfigs',
|
||||
id: id.toString(),
|
||||
createMethod: bucket.createNotification.bind(bucket),
|
||||
methods,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @typedef {array} DeleteNotificationResponse
|
||||
* @property {object} 0 The full API response.
|
||||
*/
|
||||
/**
|
||||
* Permanently deletes a notification subscription.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/delete| Notifications: delete API Documentation}
|
||||
*
|
||||
* @param {object} [options] Configuration options.
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {DeleteNotificationCallback} [callback] Callback function.
|
||||
* @returns {Promise<DeleteNotificationResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const notification = myBucket.notification('1');
|
||||
*
|
||||
* notification.delete(function(err, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* notification.delete().then(function(data) {
|
||||
* const apiResponse = data[0];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/deleteNotification.js</caption>
|
||||
* region_tag:storage_delete_bucket_notification
|
||||
* Another example:
|
||||
*/
|
||||
delete(optionsOrCallback, callback) {
|
||||
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
|
||||
callback =
|
||||
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
|
||||
this.request({
|
||||
method: 'DELETE',
|
||||
uri: '',
|
||||
qs: options,
|
||||
}, callback || common_1.util.noop);
|
||||
}
|
||||
/**
|
||||
* Get a notification and its metadata if it exists.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation}
|
||||
*
|
||||
* @param {object} [options] Configuration options.
|
||||
* See {@link Bucket#createNotification} for create options.
|
||||
* @param {boolean} [options.autoCreate] Automatically create the object if
|
||||
* it does not exist. Default: `false`.
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {GetNotificationCallback} [callback] Callback function.
|
||||
* @return {Promise<GetNotificationCallback>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const notification = myBucket.notification('1');
|
||||
*
|
||||
* notification.get(function(err, notification, apiResponse) {
|
||||
* // `notification.metadata` has been populated.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* notification.get().then(function(data) {
|
||||
* const notification = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get(optionsOrCallback, callback) {
|
||||
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
|
||||
callback =
|
||||
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
|
||||
const autoCreate = options.autoCreate;
|
||||
delete options.autoCreate;
|
||||
const onCreate = (err, notification, apiResponse) => {
|
||||
if (err) {
|
||||
if (err.code === 409) {
|
||||
this.get(options, callback);
|
||||
return;
|
||||
}
|
||||
callback(err, null, apiResponse);
|
||||
return;
|
||||
}
|
||||
callback(null, notification, apiResponse);
|
||||
};
|
||||
this.getMetadata(options, (err, metadata) => {
|
||||
if (err) {
|
||||
if (err.code === 404 && autoCreate) {
|
||||
const args = [];
|
||||
if (Object.keys(options).length > 0) {
|
||||
args.push(options);
|
||||
}
|
||||
args.push(onCreate);
|
||||
// eslint-disable-next-line
|
||||
this.create.apply(this, args);
|
||||
return;
|
||||
}
|
||||
callback(err, null, metadata);
|
||||
return;
|
||||
}
|
||||
callback(null, this, metadata);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Get the notification's metadata.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation}
|
||||
*
|
||||
* @param {object} [options] Configuration options.
|
||||
* @param {string} [options.userProject] The ID of the project which will be
|
||||
* billed for the request.
|
||||
* @param {GetNotificationMetadataCallback} [callback] Callback function.
|
||||
* @returns {Promise<GetNotificationMetadataResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const myBucket = storage.bucket('my-bucket');
|
||||
* const notification = myBucket.notification('1');
|
||||
*
|
||||
* notification.getMetadata(function(err, metadata, apiResponse) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* notification.getMetadata().then(function(data) {
|
||||
* const metadata = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
*
|
||||
* ```
|
||||
* @example <caption>include:samples/getMetadataNotifications.js</caption>
|
||||
* region_tag:storage_print_pubsub_bucket_notification
|
||||
* Another example:
|
||||
*/
|
||||
getMetadata(optionsOrCallback, callback) {
|
||||
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
|
||||
callback =
|
||||
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
|
||||
this.request({
|
||||
uri: '',
|
||||
qs: options,
|
||||
}, (err, resp) => {
|
||||
if (err) {
|
||||
callback(err, null, resp);
|
||||
return;
|
||||
}
|
||||
this.metadata = resp;
|
||||
callback(null, this.metadata, resp);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Notification = Notification;
|
||||
/*! Developer Documentation
|
||||
*
|
||||
* All async methods (except for streams) will return a Promise in the event
|
||||
* that a callback is omitted.
|
||||
*/
|
||||
promisify_1.promisifyAll(Notification);
|
||||
//# sourceMappingURL=notification.js.map
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/// <reference types="node" />
|
||||
import * as http from 'http';
|
||||
interface GetCredentialsResponse {
|
||||
client_email?: string;
|
||||
}
|
||||
export interface AuthClient {
|
||||
sign(blobToSign: string): Promise<string>;
|
||||
getCredentials(): Promise<GetCredentialsResponse>;
|
||||
}
|
||||
export interface BucketI {
|
||||
name: string;
|
||||
}
|
||||
export interface FileI {
|
||||
name: string;
|
||||
}
|
||||
export interface Query {
|
||||
[key: string]: string;
|
||||
}
|
||||
export interface GetSignedUrlConfigInternal {
|
||||
expiration: number;
|
||||
accessibleAt?: Date;
|
||||
method: string;
|
||||
extensionHeaders?: http.OutgoingHttpHeaders;
|
||||
queryParams?: Query;
|
||||
cname?: string;
|
||||
contentMd5?: string;
|
||||
contentType?: string;
|
||||
bucket: string;
|
||||
file?: string;
|
||||
}
|
||||
export interface SignerGetSignedUrlConfig {
|
||||
method: 'GET' | 'PUT' | 'DELETE' | 'POST';
|
||||
expires: string | number | Date;
|
||||
accessibleAt?: string | number | Date;
|
||||
virtualHostedStyle?: boolean;
|
||||
version?: 'v2' | 'v4';
|
||||
cname?: string;
|
||||
extensionHeaders?: http.OutgoingHttpHeaders;
|
||||
queryParams?: Query;
|
||||
contentMd5?: string;
|
||||
contentType?: string;
|
||||
}
|
||||
export declare type SignerGetSignedUrlResponse = string;
|
||||
export declare type GetSignedUrlResponse = [SignerGetSignedUrlResponse];
|
||||
export interface GetSignedUrlCallback {
|
||||
(err: Error | null, url?: string): void;
|
||||
}
|
||||
/**
|
||||
* @const {string}
|
||||
* @private
|
||||
*/
|
||||
export declare const PATH_STYLED_HOST = "https://storage.googleapis.com";
|
||||
export declare class URLSigner {
|
||||
private authClient;
|
||||
private bucket;
|
||||
private file?;
|
||||
constructor(authClient: AuthClient, bucket: BucketI, file?: FileI);
|
||||
getSignedUrl(cfg: SignerGetSignedUrlConfig): Promise<SignerGetSignedUrlResponse>;
|
||||
private getSignedUrlV2;
|
||||
private getSignedUrlV4;
|
||||
/**
|
||||
* Create canonical headers for signing v4 url.
|
||||
*
|
||||
* The canonical headers for v4-signing a request demands header names are
|
||||
* first lowercased, followed by sorting the header names.
|
||||
* Then, construct the canonical headers part of the request:
|
||||
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
|
||||
* ..
|
||||
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
|
||||
*
|
||||
* @param headers
|
||||
* @private
|
||||
*/
|
||||
getCanonicalHeaders(headers: http.OutgoingHttpHeaders): string;
|
||||
getCanonicalRequest(method: string, path: string, query: string, headers: string, signedHeaders: string, contentSha256?: string): string;
|
||||
getCanonicalQueryParams(query: Query): string;
|
||||
getResourcePath(cname: boolean, bucket: string, file?: string): string;
|
||||
parseExpires(expires: string | number | Date, current?: Date): number;
|
||||
parseAccessibleAt(accessibleAt?: string | number | Date): number;
|
||||
}
|
||||
/**
|
||||
* Custom error type for errors related to getting signed errors and policies.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
export declare class SigningError extends Error {
|
||||
name: string;
|
||||
}
|
||||
export {};
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
"use strict";
|
||||
// Copyright 2020 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SigningError = exports.URLSigner = exports.PATH_STYLED_HOST = void 0;
|
||||
const crypto = require("crypto");
|
||||
const dateFormat = require("date-and-time");
|
||||
const url = require("url");
|
||||
const util_1 = require("./util");
|
||||
/*
|
||||
* Default signing version for getSignedUrl is 'v2'.
|
||||
*/
|
||||
const DEFAULT_SIGNING_VERSION = 'v2';
|
||||
const SEVEN_DAYS = 604800;
|
||||
/**
|
||||
* @const {string}
|
||||
* @private
|
||||
*/
|
||||
exports.PATH_STYLED_HOST = 'https://storage.googleapis.com';
|
||||
class URLSigner {
|
||||
constructor(authClient, bucket, file) {
|
||||
this.bucket = bucket;
|
||||
this.file = file;
|
||||
this.authClient = authClient;
|
||||
}
|
||||
getSignedUrl(cfg) {
|
||||
const expiresInSeconds = this.parseExpires(cfg.expires);
|
||||
const method = cfg.method;
|
||||
const accessibleAtInSeconds = this.parseAccessibleAt(cfg.accessibleAt);
|
||||
if (expiresInSeconds < accessibleAtInSeconds) {
|
||||
throw new Error('An expiration date cannot be before accessible date.');
|
||||
}
|
||||
let customHost;
|
||||
// Default style is `path`.
|
||||
const isVirtualHostedStyle = cfg.virtualHostedStyle || false;
|
||||
if (cfg.cname) {
|
||||
customHost = cfg.cname;
|
||||
}
|
||||
else if (isVirtualHostedStyle) {
|
||||
customHost = `https://${this.bucket.name}.storage.googleapis.com`;
|
||||
}
|
||||
const secondsToMilliseconds = 1000;
|
||||
const config = Object.assign({}, cfg, {
|
||||
method,
|
||||
expiration: expiresInSeconds,
|
||||
accessibleAt: new Date(secondsToMilliseconds * accessibleAtInSeconds),
|
||||
bucket: this.bucket.name,
|
||||
file: this.file ? util_1.encodeURI(this.file.name, false) : undefined,
|
||||
});
|
||||
if (customHost) {
|
||||
config.cname = customHost;
|
||||
}
|
||||
const version = cfg.version || DEFAULT_SIGNING_VERSION;
|
||||
let promise;
|
||||
if (version === 'v2') {
|
||||
promise = this.getSignedUrlV2(config);
|
||||
}
|
||||
else if (version === 'v4') {
|
||||
promise = this.getSignedUrlV4(config);
|
||||
}
|
||||
else {
|
||||
throw new Error(`Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`);
|
||||
}
|
||||
return promise.then(query => {
|
||||
query = Object.assign(query, cfg.queryParams);
|
||||
const signedUrl = new url.URL(config.cname || exports.PATH_STYLED_HOST);
|
||||
signedUrl.pathname = this.getResourcePath(!!config.cname, this.bucket.name, config.file);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
signedUrl.search = util_1.qsStringify(query);
|
||||
return signedUrl.href;
|
||||
});
|
||||
}
|
||||
getSignedUrlV2(config) {
|
||||
const canonicalHeadersString = this.getCanonicalHeaders(config.extensionHeaders || {});
|
||||
const resourcePath = this.getResourcePath(false, config.bucket, config.file);
|
||||
const blobToSign = [
|
||||
config.method,
|
||||
config.contentMd5 || '',
|
||||
config.contentType || '',
|
||||
config.expiration,
|
||||
canonicalHeadersString + resourcePath,
|
||||
].join('\n');
|
||||
const sign = async () => {
|
||||
const authClient = this.authClient;
|
||||
try {
|
||||
const signature = await authClient.sign(blobToSign);
|
||||
const credentials = await authClient.getCredentials();
|
||||
return {
|
||||
GoogleAccessId: credentials.client_email,
|
||||
Expires: config.expiration,
|
||||
Signature: signature,
|
||||
};
|
||||
}
|
||||
catch (err) {
|
||||
const signingErr = new SigningError(err.message);
|
||||
signingErr.stack = err.stack;
|
||||
throw signingErr;
|
||||
}
|
||||
};
|
||||
return sign();
|
||||
}
|
||||
getSignedUrlV4(config) {
|
||||
config.accessibleAt = config.accessibleAt
|
||||
? config.accessibleAt
|
||||
: new Date();
|
||||
const millisecondsToSeconds = 1.0 / 1000.0;
|
||||
const expiresPeriodInSeconds = config.expiration - config.accessibleAt.valueOf() * millisecondsToSeconds;
|
||||
// v4 limit expiration to be 7 days maximum
|
||||
if (expiresPeriodInSeconds > SEVEN_DAYS) {
|
||||
throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`);
|
||||
}
|
||||
const extensionHeaders = Object.assign({}, config.extensionHeaders);
|
||||
const fqdn = new url.URL(config.cname || exports.PATH_STYLED_HOST);
|
||||
extensionHeaders.host = fqdn.host;
|
||||
if (config.contentMd5) {
|
||||
extensionHeaders['content-md5'] = config.contentMd5;
|
||||
}
|
||||
if (config.contentType) {
|
||||
extensionHeaders['content-type'] = config.contentType;
|
||||
}
|
||||
let contentSha256;
|
||||
const sha256Header = extensionHeaders['x-goog-content-sha256'];
|
||||
if (sha256Header) {
|
||||
if (typeof sha256Header !== 'string' ||
|
||||
!/[A-Fa-f0-9]{40}/.test(sha256Header)) {
|
||||
throw new Error('The header X-Goog-Content-SHA256 must be a hexadecimal string.');
|
||||
}
|
||||
contentSha256 = sha256Header;
|
||||
}
|
||||
const signedHeaders = Object.keys(extensionHeaders)
|
||||
.map(header => header.toLowerCase())
|
||||
.sort()
|
||||
.join(';');
|
||||
const extensionHeadersString = this.getCanonicalHeaders(extensionHeaders);
|
||||
const datestamp = dateFormat.format(config.accessibleAt, 'YYYYMMDD', true);
|
||||
const credentialScope = `${datestamp}/auto/storage/goog4_request`;
|
||||
const sign = async () => {
|
||||
const credentials = await this.authClient.getCredentials();
|
||||
const credential = `${credentials.client_email}/${credentialScope}`;
|
||||
const dateISO = dateFormat.format(config.accessibleAt ? config.accessibleAt : new Date(), 'YYYYMMDD[T]HHmmss[Z]', true);
|
||||
const queryParams = {
|
||||
'X-Goog-Algorithm': 'GOOG4-RSA-SHA256',
|
||||
'X-Goog-Credential': credential,
|
||||
'X-Goog-Date': dateISO,
|
||||
'X-Goog-Expires': expiresPeriodInSeconds.toString(10),
|
||||
'X-Goog-SignedHeaders': signedHeaders,
|
||||
...(config.queryParams || {}),
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const canonicalQueryParams = this.getCanonicalQueryParams(queryParams);
|
||||
const canonicalRequest = this.getCanonicalRequest(config.method, this.getResourcePath(!!config.cname, config.bucket, config.file), canonicalQueryParams, extensionHeadersString, signedHeaders, contentSha256);
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(canonicalRequest)
|
||||
.digest('hex');
|
||||
const blobToSign = [
|
||||
'GOOG4-RSA-SHA256',
|
||||
dateISO,
|
||||
credentialScope,
|
||||
hash,
|
||||
].join('\n');
|
||||
try {
|
||||
const signature = await this.authClient.sign(blobToSign);
|
||||
const signatureHex = Buffer.from(signature, 'base64').toString('hex');
|
||||
const signedQuery = Object.assign({}, queryParams, {
|
||||
'X-Goog-Signature': signatureHex,
|
||||
});
|
||||
return signedQuery;
|
||||
}
|
||||
catch (err) {
|
||||
const signingErr = new SigningError(err.message);
|
||||
signingErr.stack = err.stack;
|
||||
throw signingErr;
|
||||
}
|
||||
};
|
||||
return sign();
|
||||
}
|
||||
/**
|
||||
* Create canonical headers for signing v4 url.
|
||||
*
|
||||
* The canonical headers for v4-signing a request demands header names are
|
||||
* first lowercased, followed by sorting the header names.
|
||||
* Then, construct the canonical headers part of the request:
|
||||
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
|
||||
* ..
|
||||
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
|
||||
*
|
||||
* @param headers
|
||||
* @private
|
||||
*/
|
||||
getCanonicalHeaders(headers) {
|
||||
// Sort headers by their lowercased names
|
||||
const sortedHeaders = util_1.objectEntries(headers)
|
||||
// Convert header names to lowercase
|
||||
.map(([headerName, value]) => [
|
||||
headerName.toLowerCase(),
|
||||
value,
|
||||
])
|
||||
.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
return sortedHeaders
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.map(([headerName, value]) => {
|
||||
// - Convert Array (multi-valued header) into string, delimited by
|
||||
// ',' (no space).
|
||||
// - Trim leading and trailing spaces.
|
||||
// - Convert sequential (2+) spaces into a single space
|
||||
const canonicalValue = `${value}`.trim().replace(/\s{2,}/g, ' ');
|
||||
return `${headerName}:${canonicalValue}\n`;
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
getCanonicalRequest(method, path, query, headers, signedHeaders, contentSha256) {
|
||||
return [
|
||||
method,
|
||||
path,
|
||||
query,
|
||||
headers,
|
||||
signedHeaders,
|
||||
contentSha256 || 'UNSIGNED-PAYLOAD',
|
||||
].join('\n');
|
||||
}
|
||||
getCanonicalQueryParams(query) {
|
||||
return util_1.objectEntries(query)
|
||||
.map(([key, value]) => [util_1.encodeURI(key, true), util_1.encodeURI(value, true)])
|
||||
.sort((a, b) => (a[0] < b[0] ? -1 : 1))
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('&');
|
||||
}
|
||||
getResourcePath(cname, bucket, file) {
|
||||
if (cname) {
|
||||
return '/' + (file || '');
|
||||
}
|
||||
else if (file) {
|
||||
return `/${bucket}/${file}`;
|
||||
}
|
||||
else {
|
||||
return `/${bucket}`;
|
||||
}
|
||||
}
|
||||
parseExpires(expires, current = new Date()) {
|
||||
const expiresInMSeconds = new Date(expires).valueOf();
|
||||
if (isNaN(expiresInMSeconds)) {
|
||||
throw new Error('The expiration date provided was invalid.');
|
||||
}
|
||||
if (expiresInMSeconds < current.valueOf()) {
|
||||
throw new Error('An expiration date cannot be in the past.');
|
||||
}
|
||||
return Math.round(expiresInMSeconds / 1000); // The API expects seconds.
|
||||
}
|
||||
parseAccessibleAt(accessibleAt) {
|
||||
const accessibleAtInMSeconds = new Date(accessibleAt || new Date()).valueOf();
|
||||
if (isNaN(accessibleAtInMSeconds)) {
|
||||
throw new Error('The accessible at date provided was invalid.');
|
||||
}
|
||||
return Math.floor(accessibleAtInMSeconds / 1000); // The API expects seconds.
|
||||
}
|
||||
}
|
||||
exports.URLSigner = URLSigner;
|
||||
/**
|
||||
* Custom error type for errors related to getting signed errors and policies.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
class SigningError extends Error {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.name = 'SigningError';
|
||||
}
|
||||
}
|
||||
exports.SigningError = SigningError;
|
||||
//# sourceMappingURL=signer.js.map
|
||||
+562
@@ -0,0 +1,562 @@
|
||||
/// <reference types="node" />
|
||||
import { ApiError, Metadata, Service, ServiceOptions } from '@google-cloud/common';
|
||||
import { Readable } from 'stream';
|
||||
import { Bucket } from './bucket';
|
||||
import { Channel } from './channel';
|
||||
import { File } from './file';
|
||||
import { HmacKey, HmacKeyMetadata, HmacKeyOptions } from './hmacKey';
|
||||
export interface GetServiceAccountOptions {
|
||||
userProject?: string;
|
||||
}
|
||||
export interface ServiceAccount {
|
||||
emailAddress?: string;
|
||||
}
|
||||
export declare type GetServiceAccountResponse = [ServiceAccount, Metadata];
|
||||
export interface GetServiceAccountCallback {
|
||||
(err: Error | null, serviceAccount?: ServiceAccount, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface CreateBucketQuery {
|
||||
project: string;
|
||||
userProject: string;
|
||||
}
|
||||
export declare enum IdempotencyStrategy {
|
||||
RetryAlways = 0,
|
||||
RetryConditional = 1,
|
||||
RetryNever = 2
|
||||
}
|
||||
export interface RetryOptions {
|
||||
retryDelayMultiplier?: number;
|
||||
totalTimeout?: number;
|
||||
maxRetryDelay?: number;
|
||||
autoRetry?: boolean;
|
||||
maxRetries?: number;
|
||||
retryableErrorFn?: (err: ApiError) => boolean;
|
||||
idempotencyStrategy?: IdempotencyStrategy;
|
||||
}
|
||||
export interface PreconditionOptions {
|
||||
ifGenerationMatch?: number;
|
||||
ifGenerationNotMatch?: number;
|
||||
ifMetagenerationMatch?: number;
|
||||
ifMetagenerationNotMatch?: number;
|
||||
}
|
||||
export interface StorageOptions extends ServiceOptions {
|
||||
retryOptions?: RetryOptions;
|
||||
/**
|
||||
* @deprecated Use retryOptions instead.
|
||||
* @internal
|
||||
*/
|
||||
autoRetry?: boolean;
|
||||
/**
|
||||
* @deprecated Use retryOptions instead.
|
||||
* @internal
|
||||
*/
|
||||
maxRetries?: number;
|
||||
/**
|
||||
* **This option is deprecated.**
|
||||
* @todo Remove in next major release.
|
||||
*/
|
||||
promise?: typeof Promise;
|
||||
/**
|
||||
* The API endpoint of the service used to make requests.
|
||||
* Defaults to `storage.googleapis.com`.
|
||||
*/
|
||||
apiEndpoint?: string;
|
||||
}
|
||||
export interface BucketOptions {
|
||||
kmsKeyName?: string;
|
||||
userProject?: string;
|
||||
preconditionOpts?: PreconditionOptions;
|
||||
}
|
||||
export interface Cors {
|
||||
maxAgeSeconds?: number;
|
||||
method?: string[];
|
||||
origin?: string[];
|
||||
responseHeader?: string[];
|
||||
}
|
||||
interface Versioning {
|
||||
enabled: boolean;
|
||||
}
|
||||
export interface CreateBucketRequest {
|
||||
archive?: boolean;
|
||||
coldline?: boolean;
|
||||
cors?: Cors[];
|
||||
dra?: boolean;
|
||||
multiRegional?: boolean;
|
||||
nearline?: boolean;
|
||||
regional?: boolean;
|
||||
requesterPays?: boolean;
|
||||
retentionPolicy?: object;
|
||||
standard?: boolean;
|
||||
storageClass?: string;
|
||||
userProject?: string;
|
||||
location?: string;
|
||||
versioning?: Versioning;
|
||||
}
|
||||
export declare type CreateBucketResponse = [Bucket, Metadata];
|
||||
export interface BucketCallback {
|
||||
(err: Error | null, bucket?: Bucket | null, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type GetBucketsResponse = [Bucket[], {}, Metadata];
|
||||
export interface GetBucketsCallback {
|
||||
(err: Error | null, buckets: Bucket[], nextQuery?: {}, apiResponse?: Metadata): void;
|
||||
}
|
||||
export interface GetBucketsRequest {
|
||||
prefix?: string;
|
||||
project?: string;
|
||||
autoPaginate?: boolean;
|
||||
maxApiCalls?: number;
|
||||
maxResults?: number;
|
||||
pageToken?: string;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface HmacKeyResourceResponse {
|
||||
metadata: HmacKeyMetadata;
|
||||
secret: string;
|
||||
}
|
||||
export declare type CreateHmacKeyResponse = [HmacKey, string, HmacKeyResourceResponse];
|
||||
export interface CreateHmacKeyOptions {
|
||||
projectId?: string;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface CreateHmacKeyCallback {
|
||||
(err: Error | null, hmacKey?: HmacKey | null, secret?: string | null, apiResponse?: HmacKeyResourceResponse): void;
|
||||
}
|
||||
export interface GetHmacKeysOptions {
|
||||
projectId?: string;
|
||||
serviceAccountEmail?: string;
|
||||
showDeletedKeys?: boolean;
|
||||
autoPaginate?: boolean;
|
||||
maxApiCalls?: number;
|
||||
maxResults?: number;
|
||||
pageToken?: string;
|
||||
userProject?: string;
|
||||
}
|
||||
export interface GetHmacKeysCallback {
|
||||
(err: Error | null, hmacKeys: HmacKey[] | null, nextQuery?: {}, apiResponse?: Metadata): void;
|
||||
}
|
||||
export declare type GetHmacKeysResponse = [HmacKey[]];
|
||||
export declare const PROTOCOL_REGEX: RegExp;
|
||||
/*! Developer Documentation
|
||||
*
|
||||
* Invoke this method to create a new Storage object bound with pre-determined
|
||||
* configuration options. For each object that can be created (e.g., a bucket),
|
||||
* there is an equivalent static and instance method. While they are classes,
|
||||
* they can be instantiated without use of the `new` keyword.
|
||||
*/
|
||||
/**
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share objects with other
|
||||
* users and allow other users to access your buckets and objects.
|
||||
*
|
||||
* This object provides constants to refer to the three permission levels that
|
||||
* can be granted to an entity:
|
||||
*
|
||||
* - `gcs.acl.OWNER_ROLE` - ("OWNER")
|
||||
* - `gcs.acl.READER_ROLE` - ("READER")
|
||||
* - `gcs.acl.WRITER_ROLE` - ("WRITER")
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists}
|
||||
*
|
||||
* @name Storage#acl
|
||||
* @type {object}
|
||||
* @property {string} OWNER_ROLE
|
||||
* @property {string} READER_ROLE
|
||||
* @property {string} WRITER_ROLE
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const albums = storage.bucket('albums');
|
||||
*
|
||||
* //-
|
||||
* // Make all of the files currently in a bucket publicly readable.
|
||||
* //-
|
||||
* const options = {
|
||||
* entity: 'allUsers',
|
||||
* role: storage.acl.READER_ROLE
|
||||
* };
|
||||
*
|
||||
* albums.acl.add(options, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // Make any new objects added to a bucket publicly readable.
|
||||
* //-
|
||||
* albums.acl.default.add(options, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // Grant a user ownership permissions to a bucket.
|
||||
* //-
|
||||
* albums.acl.add({
|
||||
* entity: '[email protected]',
|
||||
* role: storage.acl.OWNER_ROLE
|
||||
* }, function(err, aclObject) {});
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* albums.acl.add(options).then(function(data) {
|
||||
* const aclObject = data[0];
|
||||
* const apiResponse = data[1];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* Get {@link Bucket} objects for all of the buckets in your project as
|
||||
* a readable object stream.
|
||||
*
|
||||
* @method Storage#getBucketsStream
|
||||
* @param {GetBucketsRequest} [query] Query object for listing buckets.
|
||||
* @returns {ReadableStream} A readable stream that emits {@link Bucket}
|
||||
* instances.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* storage.getBucketsStream()
|
||||
* .on('error', console.error)
|
||||
* .on('data', function(bucket) {
|
||||
* // bucket is a Bucket object.
|
||||
* })
|
||||
* .on('end', function() {
|
||||
* // All buckets retrieved.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If you anticipate many results, you can end a stream early to prevent
|
||||
* // unnecessary processing and API requests.
|
||||
* //-
|
||||
* storage.getBucketsStream()
|
||||
* .on('data', function(bucket) {
|
||||
* this.end();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* Get {@link HmacKey} objects for all of the HMAC keys in the project in a
|
||||
* readable object stream.
|
||||
*
|
||||
* @method Storage#getHmacKeysStream
|
||||
* @param {GetHmacKeysOptions} [options] Configuration options.
|
||||
* @returns {ReadableStream} A readable stream that emits {@link HmacKey}
|
||||
* instances.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* storage.getHmacKeysStream()
|
||||
* .on('error', console.error)
|
||||
* .on('data', function(hmacKey) {
|
||||
* // hmacKey is an HmacKey object.
|
||||
* })
|
||||
* .on('end', function() {
|
||||
* // All HmacKey retrieved.
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // If you anticipate many results, you can end a stream early to prevent
|
||||
* // unnecessary processing and API requests.
|
||||
* //-
|
||||
* storage.getHmacKeysStream()
|
||||
* .on('data', function(bucket) {
|
||||
* this.end();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
/**
|
||||
* <h4>ACLs</h4>
|
||||
* Cloud Storage uses access control lists (ACLs) to manage object and
|
||||
* bucket access. ACLs are the mechanism you use to share files with other users
|
||||
* and allow other users to access your buckets and files.
|
||||
*
|
||||
* To learn more about ACLs, read this overview on
|
||||
* {@link https://cloud.google.com/storage/docs/access-control| Access Control}.
|
||||
*
|
||||
* See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview}
|
||||
* See {@link https://cloud.google.com/storage/docs/access-control| Access Control}
|
||||
*
|
||||
* @class
|
||||
*/
|
||||
export declare class Storage extends Service {
|
||||
/**
|
||||
* {@link Bucket} class.
|
||||
*
|
||||
* @name Storage.Bucket
|
||||
* @see Bucket
|
||||
* @type {Constructor}
|
||||
*/
|
||||
static Bucket: typeof Bucket;
|
||||
/**
|
||||
* {@link Channel} class.
|
||||
*
|
||||
* @name Storage.Channel
|
||||
* @see Channel
|
||||
* @type {Constructor}
|
||||
*/
|
||||
static Channel: typeof Channel;
|
||||
/**
|
||||
* {@link File} class.
|
||||
*
|
||||
* @name Storage.File
|
||||
* @see File
|
||||
* @type {Constructor}
|
||||
*/
|
||||
static File: typeof File;
|
||||
/**
|
||||
* {@link HmacKey} class.
|
||||
*
|
||||
* @name Storage.HmacKey
|
||||
* @see HmacKey
|
||||
* @type {Constructor}
|
||||
*/
|
||||
static HmacKey: typeof HmacKey;
|
||||
static acl: {
|
||||
OWNER_ROLE: string;
|
||||
READER_ROLE: string;
|
||||
WRITER_ROLE: string;
|
||||
};
|
||||
/**
|
||||
* Reference to {@link Storage.acl}.
|
||||
*
|
||||
* @name Storage#acl
|
||||
* @see Storage.acl
|
||||
*/
|
||||
acl: typeof Storage.acl;
|
||||
getBucketsStream(): Readable;
|
||||
getHmacKeysStream(): Readable;
|
||||
retryOptions: RetryOptions;
|
||||
/**
|
||||
* @typedef {object} StorageOptions
|
||||
* @property {string} [projectId] The project ID from the Google Developer's
|
||||
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
|
||||
* variable `GCLOUD_PROJECT` for your project ID. If your app is running
|
||||
* in an environment which supports {@link
|
||||
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
|
||||
* Application Default Credentials}, your project ID will be detected
|
||||
* automatically.
|
||||
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
|
||||
* downloaded from the Google Developers Console. If you provide a path to
|
||||
* a JSON file, the `projectId` option above is not necessary. NOTE: .pem and
|
||||
* .p12 require you to specify the `email` option as well.
|
||||
* @property {string} [email] Account email address. Required when using a .pem
|
||||
* or .p12 keyFilename.
|
||||
* @property {object} [credentials] Credentials object.
|
||||
* @property {string} [credentials.client_email]
|
||||
* @property {string} [credentials.private_key]
|
||||
* @property {object} [retryOptions] Options for customizing retries. Retriable server errors
|
||||
* will be retried with exponential delay between them dictated by the formula
|
||||
* max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout
|
||||
* has been reached. Retries will only happen if autoRetry is set to true.
|
||||
* @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the
|
||||
* response is related to rate limits or certain intermittent server
|
||||
* errors. We will exponentially backoff subsequent requests by default.
|
||||
* @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to
|
||||
* increase the delay time between the completion of failed requests, and the
|
||||
* initiation of the subsequent retrying request.
|
||||
* @property {number} [retryOptions.totalTimeout = 600] The total time, starting from
|
||||
* when the initial request is sent, after which an error will
|
||||
* be returned, regardless of the retrying attempts made meanwhile.
|
||||
* @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests.
|
||||
* When this value is reached, ``retryDelayMultiplier`` will no longer be used to
|
||||
* increase delay time.
|
||||
* @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries
|
||||
* attempted before returning the error.
|
||||
* @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given
|
||||
* error should be retried and false otherwise.
|
||||
* @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration
|
||||
* controls how conditionally idempotent operations are retried. Possible values are: RetryAlways -
|
||||
* will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional -
|
||||
* will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never
|
||||
* retry a conditionally idempotent operation.
|
||||
* @property {string} [userAgent] The value to be prepended to the User-Agent
|
||||
* header in API requests.
|
||||
* @property {object} [authClient] GoogleAuth client to reuse instead of creating a new one.
|
||||
* @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out.
|
||||
* @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned.
|
||||
* @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests.
|
||||
* @property {boolean} [useAuthWithCustomEndpoint] Controls whether or not to use authentication when using a custom endpoint.
|
||||
*/
|
||||
/**
|
||||
* Constructs the Storage client.
|
||||
*
|
||||
* @example
|
||||
* Create a client that uses Application Default Credentials
|
||||
* (ADC)
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* Create a client with explicit credentials
|
||||
* ```
|
||||
* const storage = new Storage({
|
||||
* projectId: 'your-project-id',
|
||||
* keyFilename: '/path/to/keyfile.json'
|
||||
* });
|
||||
* ```
|
||||
|
||||
* @param {StorageOptions} [options] Configuration options.
|
||||
*/
|
||||
constructor(options?: StorageOptions);
|
||||
private static sanitizeEndpoint;
|
||||
/**
|
||||
* Get a reference to a Cloud Storage bucket.
|
||||
*
|
||||
* @param {string} name Name of the bucket.
|
||||
* @param {object} [options] Configuration object.
|
||||
* @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to
|
||||
* encrypt objects inserted into this bucket, if no encryption method is
|
||||
* specified.
|
||||
* @param {string} [options.userProject] User project to be billed for all
|
||||
* requests made from this Bucket object.
|
||||
* @returns {Bucket}
|
||||
* @see Bucket
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const albums = storage.bucket('albums');
|
||||
* const photos = storage.bucket('photos');
|
||||
* ```
|
||||
*/
|
||||
bucket(name: string, options?: BucketOptions): Bucket;
|
||||
/**
|
||||
* Reference a channel to receive notifications about changes to your bucket.
|
||||
*
|
||||
* @param {string} id The ID of the channel.
|
||||
* @param {string} resourceId The resource ID of the channel.
|
||||
* @returns {Channel}
|
||||
* @see Channel
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const channel = storage.channel('id', 'resource-id');
|
||||
* ```
|
||||
*/
|
||||
channel(id: string, resourceId: string): Channel;
|
||||
createBucket(name: string, metadata?: CreateBucketRequest): Promise<CreateBucketResponse>;
|
||||
createBucket(name: string, callback: BucketCallback): void;
|
||||
createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void;
|
||||
createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void;
|
||||
createHmacKey(serviceAccountEmail: string, options?: CreateHmacKeyOptions): Promise<CreateHmacKeyResponse>;
|
||||
createHmacKey(serviceAccountEmail: string, callback: CreateHmacKeyCallback): void;
|
||||
createHmacKey(serviceAccountEmail: string, options: CreateHmacKeyOptions, callback: CreateHmacKeyCallback): void;
|
||||
getBuckets(options?: GetBucketsRequest): Promise<GetBucketsResponse>;
|
||||
getBuckets(options: GetBucketsRequest, callback: GetBucketsCallback): void;
|
||||
getBuckets(callback: GetBucketsCallback): void;
|
||||
/**
|
||||
* Query object for listing HMAC keys.
|
||||
*
|
||||
* @typedef {object} GetHmacKeysOptions
|
||||
* @property {string} [projectId] The project ID of the project that owns
|
||||
* the service account of the requested HMAC key. If not provided,
|
||||
* the project ID used to instantiate the Storage client will be used.
|
||||
* @property {string} [serviceAccountEmail] If present, only HMAC keys for the
|
||||
* given service account are returned.
|
||||
* @property {boolean} [showDeletedKeys=false] If true, include keys in the DELETE
|
||||
* state. Default is false.
|
||||
* @property {boolean} [autoPaginate=true] Have pagination handled
|
||||
* automatically.
|
||||
* @property {number} [maxApiCalls] Maximum number of API calls to make.
|
||||
* @property {number} [maxResults] Maximum number of items plus prefixes to
|
||||
* return per call.
|
||||
* Note: By default will handle pagination automatically
|
||||
* if more than 1 page worth of results are requested per call.
|
||||
* When `autoPaginate` is set to `false` the smaller of `maxResults`
|
||||
* or 1 page of results will be returned per call.
|
||||
* @property {string} [pageToken] A previously-returned page token
|
||||
* representing part of the larger set of results to view.
|
||||
* @property {string} [userProject] This parameter is currently ignored.
|
||||
*/
|
||||
/**
|
||||
* @typedef {array} GetHmacKeysResponse
|
||||
* @property {HmacKey[]} 0 Array of {@link HmacKey} instances.
|
||||
* @param {object} nextQuery 1 A query object to receive more results.
|
||||
* @param {object} apiResponse 2 The full API response.
|
||||
*/
|
||||
/**
|
||||
* @callback GetHmacKeysCallback
|
||||
* @param {?Error} err Request error, if any.
|
||||
* @param {HmacKey[]} hmacKeys Array of {@link HmacKey} instances.
|
||||
* @param {object} nextQuery A query object to receive more results.
|
||||
* @param {object} apiResponse The full API response.
|
||||
*/
|
||||
/**
|
||||
* Retrieves a list of HMAC keys matching the criteria.
|
||||
*
|
||||
* The authenticated user must have storage.hmacKeys.list permission for the project in which the key exists.
|
||||
*
|
||||
* @param {GetHmacKeysOption} options Configuration options.
|
||||
* @param {GetHmacKeysCallback} callback Callback function.
|
||||
* @return {Promise<GetHmacKeysResponse>}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* storage.getHmacKeys(function(err, hmacKeys) {
|
||||
* if (!err) {
|
||||
* // hmacKeys is an array of HmacKey objects.
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* //-
|
||||
* // To control how many API requests are made and page through the results
|
||||
* // manually, set `autoPaginate` to `false`.
|
||||
* //-
|
||||
* const callback = function(err, hmacKeys, nextQuery, apiResponse) {
|
||||
* if (nextQuery) {
|
||||
* // More results exist.
|
||||
* storage.getHmacKeys(nextQuery, callback);
|
||||
* }
|
||||
*
|
||||
* // The `metadata` property is populated for you with the metadata at the
|
||||
* // time of fetching.
|
||||
* hmacKeys[0].metadata;
|
||||
* };
|
||||
*
|
||||
* storage.getHmacKeys({
|
||||
* autoPaginate: false
|
||||
* }, callback);
|
||||
*
|
||||
* //-
|
||||
* // If the callback is omitted, we'll return a Promise.
|
||||
* //-
|
||||
* storage.getHmacKeys().then(function(data) {
|
||||
* const hmacKeys = data[0];
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
getHmacKeys(options?: GetHmacKeysOptions): Promise<GetHmacKeysResponse>;
|
||||
getHmacKeys(callback: GetHmacKeysCallback): void;
|
||||
getHmacKeys(options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void;
|
||||
getServiceAccount(options?: GetServiceAccountOptions): Promise<GetServiceAccountResponse>;
|
||||
getServiceAccount(options?: GetServiceAccountOptions): Promise<GetServiceAccountResponse>;
|
||||
getServiceAccount(options: GetServiceAccountOptions, callback: GetServiceAccountCallback): void;
|
||||
getServiceAccount(callback: GetServiceAccountCallback): void;
|
||||
/**
|
||||
* Get a reference to an HmacKey object.
|
||||
* Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to
|
||||
* retrieve and populate the metadata.
|
||||
*
|
||||
* To get a reference to an HMAC key that's not created for a service
|
||||
* account in the same project used to instantiate the Storage client,
|
||||
* supply the project's ID as `projectId` in the `options` argument.
|
||||
*
|
||||
* @param {string} accessId The HMAC key's access ID.
|
||||
* @param {HmacKeyOptions} options HmacKey constructor owptions.
|
||||
* @returns {HmacKey}
|
||||
* @see HmacKey
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const {Storage} = require('@google-cloud/storage');
|
||||
* const storage = new Storage();
|
||||
* const hmacKey = storage.hmacKey('ACCESS_ID');
|
||||
* ```
|
||||
*/
|
||||
hmacKey(accessId: string, options?: HmacKeyOptions): HmacKey;
|
||||
}
|
||||
export {};
|
||||
+1001
File diff suppressed because it is too large
Load Diff
+51
@@ -0,0 +1,51 @@
|
||||
/// <reference types="node" />
|
||||
import * as querystring from 'querystring';
|
||||
export declare function normalize<T = {}, U = Function>(optionsOrCallback?: T | U, cb?: U): {
|
||||
options: T;
|
||||
callback: U;
|
||||
};
|
||||
/**
|
||||
* Flatten an object into an Array of arrays, [[key, value], ..].
|
||||
* Implements Object.entries() for Node.js <8
|
||||
* @internal
|
||||
*/
|
||||
export declare function objectEntries<T>(obj: {
|
||||
[key: string]: T;
|
||||
}): Array<[string, T]>;
|
||||
/**
|
||||
* Encode `str` with encodeURIComponent, plus these
|
||||
* reserved characters: `! * ' ( )`.
|
||||
*
|
||||
* See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent}
|
||||
*
|
||||
* @param {string} str The URI component to encode.
|
||||
* @return {string} The encoded string.
|
||||
*/
|
||||
export declare function fixedEncodeURIComponent(str: string): string;
|
||||
/**
|
||||
* URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent.
|
||||
*
|
||||
* Encode every byte except `A-Z a-Z 0-9 ~ - . _`.
|
||||
*
|
||||
* @param {string} uri The URI to encode.
|
||||
* @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded.
|
||||
* @return {string} The encoded string.
|
||||
*/
|
||||
export declare function encodeURI(uri: string, encodeSlash: boolean): string;
|
||||
/**
|
||||
* Serialize an object to a URL query string using util.encodeURI(uri, true).
|
||||
* @param {string} url The object to serialize.
|
||||
* @return {string} Serialized string.
|
||||
*/
|
||||
export declare function qsStringify(qs: querystring.ParsedUrlQueryInput): string;
|
||||
export declare function objectKeyToLowercase<T>(object: {
|
||||
[key: string]: T;
|
||||
}): {
|
||||
[key: string]: T;
|
||||
};
|
||||
/**
|
||||
* JSON encode str, with unicode \u+ representation.
|
||||
* @param {object} obj The object to encode.
|
||||
* @return {string} Serialized string.
|
||||
*/
|
||||
export declare function unicodeJSONStringify(obj: object): string;
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.unicodeJSONStringify = exports.objectKeyToLowercase = exports.qsStringify = exports.encodeURI = exports.fixedEncodeURIComponent = exports.objectEntries = exports.normalize = void 0;
|
||||
const querystring = require("querystring");
|
||||
function normalize(optionsOrCallback, cb) {
|
||||
const options = (typeof optionsOrCallback === 'object' ? optionsOrCallback : {});
|
||||
const callback = (typeof optionsOrCallback === 'function' ? optionsOrCallback : cb);
|
||||
return { options, callback };
|
||||
}
|
||||
exports.normalize = normalize;
|
||||
/**
|
||||
* Flatten an object into an Array of arrays, [[key, value], ..].
|
||||
* Implements Object.entries() for Node.js <8
|
||||
* @internal
|
||||
*/
|
||||
function objectEntries(obj) {
|
||||
return Object.keys(obj).map(key => [key, obj[key]]);
|
||||
}
|
||||
exports.objectEntries = objectEntries;
|
||||
/**
|
||||
* Encode `str` with encodeURIComponent, plus these
|
||||
* reserved characters: `! * ' ( )`.
|
||||
*
|
||||
* See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent}
|
||||
*
|
||||
* @param {string} str The URI component to encode.
|
||||
* @return {string} The encoded string.
|
||||
*/
|
||||
function fixedEncodeURIComponent(str) {
|
||||
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
|
||||
}
|
||||
exports.fixedEncodeURIComponent = fixedEncodeURIComponent;
|
||||
/**
|
||||
* URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent.
|
||||
*
|
||||
* Encode every byte except `A-Z a-Z 0-9 ~ - . _`.
|
||||
*
|
||||
* @param {string} uri The URI to encode.
|
||||
* @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded.
|
||||
* @return {string} The encoded string.
|
||||
*/
|
||||
function encodeURI(uri, encodeSlash) {
|
||||
// Split the string by `/`, and conditionally rejoin them with either
|
||||
// %2F if encodeSlash is `true`, or '/' if `false`.
|
||||
return uri
|
||||
.split('/')
|
||||
.map(fixedEncodeURIComponent)
|
||||
.join(encodeSlash ? '%2F' : '/');
|
||||
}
|
||||
exports.encodeURI = encodeURI;
|
||||
/**
|
||||
* Serialize an object to a URL query string using util.encodeURI(uri, true).
|
||||
* @param {string} url The object to serialize.
|
||||
* @return {string} Serialized string.
|
||||
*/
|
||||
function qsStringify(qs) {
|
||||
return querystring.stringify(qs, '&', '=', {
|
||||
encodeURIComponent: (component) => encodeURI(component, true),
|
||||
});
|
||||
}
|
||||
exports.qsStringify = qsStringify;
|
||||
function objectKeyToLowercase(object) {
|
||||
const newObj = {};
|
||||
for (let key of Object.keys(object)) {
|
||||
const value = object[key];
|
||||
key = key.toLowerCase();
|
||||
newObj[key] = value;
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
exports.objectKeyToLowercase = objectKeyToLowercase;
|
||||
/**
|
||||
* JSON encode str, with unicode \u+ representation.
|
||||
* @param {object} obj The object to encode.
|
||||
* @return {string} Serialized string.
|
||||
*/
|
||||
function unicodeJSONStringify(obj) {
|
||||
return JSON.stringify(obj).replace(/[\u0080-\uFFFF]/g, (char) => '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4));
|
||||
}
|
||||
exports.unicodeJSONStringify = unicodeJSONStringify;
|
||||
//# sourceMappingURL=util.js.map
|
||||
Reference in New Issue
Block a user