Upgrade to TypeScript 5 (#8561)

This commit is contained in:
Daniel La Rocque
2024-10-25 08:24:10 -04:00
committed by GitHub
parent d797131e0c
commit 6c2e758589
103 changed files with 13686 additions and 1639 deletions
+18
View File
@@ -4,6 +4,24 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Prune .d.ts",
"program": "${workspaceRoot}/repo-scripts/prune-dts/node_modules/.bin/_mocha",
"cwd": "${workspaceRoot}/repo-scripts/prune-dts",
"args": [
"--require",
"ts-node/register",
"--timeout",
"5000",
"${workspaceFolder}/repo-scripts/prune-dts/*.test.ts"
],
"env": {
"TS_NODE_COMPILER_OPTIONS" : "{\"module\":\"commonjs\"}"
},
"sourceMaps": true,
},
{
"type": "node",
"request": "launch",
+4 -4
View File
@@ -990,7 +990,7 @@ Whether a particular consent type has been granted or denied.
<b>Signature:</b>
```typescript
export declare type ConsentStatusString = 'granted' | 'denied';
export type ConsentStatusString = 'granted' | 'denied';
```
## Currency
@@ -1000,7 +1000,7 @@ Standard Google Analytics currency type.
<b>Signature:</b>
```typescript
export declare type Currency = string | number;
export type Currency = string | number;
```
## CustomEventName
@@ -1010,7 +1010,7 @@ Any custom event name string not in the standard list of recommended event names
<b>Signature:</b>
```typescript
export declare type CustomEventName<T> = T extends EventNameString ? never : T;
export type CustomEventName<T> = T extends EventNameString ? never : T;
```
## EventNameString
@@ -1020,5 +1020,5 @@ Type for standard Google Analytics event names. `logEvent` also accepts any cust
<b>Signature:</b>
```typescript
export declare type EventNameString = 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'exception' | 'generate_lead' | 'login' | 'page_view' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results';
export type EventNameString = 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'exception' | 'generate_lead' | 'login' | 'page_view' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results';
```
+1 -1
View File
@@ -197,5 +197,5 @@ A listener that is called whenever the App Check token changes.
<b>Signature:</b>
```typescript
export declare type AppCheckTokenListener = (token: AppCheckTokenResult) => void;
export type AppCheckTokenListener = (token: AppCheckTokenResult) => void;
```
+4 -4
View File
@@ -2114,7 +2114,7 @@ Map of OAuth Custom Parameters.
<b>Signature:</b>
```typescript
export declare type CustomParameters = Record<string, string>;
export type CustomParameters = Record<string, string>;
```
## NextOrObserver
@@ -2124,7 +2124,7 @@ Type definition for an event callback.
<b>Signature:</b>
```typescript
export declare type NextOrObserver<T> = NextFn<T | null> | Observer<T | null>;
export type NextOrObserver<T> = NextFn<T | null> | Observer<T | null>;
```
## PhoneInfoOptions
@@ -2136,7 +2136,7 @@ The information that's required depends on whether you are doing single-factor s
<b>Signature:</b>
```typescript
export declare type PhoneInfoOptions = PhoneSingleFactorInfoOptions | PhoneMultiFactorEnrollInfoOptions | PhoneMultiFactorSignInInfoOptions;
export type PhoneInfoOptions = PhoneSingleFactorInfoOptions | PhoneMultiFactorEnrollInfoOptions | PhoneMultiFactorSignInInfoOptions;
```
## UserProfile
@@ -2146,5 +2146,5 @@ User profile used in [AdditionalUserInfo](./auth.additionaluserinfo.md#additiona
<b>Signature:</b>
```typescript
export declare type UserProfile = Record<string, unknown>;
export type UserProfile = Record<string, unknown>;
```
+3 -3
View File
@@ -147,7 +147,7 @@ Possible values: - 'cancelled': The operation was cancelled (typically by the ca
<b>Signature:</b>
```typescript
export declare type FunctionsErrorCode = `functions/${FunctionsErrorCodeCore}`;
export type FunctionsErrorCode = `functions/${FunctionsErrorCodeCore}`;
```
## FunctionsErrorCodeCore
@@ -157,7 +157,7 @@ Functions error code string appended after "functions/" product prefix. See [Fun
<b>Signature:</b>
```typescript
export declare type FunctionsErrorCodeCore = 'ok' | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
export type FunctionsErrorCodeCore = 'ok' | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
```
## HttpsCallable
@@ -167,5 +167,5 @@ A reference to a "callable" HTTP trigger in Google Cloud Functions.
<b>Signature:</b>
```typescript
export declare type HttpsCallable<RequestData = unknown, ResponseData = unknown> = (data?: RequestData | null) => Promise<HttpsCallableResult<ResponseData>>;
export type HttpsCallable<RequestData = unknown, ResponseData = unknown> = (data?: RequestData | null) => Promise<HttpsCallableResult<ResponseData>>;
```
+2 -2
View File
@@ -152,7 +152,7 @@ An user defined callback function that gets called when Installations ID changes
<b>Signature:</b>
```typescript
export declare type IdChangeCallbackFn = (installationId: string) => void;
export type IdChangeCallbackFn = (installationId: string) => void;
```
## IdChangeUnsubscribeFn
@@ -162,5 +162,5 @@ Unsubscribe a callback function previously added via [IdChangeCallbackFn](./inst
<b>Signature:</b>
```typescript
export declare type IdChangeUnsubscribeFn = () => void;
export type IdChangeUnsubscribeFn = () => void;
```
+3 -3
View File
@@ -325,7 +325,7 @@ Summarizes the outcome of the last attempt to fetch config from the Firebase Rem
<b>Signature:</b>
```typescript
export declare type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
```
## LogLevel
@@ -335,7 +335,7 @@ Defines levels of Remote Config logging.
<b>Signature:</b>
```typescript
export declare type LogLevel = 'debug' | 'error' | 'silent';
export type LogLevel = 'debug' | 'error' | 'silent';
```
## ValueSource
@@ -347,5 +347,5 @@ Indicates the source of a value.
<b>Signature:</b>
```typescript
export declare type ValueSource = 'static' | 'default' | 'remote';
export type ValueSource = 'static' | 'default' | 'remote';
```
+3 -3
View File
@@ -493,7 +493,7 @@ An enumeration of the possible string formats for upload.
<b>Signature:</b>
```typescript
export declare type StringFormat = (typeof StringFormat)[keyof typeof StringFormat];
export type StringFormat = (typeof StringFormat)[keyof typeof StringFormat];
```
## TaskEvent
@@ -503,7 +503,7 @@ An event that is triggered on a task.
<b>Signature:</b>
```typescript
export declare type TaskEvent = 'state_changed';
export type TaskEvent = 'state_changed';
```
## TaskState
@@ -513,7 +513,7 @@ Represents the current state of a running upload.
<b>Signature:</b>
```typescript
export declare type TaskState = 'running' | 'paused' | 'success' | 'canceled' | 'error';
export type TaskState = 'running' | 'paused' | 'success' | 'canceled' | 'error';
```
## StorageErrorCode
+3 -3
View File
@@ -184,7 +184,7 @@ Content part - includes text, image/video, or function call/response part types.
<b>Signature:</b>
```typescript
export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart;
export type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart;
```
## Role
@@ -194,7 +194,7 @@ Role is the producer of the content.
<b>Signature:</b>
```typescript
export declare type Role = (typeof POSSIBLE_ROLES)[number];
export type Role = (typeof POSSIBLE_ROLES)[number];
```
## Tool
@@ -214,7 +214,7 @@ A type that includes all specific Schema types.
<b>Signature:</b>
```typescript
export declare type TypedSchema = IntegerSchema | NumberSchema | StringSchema | BooleanSchema | ObjectSchema | ArraySchema;
export type TypedSchema = IntegerSchema | NumberSchema | StringSchema | BooleanSchema | ObjectSchema | ArraySchema;
```
## BlockReason
+1 -1
View File
@@ -34,7 +34,7 @@
"karma-typescript": "5.5.4",
"karma-typescript-es6-transform": "5.5.4",
"mocha": "9.2.2",
"typescript": "4.7.4",
"typescript": "5.5.4",
"webpack": "5.76.0",
"webpack-cli": "4.10.0",
"webpack-dev-server": "4.11.1"
+1 -1
View File
@@ -24,7 +24,7 @@
"@firebase/remote-config-compat": "0.2.10"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"engines": {
"node": ">=18.0.0"
+1 -1
View File
@@ -10,7 +10,7 @@
"firebase": "*"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"engines": {
"node": ">=18.0.0"
+1 -1
View File
@@ -20,7 +20,7 @@
"karma-typescript": "5.5.4",
"mocha": "9.2.2",
"npm-run-all": "4.1.5",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"engines": {
"node": ">=18.0.0"
+1 -1
View File
@@ -29,7 +29,7 @@
"karma-spec-reporter": "0.0.36",
"mocha": "9.2.2",
"ts-loader": "9.5.1",
"typescript": "4.2.2",
"typescript": "5.5.4",
"webpack": "5.76.0",
"webpack-stream": "7.0.0"
},
+2 -2
View File
@@ -80,7 +80,7 @@
"@types/long": "4.0.2",
"@types/mocha": "9.1.1",
"@types/mz": "2.7.8",
"@types/node": "16.18.68",
"@types/node": "18.19.57",
"@types/request": "2.48.12",
"@types/sinon": "9.0.11",
"@types/sinon-chai": "3.2.12",
@@ -156,7 +156,7 @@
"tsec": "0.2.8",
"tslint": "6.1.3",
"typedoc": "0.16.11",
"typescript": "4.7.4",
"typescript": "5.5.4",
"watch": "1.0.2",
"webpack": "5.76.0",
"yargs": "17.7.2"
+1 -1
View File
@@ -26,7 +26,7 @@
"rollup": "2.79.1",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/analytics-compat",
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -53,7 +53,7 @@
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "13.3.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/analytics",
+1 -1
View File
@@ -49,7 +49,7 @@
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "13.3.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/app-check",
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -50,7 +50,7 @@
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "13.3.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/app-check",
+1 -1
View File
@@ -48,7 +48,7 @@
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/app-compat",
+1 -1
View File
@@ -24,6 +24,6 @@
"@firebase/logger": "0.2.6"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -50,7 +50,7 @@
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"rollup-plugin-dts": "5.3.1",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/app",
+1 -1
View File
@@ -34,7 +34,7 @@
"rollup-plugin-sourcemaps": "0.6.3",
"rollup-plugin-typescript2": "0.31.2",
"rollup-plugin-uglify": "6.0.4",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/auth-compat/demo",
+1 -1
View File
@@ -63,7 +63,7 @@
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"selenium-webdriver": "4.8.0",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/auth-compat",
+1 -1
View File
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -24,6 +24,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -141,7 +141,7 @@
"rollup-plugin-typescript2": "0.31.2",
"selenium-webdriver": "4.8.0",
"totp-generator": "0.0.14",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/auth",
+3 -3
View File
@@ -241,20 +241,20 @@ export async function _performSignInRequest<T, V extends IdTokenResponse>(
request?: T,
customErrorMap: Partial<ServerErrorMap<ServerError>> = {}
): Promise<V> {
const serverResponse = (await _performApiRequest<T, V | IdTokenMfaResponse>(
const serverResponse = await _performApiRequest<T, V | IdTokenMfaResponse>(
auth,
method,
path,
request,
customErrorMap
)) as V;
);
if ('mfaPendingCredential' in serverResponse) {
_fail(auth, AuthErrorCode.MFA_REQUIRED, {
_serverResponse: serverResponse
});
}
return serverResponse;
return serverResponse as V;
}
export function _getFinalTarget(
@@ -162,7 +162,7 @@ export class RecaptchaEnterpriseVerifier {
}
}
export async function injectRecaptchaFields<T>(
export async function injectRecaptchaFields<T extends object>(
auth: AuthInternal,
request: T,
action: RecaptchaActionName,
@@ -238,7 +238,7 @@ type ActionMethod<TRequest, TResponse> = (
request: TRequest
) => Promise<TResponse>;
export async function handleRecaptchaFlow<TRequest, TResponse>(
export async function handleRecaptchaFlow<TRequest extends object, TResponse>(
authInstance: AuthInternal,
request: TRequest,
actionName: RecaptchaActionName,
@@ -462,7 +462,7 @@ export async function updatePhoneNumber(
}
// Helper function that fetches and injects a reCAPTCHA v2 token into the request.
export async function injectRecaptchaV2Token<T>(
export async function injectRecaptchaV2Token<T extends object>(
auth: AuthInternal,
request: T,
recaptchaV2Verifier: ApplicationVerifierInternal
@@ -18,6 +18,7 @@
import { expect, use } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinonChai from 'sinon-chai';
// eslint-disable-next-line import/no-extraneous-dependencies
import {
linkWithPhoneNumber,
PhoneAuthProvider,
+1 -1
View File
@@ -38,7 +38,7 @@
"devDependencies": {
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/component",
+1 -1
View File
@@ -58,7 +58,7 @@
"@firebase/app": "0.10.15",
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/data-connect",
+1 -1
View File
@@ -58,7 +58,7 @@
},
"devDependencies": {
"@firebase/app-compat": "0.2.45",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/database-compat",
@@ -847,9 +847,11 @@ describe('Transaction Tests', () => {
ref1.transaction(
current => {
retries++;
// We should be getting server events while the transaction is outstanding.
for (let i = 0; i < (current || 0); i++) {
expect(events[i]).to.equal(i);
if (typeof current === 'number') {
// We should be getting server events while the transaction is outstanding.
for (let i = 0; i < (current || 0); i++) {
expect(events[i]).to.equal(i);
}
}
if (current === SETS - 1) {
@@ -919,7 +921,7 @@ describe('Transaction Tests', () => {
current => {
if (current == null) {
return 0;
} else if (current < COUNT) {
} else if (typeof current === 'number' && current < COUNT) {
return (current as number) + 1;
} else {
shouldCommit = false;
+1 -1
View File
@@ -24,6 +24,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -60,7 +60,7 @@
"@firebase/app": "0.10.15",
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/database",
+1 -1
View File
@@ -439,7 +439,7 @@
"gulp": "4.0.2",
"gulp-sourcemaps": "3.0.0",
"gulp-replace": "1.1.4",
"typescript": "4.2.2",
"typescript": "5.5.4",
"rollup-plugin-license": "3.0.1"
},
"components": [
+1 -1
View File
@@ -61,7 +61,7 @@
"rollup-plugin-typescript2": "0.31.2",
"@rollup/plugin-node-resolve": "13.3.0",
"ts-node": "10.9.1",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"license": "Apache-2.0",
"typings": "dist/src/index.d.ts",
+1 -1
View File
@@ -24,6 +24,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.2.2"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -125,7 +125,7 @@
"rollup-plugin-typescript2": "0.31.2",
"rollup-plugin-dts": "5.3.1",
"ts-node": "10.9.1",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/firestore",
+1 -1
View File
@@ -14,4 +14,4 @@
* 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.
*/var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};exports.__esModule=true;var rollup_1=require("rollup");var yargs=require("yargs");var alias=require("@rollup/plugin-alias");var json=require("@rollup/plugin-json");var typescriptPlugin=require("rollup-plugin-typescript2");var util=require("../rollup.shared");var argv=yargs.options({input:{type:"string",demandOption:true,desc:"The location of the index.ts file"},output:{type:"string",demandOption:true,desc:"The location for the transpiled JavaScript bundle"}}).argv;function buildBundle(input,output){return __awaiter(this,void 0,void 0,(function(){var bundle;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,rollup_1.rollup({input:input,plugins:[alias(util.generateAliasConfig("node")),typescriptPlugin({tsconfigOverride:{compilerOptions:{target:"es2017"}},transformers:[util.removeAssertTransformer]}),json({preferConst:true})],external:util.resolveNodeExterns})];case 1:bundle=_a.sent();return[4,bundle.write({file:output,format:"es"})];case 2:_a.sent();return[2]}}))}))}buildBundle(argv.input,argv.output);
*/var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};exports.__esModule=true;var rollup_1=require("rollup");var yargs=require("yargs");var alias=require("@rollup/plugin-alias");var json=require("@rollup/plugin-json");var typescriptPlugin=require("rollup-plugin-typescript2");var util=require("../rollup.shared");var argv=yargs.options({input:{type:"string",demandOption:true,desc:"The location of the index.ts file"},output:{type:"string",demandOption:true,desc:"The location for the transpiled JavaScript bundle"}}).parseSync();function buildBundle(input,output){return __awaiter(this,void 0,void 0,(function(){var bundle;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,(0,rollup_1.rollup)({input:input,plugins:[alias(util.generateAliasConfig("node")),typescriptPlugin({tsconfigOverride:{compilerOptions:{target:"es2017"}},transformers:[util.removeAssertTransformer]}),json({preferConst:true})],external:util.resolveNodeExterns})];case 1:bundle=_a.sent();return[4,bundle.write({file:output,format:"es"})];case 2:_a.sent();return[2]}}))}))}buildBundle(argv.input,argv.output);
+1 -1
View File
@@ -14,4 +14,4 @@
* 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.
*/exports.__esModule=true;exports.removeAsserts=void 0;var ts=require("typescript");var ASSERT_LOCATION="packages/firestore/src/util/assert.ts";function removeAsserts(program){var removeAsserts=new RemoveAsserts(program.getTypeChecker());return function(context){return function(file){return removeAsserts.visitNodeAndChildren(file,context)}}}exports.removeAsserts=removeAsserts;var RemoveAsserts=function(){function RemoveAsserts(typeChecker){this.typeChecker=typeChecker}RemoveAsserts.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RemoveAsserts.prototype.visitNode=function(node){var updatedNode=null;if(ts.isCallExpression(node)){var signature=this.typeChecker.getResolvedSignature(node);if(signature&&signature.declaration&&signature.declaration.kind===ts.SyntaxKind.FunctionDeclaration){var declaration=signature.declaration;if(declaration&&declaration.getSourceFile().fileName.indexOf(ASSERT_LOCATION)>=0){var method=declaration.name.text;if(method==="debugAssert"){updatedNode=ts.createOmittedExpression()}else if(method==="hardAssert"){updatedNode=ts.createCall(declaration.name,undefined,[node.arguments[0]])}else if(method==="fail"){updatedNode=ts.createCall(declaration.name,undefined,[])}}}}if(updatedNode){ts.setSourceMapRange(updatedNode,ts.getSourceMapRange(node));return updatedNode}else{return node}};return RemoveAsserts}();
*/exports.__esModule=true;exports.removeAsserts=void 0;var ts=require("typescript");var ASSERT_LOCATION="packages/firestore/src/util/assert.ts";function removeAsserts(program){var removeAsserts=new RemoveAsserts(program.getTypeChecker());return function(context){return function(file){return removeAsserts.visitNodeAndChildren(file,context)}}}exports.removeAsserts=removeAsserts;var RemoveAsserts=function(){function RemoveAsserts(typeChecker){this.typeChecker=typeChecker}RemoveAsserts.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RemoveAsserts.prototype.visitNode=function(node){var updatedNode=null;if(ts.isCallExpression(node)){var signature=this.typeChecker.getResolvedSignature(node);if(signature&&signature.declaration&&signature.declaration.kind===ts.SyntaxKind.FunctionDeclaration){var declaration=signature.declaration;if(declaration&&declaration.getSourceFile().fileName.indexOf(ASSERT_LOCATION)>=0){var method=declaration.name.text;if(method==="debugAssert"){updatedNode=ts.factory.createOmittedExpression()}else if(method==="hardAssert"){updatedNode=ts.factory.createCallExpression(declaration.name,undefined,[node.arguments[0]])}else if(method==="fail"){updatedNode=ts.factory.createCallExpression(declaration.name,undefined,[])}}}}if(updatedNode){ts.setSourceMapRange(updatedNode,ts.getSourceMapRange(node));return updatedNode}else{return node}};return RemoveAsserts}();
+3 -3
View File
@@ -64,17 +64,17 @@ class RemoveAsserts {
) {
const method = declaration.name!.text;
if (method === 'debugAssert') {
updatedNode = ts.createOmittedExpression();
updatedNode = ts.factory.createOmittedExpression();
} else if (method === 'hardAssert') {
// Remove the log message but keep the assertion
updatedNode = ts.createCall(
updatedNode = ts.factory.createCallExpression(
declaration.name!,
/*typeArgs*/ undefined,
[node.arguments[0]]
);
} else if (method === 'fail') {
// Remove the log message
updatedNode = ts.createCall(
updatedNode = ts.factory.createCallExpression(
declaration.name!,
/*typeArgs*/ undefined,
[]
@@ -14,4 +14,4 @@
* 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.
*/exports.__esModule=true;exports.renameInternals=void 0;var ts=require("typescript");var ignoredIdentifiers=["undefined"];var RenameInternals=function(){function RenameInternals(publicApi,prefix){this.publicApi=publicApi;this.prefix=prefix}RenameInternals.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RenameInternals.prototype.visitNode=function(node){if(ts.isIdentifier(node)){var name_1=node.escapedText.toString();if(!this.publicApi.has(name_1)&&ignoredIdentifiers.indexOf(node.escapedText.toString())===-1){var newIdentifier=ts.createIdentifier(this.prefix+name_1);ts.setSourceMapRange(newIdentifier,ts.getSourceMapRange(node));return newIdentifier}}return node};return RenameInternals}();var DEFAULT_PREFIX="_";function renameInternals(program,config){var _a;var prefix=(_a=config.prefix)!==null&&_a!==void 0?_a:DEFAULT_PREFIX;var renamer=new RenameInternals(config.publicIdentifiers,prefix);return function(context){return function(file){return renamer.visitNodeAndChildren(file,context)}}}exports.renameInternals=renameInternals;
*/exports.__esModule=true;exports.renameInternals=void 0;var ts=require("typescript");var ignoredIdentifiers=["undefined"];var RenameInternals=function(){function RenameInternals(publicApi,prefix){this.publicApi=publicApi;this.prefix=prefix}RenameInternals.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RenameInternals.prototype.visitNode=function(node){if(ts.isIdentifier(node)){var name_1=node.escapedText.toString();if(!this.publicApi.has(name_1)&&ignoredIdentifiers.indexOf(node.escapedText.toString())===-1){var newIdentifier=ts.factory.createIdentifier(this.prefix+name_1);ts.setSourceMapRange(newIdentifier,ts.getSourceMapRange(node));return newIdentifier}}return node};return RenameInternals}();var DEFAULT_PREFIX="_";function renameInternals(program,config){var _a;var prefix=(_a=config.prefix)!==null&&_a!==void 0?_a:DEFAULT_PREFIX;var renamer=new RenameInternals(config.publicIdentifiers,prefix);return function(context){return function(file){return renamer.visitNodeAndChildren(file,context)}}}exports.renameInternals=renameInternals;
@@ -48,7 +48,7 @@ class RenameInternals {
!this.publicApi.has(name) &&
ignoredIdentifiers.indexOf(node.escapedText.toString()) === -1
) {
const newIdentifier = ts.createIdentifier(this.prefix + name);
const newIdentifier = ts.factory.createIdentifier(this.prefix + name);
ts.setSourceMapRange(newIdentifier, ts.getSourceMapRange(node));
return newIdentifier;
}
@@ -24,7 +24,7 @@ import { toByteStreamReaderHelper } from '../../util/byte_stream';
export function toByteStreamReader(
source: BundleSource,
bytesPerRead: number
): ReadableStreamReader<Uint8Array> {
): ReadableStreamDefaultReader<Uint8Array> {
if (source instanceof Uint8Array) {
return toByteStreamReaderHelper(source, bytesPerRead);
}
@@ -359,7 +359,7 @@ export class WebChannelConnection extends RestConnection {
// Use any because msgData.error is not typed.
const msgDataOrError: WebChannelError | object = msgData;
const error =
msgDataOrError.error ||
(msgDataOrError as WebChannelError)?.error ||
(msgDataOrError as WebChannelError[])[0]?.error;
if (error) {
logDebug(
@@ -27,7 +27,7 @@ import * as rn from './rn/byte_stream_reader';
export function toByteStreamReader(
source: BundleSource,
bytesPerRead: number = DEFAULT_BYTES_PER_READ
): ReadableStreamReader<Uint8Array> {
): ReadableStreamDefaultReader<Uint8Array> {
if (isNode()) {
return node.toByteStreamReader(source, bytesPerRead);
} else if (isReactNative()) {
@@ -26,7 +26,7 @@ import { valueDescription } from '../../util/input_validation';
export function toByteStreamReader(
source: BundleSource,
bytesPerRead: number
): ReadableStreamReader<Uint8Array> {
): ReadableStreamDefaultReader<Uint8Array> {
if (!(source instanceof Uint8Array)) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
@@ -42,7 +42,7 @@ class BundleReaderImpl implements BundleReader {
constructor(
/** The reader to read from underlying binary bundle data source. */
private reader: ReadableStreamReader<Uint8Array>,
private reader: ReadableStreamDefaultReader<Uint8Array>,
readonly serializer: JsonProtoSerializer
) {
this.textDecoder = newTextDecoder();
@@ -192,7 +192,7 @@ class BundleReaderImpl implements BundleReader {
}
export function newBundleReader(
reader: ReadableStreamReader<Uint8Array>,
reader: ReadableStreamDefaultReader<Uint8Array>,
serializer: JsonProtoSerializer
): BundleReader {
return new BundleReaderImpl(reader, serializer);
+1 -1
View File
@@ -33,7 +33,7 @@ export const DEFAULT_BYTES_PER_READ = 10240;
export function toByteStreamReaderHelper(
source: Uint8Array,
bytesPerRead: number = DEFAULT_BYTES_PER_READ
): ReadableStreamReader<Uint8Array> {
): ReadableStreamDefaultReader<Uint8Array> {
debugAssert(
bytesPerRead > 0,
`toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`
@@ -600,7 +600,7 @@ describe('FirestoreTypeConverter', () => {
stringProperty: string;
numberProperty: number;
}
const converter = {
const converter: FirestoreDataConverter<MyModelType> = {
toFirestore(
modelObject: PartialWithFieldValue<MyModelType>,
options?: SetOptions
@@ -59,7 +59,7 @@ const encoder = newTextEncoder();
export function byteStreamReaderFromString(
content: string,
bytesPerRead: number
): ReadableStreamReader<Uint8Array> {
): ReadableStreamDefaultReader<Uint8Array> {
const data = encoder.encode(content);
return toByteStreamReader(data, bytesPerRead);
}
+1 -1
View File
@@ -33,7 +33,7 @@
"rollup": "2.79.1",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/functions-compat",
+1 -1
View File
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -53,7 +53,7 @@
"rollup": "2.79.1",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/functions",
+1 -1
View File
@@ -51,7 +51,7 @@
"@rollup/plugin-node-resolve": "13.3.0",
"rollup-plugin-typescript2": "0.31.2",
"rollup-plugin-uglify": "6.0.4",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"peerDependencies": {
"@firebase/app-compat": "0.x"
+1 -1
View File
@@ -23,6 +23,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -56,7 +56,7 @@
"@rollup/plugin-node-resolve": "13.3.0",
"rollup-plugin-typescript2": "0.31.2",
"rollup-plugin-uglify": "6.0.4",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"peerDependencies": {
"@firebase/app": "0.x"
+1 -1
View File
@@ -37,7 +37,7 @@
"devDependencies": {
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/logger",
+1 -1
View File
@@ -48,7 +48,7 @@
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"ts-essentials": "9.3.0",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/messaging",
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+2 -2
View File
@@ -64,8 +64,8 @@
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"@rollup/plugin-json": "4.1.0",
"ts-essentials": "9.3.0",
"typescript": "4.7.4"
"ts-essentials": "10.0.2",
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/messaging",
@@ -33,7 +33,29 @@ export interface MessagePayloadInternal {
collapse_key: string;
}
export interface NotificationPayloadInternal extends NotificationOptions {
// https://developer.mozilla.org/en-US/docs/Web/API/Notification/actions
interface NotificationAction {
action: string;
icon?: string;
title: string;
}
/**
* This interface defines experimental properties of NotificationOptions, that are not part of
* the interface in the generated DOM types at https://github.com/microsoft/TypeScript-DOM-lib-generator/blob/179bdd84a944933a3103f29c2274c9f5a857b693/baselines/dom.generated.d.ts#L1012
* https://developer.mozilla.org/en-US/docs/Web/API/Notification
*/
interface NotificationOptionsExperimental extends NotificationOptions {
readonly maxActions?: number;
readonly actions?: NotificationAction[];
readonly image?: string;
readonly renotify?: boolean;
readonly timestamp?: EpochTimeStamp;
readonly vibrate?: VibratePattern;
}
export interface NotificationPayloadInternal
extends NotificationOptionsExperimental {
title: string;
// Supported in the Legacy Send API.
// See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.
+1 -1
View File
@@ -50,7 +50,7 @@
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4",
"typescript": "5.5.4",
"@firebase/app-compat": "0.2.45"
},
"repository": {
+1 -1
View File
@@ -12,7 +12,7 @@
"index.d.ts"
],
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/performance-types",
+1 -1
View File
@@ -50,7 +50,7 @@
"rollup": "2.79.1",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/performance",
@@ -39,14 +39,27 @@ const enum EffectiveConnectionType {
CONNECTION_4G = 4
}
type ConnectionType =
| 'bluetooth'
| 'cellular'
| 'ethernet'
| 'mixed'
| 'none'
| 'other'
| 'unknown'
| 'wifi';
/**
* NetworkInformation
* This API is not well supported in all major browsers, so TypeScript does not provide types for it.
*
* ref: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
*/
interface NetworkInformation extends EventTarget {
readonly type: ConnectionType;
}
interface NetworkInformationWithEffectiveType extends NetworkInformation {
// `effectiveType` is an experimental property and not included in
// TypeScript's typings for the native NetworkInformation interface
readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';
}
+1 -1
View File
@@ -49,7 +49,7 @@
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4",
"typescript": "5.5.4",
"@firebase/app-compat": "0.2.45"
},
"repository": {
+1 -1
View File
@@ -20,6 +20,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -51,7 +51,7 @@
"@firebase/app": "0.10.15",
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/remote-config",
@@ -442,7 +442,7 @@ describe('RemoteConfig', () => {
describe('fetch', () => {
let timeoutStub: sinon.SinonStub<
[(...args: any[]) => void, number, ...any[]]
[callback: (args: void) => void, ms?: number | undefined]
>;
beforeEach(() => {
client.fetch = sinon
@@ -88,7 +88,7 @@ export function getEmulatorHostAndPort(
discovered?: DiscoveredEmulators
) {
if (conf && ('host' in conf || 'port' in conf)) {
const { host, port } = conf;
const { host, port } = conf as any;
if (host || port) {
if (!host || !port) {
throw new Error(
@@ -103,8 +103,8 @@ export function getEmulatorHostAndPort(
);
}
return {
host: fixHostname(conf.host, discovered?.hub?.host),
port: conf.port
host: fixHostname(host, discovered?.hub?.host),
port: port
};
}
}
+1 -1
View File
@@ -49,7 +49,7 @@
"rollup": "2.79.1",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"files": [
"dist"
+1 -1
View File
@@ -24,6 +24,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -60,7 +60,7 @@
"@rollup/plugin-alias": "5.1.0",
"@rollup/plugin-json": "4.1.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/storage",
+1 -1
View File
@@ -21,6 +21,6 @@
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
}
}
+1 -1
View File
@@ -51,7 +51,7 @@
"@firebase/app": "0.10.15",
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/template",
+1 -1
View File
@@ -47,7 +47,7 @@
"devDependencies": {
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/util",
+1 -1
View File
@@ -61,7 +61,7 @@
"rollup": "2.79.1",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/vertexai",
+1 -1
View File
@@ -37,7 +37,7 @@
"rollup-plugin-copy": "3.5.0",
"rollup-plugin-sourcemaps": "0.6.3",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "packages/webchannel-wrapper",
@@ -19,11 +19,11 @@
"dependencies": {
"@changesets/types": "3.3.0",
"@changesets/get-github-info": "0.5.2",
"@types/node": "20.8.10"
"@types/node": "18.19.57"
},
"license": "Apache-2.0",
"devDependencies": {
"typescript": "4.7.4"
"typescript": "5.5.4"
},
"repository": {
"directory": "repo-scripts/changelog-generator",
+180 -81
View File
@@ -155,16 +155,15 @@ function maybeHideConstructor(
?.find(t => t.tagName.escapedText === 'hideconstructor');
if (hideConstructorTag) {
const modifier = ts.createModifier(
const hideConstructorModifier = ts.factory.createModifier(
hideConstructorTag.comment === 'protected'
? ts.SyntaxKind.ProtectedKeyword
: ts.SyntaxKind.PrivateKeyword
);
return ts.createConstructor(
node.decorators,
[modifier],
/*parameters=*/ [],
/* body= */ undefined
return ts.factory.createConstructorDeclaration(
[...(ts.getModifiers(node) ?? []), hideConstructorModifier],
[],
undefined
);
} else {
return node;
@@ -192,7 +191,6 @@ function maybeHideConstructor(
function prunePrivateImports<
T extends ts.InterfaceDeclaration | ts.ClassDeclaration
>(
factory: ts.NodeFactory,
program: ts.Program,
host: ts.CompilerHost,
sourceFile: ts.SourceFile,
@@ -204,8 +202,8 @@ function prunePrivateImports<
const prunedHeritageClauses: ts.HeritageClause[] = [];
// Additional members that are copied from the private symbols into the public
// symbols
const additionalMembers: ts.Node[] = [];
const inheritedInterfaceProperties: ts.TypeElement[] = [];
const inheritedClassMembers: ts.ClassElement[] = [];
for (const heritageClause of node.heritageClauses || []) {
const exportedTypes: ts.ExpressionWithTypeArguments[] = [];
for (const type of heritageClause.types) {
@@ -217,53 +215,53 @@ function prunePrivateImports<
} else {
// Hide the type we are inheriting from and merge its declarations
// into the current class.
// TODO: We really only need to do this when the type that is extended
// is a class. We should skip this for interfaces.
const privateType = typeChecker.getTypeAtLocation(type);
additionalMembers.push(
...convertPropertiesForEnclosingClass(
program,
host,
sourceFile,
privateType.getProperties(),
node
)
);
if (ts.isClassDeclaration(node)) {
inheritedClassMembers.push(
...convertPropertiesForEnclosingDeclaration<
ts.ClassDeclaration,
ts.ClassElement
>(program, host, sourceFile, privateType.getProperties(), node)
);
} else if (ts.isInterfaceDeclaration(node)) {
inheritedInterfaceProperties.push(
...convertPropertiesForEnclosingDeclaration<
ts.InterfaceDeclaration,
ts.TypeElement
>(program, host, sourceFile, privateType.getProperties(), node)
);
}
}
}
if (exportedTypes.length > 0) {
prunedHeritageClauses.push(
factory.updateHeritageClause(heritageClause, exportedTypes)
ts.factory.updateHeritageClause(heritageClause, exportedTypes)
);
}
}
if (ts.isClassDeclaration(node)) {
return factory.updateClassDeclaration(
const modifiersAndDecorators = [
...(ts.getModifiers(node) ?? []),
...(ts.getDecorators(node) ?? [])
];
return ts.factory.updateClassDeclaration(
node,
node.decorators,
node.modifiers,
modifiersAndDecorators,
node.name,
node.typeParameters,
prunedHeritageClauses,
[
...(node.members as ts.NodeArray<ts.ClassElement>),
...(additionalMembers as ts.ClassElement[])
]
[...node.members, ...inheritedClassMembers]
) as T;
} else if (ts.isInterfaceDeclaration(node)) {
return factory.updateInterfaceDeclaration(
return ts.factory.updateInterfaceDeclaration(
node,
node.decorators,
node.modifiers,
node.name,
node.typeParameters,
prunedHeritageClauses,
[
...(node.members as ts.NodeArray<ts.TypeElement>),
...(additionalMembers as ts.TypeElement[])
]
[...node.members, ...inheritedInterfaceProperties]
) as T;
} else {
throw new Error('Only classes or interfaces are supported');
@@ -271,7 +269,7 @@ function prunePrivateImports<
}
/**
* Iterates the provided symbols and returns named declarations for these
* Iterates over the provided symbols and returns named declarations for these
* symbols if they are missing from `currentClass`. This allows us to merge
* class hierarchies for classes whose inherited types are not part of the
* public API.
@@ -283,9 +281,9 @@ function convertPropertiesForEnclosingClass(
host: ts.CompilerHost,
sourceFile: ts.SourceFile,
parentClassSymbols: ts.Symbol[],
currentClass: ts.ClassDeclaration | ts.InterfaceDeclaration
): ts.Node[] {
const newMembers: ts.Node[] = [];
currentClass: ts.ClassDeclaration
): ts.ClassElement[] {
const newMembers: ts.ClassElement[] = [];
// The `codefix` package is not public but it does exactly what we want. It's
// the same package that is used by VSCode to fill in missing members, which
// is what we are using it for in this script. `codefix` handles missing
@@ -304,12 +302,78 @@ function convertPropertiesForEnclosingClass(
symbol.escapedName ==
(missingMember.name as ts.Identifier).escapedText
);
const jsDocComment = originalSymbol
? extractJSDocComment(originalSymbol, newMembers)
: undefined;
if (jsDocComment) {
newMembers.push(jsDocComment, missingMember);
} else {
if (originalSymbol) {
const jsDocComment = extractJSDocComment(originalSymbol, newMembers);
if (jsDocComment) {
ts.setSyntheticLeadingComments(missingMember, [
{
kind: ts.SyntaxKind.MultiLineCommentTrivia,
text: `*\n${jsDocComment}\n`,
hasTrailingNewLine: true,
pos: -1,
end: -1
}
]);
}
newMembers.push(missingMember);
}
}
);
return newMembers;
}
/**
* Iterates over the provided symbols and returns named declarations for these
* symbols if they are missing from `currentInterface`. This allows us to merge
* interface hierarchies for interfaces whose inherited properties are not part of the
* public API.
*
* This method relies on a private API in TypeScript's `codefix` package.
*/
function convertPropertiesForEnclosingDeclaration<
T extends ts.ClassDeclaration | ts.InterfaceDeclaration,
U extends ts.ClassElement | ts.TypeElement
>(
program: ts.Program,
host: ts.CompilerHost,
sourceFile: ts.SourceFile,
parentClassSymbols: ts.Symbol[],
currentDeclaration: T
): U[] {
const newMembers: U[] = [];
// The `codefix` package is not public but it does exactly what we want. It's
// the same package that is used by VSCode to fill in missing members, which
// is what we are using it for in this script. `codefix` handles missing
// properties, methods and correctly deduces generics.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(ts as any).codefix.createMissingMemberNodes(
currentDeclaration,
parentClassSymbols,
sourceFile,
{ program, host },
/* userPreferences= */ {},
/* importAdder= */ undefined,
(missingMember: U) => {
const originalSymbol = parentClassSymbols.find(
symbol =>
symbol.escapedName ==
(missingMember.name as ts.Identifier).escapedText
);
if (originalSymbol) {
const jsDocComment = extractJSDocComment(originalSymbol, newMembers);
if (jsDocComment) {
ts.setSyntheticLeadingComments(missingMember, [
{
kind: ts.SyntaxKind.MultiLineCommentTrivia,
text: `*\n${jsDocComment}\n`,
hasTrailingNewLine: true,
pos: -1,
end: -1
}
]);
}
newMembers.push(missingMember);
}
}
@@ -321,7 +385,7 @@ function convertPropertiesForEnclosingClass(
function extractJSDocComment(
symbol: ts.Symbol,
alreadyAddedMembers: ts.Node[]
): ts.Node | null {
): string | null {
const overloadCount = alreadyAddedMembers.filter(
node =>
ts.isClassElement(node) &&
@@ -330,37 +394,69 @@ function extractJSDocComment(
// Extract the comment from the overload that we are currently processing.
let targetIndex = 0;
const comments = symbol.getDocumentationComment(undefined).filter(symbol => {
// Overload comments are separated by line breaks.
if (symbol.kind == 'lineBreak') {
++targetIndex;
return false;
} else {
return overloadCount == targetIndex;
}
});
const commentParts = symbol
.getDocumentationComment(undefined)
.filter(symbol => {
// Overload comments are separated by line breaks.
if (symbol.kind == 'lineBreak') {
++targetIndex;
return false;
} else {
return overloadCount == targetIndex;
}
});
if (comments.length > 0 && symbol.declarations) {
const jsDocTags = ts.getJSDocTags(symbol.declarations[overloadCount]);
const maybeNewline = jsDocTags?.length > 0 ? '\n' : '';
const joinedComments = comments
.map(comment => {
if (comment.kind === 'linkText') {
return comment.text.trim();
}
return comment.text;
})
.join('');
const formattedComments = joinedComments
.replace('*', '\n')
.replace(' \n', '\n')
.replace('\n ', '\n');
return ts.factory.createJSDocComment(
formattedComments + maybeNewline,
jsDocTags
);
const comment = commentParts
.map(commentPart => {
if (commentPart.kind === 'linkText') {
/**
* Some links will be spread across more than one line. For example:
* {@link
* DocumentReference}
* In this case, we want to remove the leading ' * ' without removing the newline.
*/
const leadingStar = /(?!\n)\s*\* /;
/**
* For some reason, this text will also have a trailing space (the above example would give
* us 'DocumentReference '), so we trim that from the end of the string.
*/
const trailingSpaces = / *$/;
return commentPart.text
.replace(leadingStar, '\n')
.replace(trailingSpaces, '');
} else {
return commentPart.text;
}
})
.join('');
if (!comment || !symbol.declarations) {
return null;
}
return null;
const declaration = symbol.declarations[overloadCount];
const jsDocTags = ts
.getJSDocTags(declaration)
.map(tag =>
tag
.getFullText()
.split('\n')
.map(line => line.replace('*', '').trim())
.filter(line => line !== '') // Remove empty lines
.map(text => text.replace(/s*\* /, '')) // Remove the '*' prefix from all lines
.join('\n')
)
.join('\n');
const maybeNewline = jsDocTags?.length > 0 ? '\n' : '';
const commentAndTags = `${comment}\n${maybeNewline}${jsDocTags}`.trim();
const formattedJSDocComment = commentAndTags
.split('\n')
.map(line => ` * ${line.trim()}`)
.join('\n');
return formattedJSDocComment;
}
/**
@@ -468,7 +564,6 @@ function dropPrivateApiTransformer(
context: ts.TransformationContext
): ts.Transformer<ts.SourceFile> {
const typeChecker = program.getTypeChecker();
const { factory } = context;
return (sourceFile: ts.SourceFile) => {
function visit(node: ts.Node): ts.Node {
@@ -483,9 +578,11 @@ function dropPrivateApiTransformer(
) {
// Remove any types that are not exported.
if (
!node.modifiers?.find(m => m.kind === ts.SyntaxKind.ExportKeyword)
!ts
.getModifiers(node)
?.find(m => m.kind === ts.SyntaxKind.ExportKeyword)
) {
return factory.createNotEmittedStatement(node);
return ts.factory.createNotEmittedStatement(node);
}
}
@@ -498,7 +595,7 @@ function dropPrivateApiTransformer(
) {
// Remove any imports that reference internal APIs, while retaining
// their public members.
return prunePrivateImports(factory, program, host, sourceFile, node);
return prunePrivateImports(program, host, sourceFile, node);
} else if (
ts.isPropertyDeclaration(node) ||
ts.isMethodDeclaration(node) ||
@@ -507,7 +604,9 @@ function dropPrivateApiTransformer(
// Remove any class and interface members that are prefixed with
// underscores.
if (hasPrivatePrefix(node.name as ts.Identifier)) {
return factory.createNotEmittedStatement(node);
const notEmittedStatement =
ts.factory.createNotEmittedStatement(node);
return notEmittedStatement;
}
} else if (ts.isTypeReferenceNode(node)) {
// For public types that refer internal types, find a public type that
@@ -518,9 +617,9 @@ function dropPrivateApiTransformer(
node.typeName
);
return publicName
? factory.updateTypeReferenceNode(
? ts.factory.updateTypeReferenceNode(
node,
factory.createIdentifier(publicName.name),
ts.factory.createIdentifier(publicName.name),
node.typeArguments
)
: node;
+455
View File
@@ -0,0 +1,455 @@
/**
* @license
* Copyright 2024 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.
*/
/**
* Firebase Data Connect
*
* @packageDocumentation
*/
import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';
import { AppCheckTokenListener } from '@firebase/app-check-interop-types';
import { AppCheckTokenResult } from '@firebase/app-check-interop-types';
import { FirebaseApp } from '@firebase/app';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { FirebaseAuthTokenData } from '@firebase/auth-interop-types';
import { FirebaseError } from '@firebase/util';
import { LogLevelString } from '@firebase/logger';
import { Provider } from '@firebase/component';
/* Excluded from this release type: AppCheckTokenProvider */
declare type AuthTokenListener = (token: string | null) => void;
declare interface AuthTokenProvider {
getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData | null>;
addTokenChangeListener(listener: AuthTokenListener): void;
}
export declare interface CancellableOperation<T>
extends PromiseLike<{
data: T;
}> {
cancel: () => void;
}
/**
* Connect to the DataConnect Emulator
* @param dc Data Connect instance
* @param host host of emulator server
* @param port port of emulator server
* @param sslEnabled use https
*/
export declare function connectDataConnectEmulator(
dc: DataConnect,
host: string,
port?: number,
sslEnabled?: boolean
): void;
/**
* Connector Config for calling Data Connect backend.
*/
export declare interface ConnectorConfig {
location: string;
connector: string;
service: string;
}
/**
* Class representing Firebase Data Connect
*/
export declare class DataConnect {
readonly app: FirebaseApp;
private readonly dataConnectOptions;
private readonly _authProvider;
private readonly _appCheckProvider;
_queryManager: QueryManager;
_mutationManager: MutationManager;
isEmulator: boolean;
_initialized: boolean;
private _transport;
private _transportClass;
private _transportOptions?;
private _authTokenProvider?;
_isUsingGeneratedSdk: boolean;
private _appCheckTokenProvider?;
constructor(
app: FirebaseApp,
dataConnectOptions: DataConnectOptions,
_authProvider: Provider<FirebaseAuthInternalName>,
_appCheckProvider: Provider<AppCheckInternalComponentName>
);
_useGeneratedSdk(): void;
_delete(): Promise<void>;
getSettings(): ConnectorConfig;
setInitialized(): void;
enableEmulator(transportOptions: TransportOptions): void;
}
/** An error returned by a DataConnect operation. */
declare class DataConnectError extends FirebaseError {
/**
* The backend error code associated with this error.
*/
readonly code: DataConnectErrorCode;
/**
* A custom error description.
*/
readonly message: string;
/** The stack of the error. */
readonly stack?: string;
/** @hideconstructor */
constructor(
/**
* The backend error code associated with this error.
*/
code: DataConnectErrorCode,
/**
* A custom error description.
*/
message: string
);
}
declare type DataConnectErrorCode =
| 'other'
| 'already-initialized'
| 'not-initialized'
| 'not-supported'
| 'invalid-argument'
| 'partial-error'
| 'unauthorized';
/**
* DataConnectOptions including project id
*/
export declare interface DataConnectOptions extends ConnectorConfig {
projectId: string;
}
export declare interface DataConnectResult<Data, Variables>
extends OpResult<Data> {
ref: OperationRef<Data, Variables>;
}
/**
* Representation of user provided subscription options.
*/
export declare interface DataConnectSubscription<Data, Variables> {
userCallback: OnResultSubscription<Data, Variables>;
errCallback?: (e?: DataConnectError) => void;
unsubscribe: () => void;
}
/* Excluded from this release type: DataConnectTransport */
export declare type DataSource = typeof SOURCE_CACHE | typeof SOURCE_SERVER;
/**
* Execute Mutation
* @param mutationRef mutation to execute
* @returns `MutationRef`
*/
export declare function executeMutation<Data, Variables>(
mutationRef: MutationRef<Data, Variables>
): MutationPromise<Data, Variables>;
/**
* Execute Query
* @param queryRef query to execute.
* @returns `QueryPromise`
*/
export declare function executeQuery<Data, Variables>(
queryRef: QueryRef<Data, Variables>
): QueryPromise<Data, Variables>;
/**
* Initialize DataConnect instance
* @param options ConnectorConfig
*/
export declare function getDataConnect(options: ConnectorConfig): DataConnect;
/**
* Initialize DataConnect instance
* @param app FirebaseApp to initialize to.
* @param options ConnectorConfig
*/
export declare function getDataConnect(
app: FirebaseApp,
options: ConnectorConfig
): DataConnect;
export declare const MUTATION_STR = 'mutation';
/* Excluded from this release type: MutationManager */
/**
* Mutation return value from `executeMutation`
*/
export declare interface MutationPromise<Data, Variables>
extends PromiseLike<MutationResult<Data, Variables>> {}
export declare interface MutationRef<Data, Variables>
extends OperationRef<Data, Variables> {
refType: typeof MUTATION_STR;
}
/**
* Creates a `MutationRef`
* @param dcInstance Data Connect instance
* @param mutationName name of mutation
*/
export declare function mutationRef<Data>(
dcInstance: DataConnect,
mutationName: string
): MutationRef<Data, undefined>;
/**
*
* @param dcInstance Data Connect instance
* @param mutationName name of mutation
* @param variables variables to send with mutation
*/
export declare function mutationRef<Data, Variables>(
dcInstance: DataConnect,
mutationName: string,
variables: Variables
): MutationRef<Data, Variables>;
/**
* Mutation Result from `executeMutation`
*/
export declare interface MutationResult<Data, Variables>
extends DataConnectResult<Data, Variables> {
ref: MutationRef<Data, Variables>;
}
/**
* `OnCompleteSubscription`
*/
export declare type OnCompleteSubscription = () => void;
/**
* Signature for `OnErrorSubscription` for `subscribe`
*/
export declare type OnErrorSubscription = (err?: DataConnectError) => void;
/**
* Signature for `OnResultSubscription` for `subscribe`
*/
export declare type OnResultSubscription<Data, Variables> = (
res: QueryResult<Data, Variables>
) => void;
export declare interface OperationRef<_Data, Variables> {
name: string;
variables: Variables;
refType: ReferenceType;
dataConnect: DataConnect;
}
export declare interface OpResult<Data> {
data: Data;
source: DataSource;
fetchTime: string;
}
declare interface ParsedArgs<Variables> {
dc: DataConnect;
vars: Variables;
}
/* Excluded from this release type: parseOptions */
export declare const QUERY_STR = 'query';
declare class QueryManager {
private transport;
_queries: Map<string, TrackedQuery<unknown, unknown>>;
constructor(transport: DataConnectTransport);
track<Data, Variables>(
queryName: string,
variables: Variables,
initialCache?: OpResult<Data>
): TrackedQuery<Data, Variables>;
addSubscription<Data, Variables>(
queryRef: OperationRef<Data, Variables>,
onResultCallback: OnResultSubscription<Data, Variables>,
onErrorCallback?: OnErrorSubscription,
initialCache?: OpResult<Data>
): () => void;
executeQuery<Data, Variables>(
queryRef: QueryRef<Data, Variables>
): QueryPromise<Data, Variables>;
enableEmulator(host: string, port: number): void;
}
/**
* Promise returned from `executeQuery`
*/
export declare interface QueryPromise<Data, Variables>
extends PromiseLike<QueryResult<Data, Variables>> {}
/**
* QueryRef object
*/
export declare interface QueryRef<Data, Variables>
extends OperationRef<Data, Variables> {
refType: typeof QUERY_STR;
}
/**
* Execute Query
* @param dcInstance Data Connect instance to use.
* @param queryName Query to execute
* @returns `QueryRef`
*/
export declare function queryRef<Data>(
dcInstance: DataConnect,
queryName: string
): QueryRef<Data, undefined>;
/**
* Execute Query
* @param dcInstance Data Connect instance to use.
* @param queryName Query to execute
* @param variables Variables to execute with
* @returns `QueryRef`
*/
export declare function queryRef<Data, Variables>(
dcInstance: DataConnect,
queryName: string,
variables: Variables
): QueryRef<Data, Variables>;
/**
* Result of `executeQuery`
*/
export declare interface QueryResult<Data, Variables>
extends DataConnectResult<Data, Variables> {
ref: QueryRef<Data, Variables>;
toJSON: () => SerializedRef<Data, Variables>;
}
/**
* Signature for unsubscribe from `subscribe`
*/
export declare type QueryUnsubscribe = () => void;
export declare type ReferenceType = typeof QUERY_STR | typeof MUTATION_STR;
/**
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo`
*/
export declare interface RefInfo<Variables> {
name: string;
variables: Variables;
connectorConfig: DataConnectOptions;
}
/**
* Serialized Ref as a result of `QueryResult.toJSON()`
*/
export declare interface SerializedRef<Data, Variables> extends OpResult<Data> {
refInfo: RefInfo<Variables>;
}
export declare function setLogLevel(logLevel: LogLevelString): void;
export declare const SOURCE_CACHE = 'CACHE';
export declare const SOURCE_SERVER = 'SERVER';
/**
* Subscribe to a `QueryRef`
* @param queryRefOrSerializedResult query ref or serialized result.
* @param observer observer object to use for subscribing.
* @returns `SubscriptionOptions`
*/
export declare function subscribe<Data, Variables>(
queryRefOrSerializedResult:
| QueryRef<Data, Variables>
| SerializedRef<Data, Variables>,
observer: SubscriptionOptions<Data, Variables>
): QueryUnsubscribe;
/**
* Subscribe to a `QueryRef`
* @param queryRefOrSerializedResult query ref or serialized result.
* @param onNext Callback to call when result comes back.
* @param onError Callback to call when error gets thrown.
* @param onComplete Called when subscription completes.
* @returns `SubscriptionOptions`
*/
export declare function subscribe<Data, Variables>(
queryRefOrSerializedResult:
| QueryRef<Data, Variables>
| SerializedRef<Data, Variables>,
onNext: OnResultSubscription<Data, Variables>,
onError?: OnErrorSubscription,
onComplete?: OnCompleteSubscription
): QueryUnsubscribe;
/**
* Representation of full observer options in `subscribe`
*/
export declare interface SubscriptionOptions<Data, Variables> {
onNext?: OnResultSubscription<Data, Variables>;
onErr?: OnErrorSubscription;
onComplete?: OnCompleteSubscription;
}
/**
* Delete DataConnect instance
* @param dataConnect DataConnect instance
* @returns
*/
export declare function terminate(dataConnect: DataConnect): Promise<void>;
/**
* Converts serialized ref to query ref
* @param serializedRef ref to convert to `QueryRef`
* @returns `QueryRef`
*/
export declare function toQueryRef<Data, Variables>(
serializedRef: SerializedRef<Data, Variables>
): QueryRef<Data, Variables>;
declare interface TrackedQuery<Data, Variables> {
ref: Omit<OperationRef<Data, Variables>, 'dataConnect'>;
subscriptions: Array<DataConnectSubscription<Data, Variables>>;
currentCache: OpResult<Data> | null;
lastError: DataConnectError | null;
}
/* Excluded from this release type: TransportClass */
/**
* Options to connect to emulator
*/
export declare interface TransportOptions {
host: string;
sslEnabled?: boolean;
port?: number;
}
/* Excluded from this release type: validateArgs */
/* Excluded from this release type: validateDCOptions */
export {};
+315
View File
@@ -0,0 +1,315 @@
/**
* @license
* Copyright 2024 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.
*/
/**
* Firebase Data Connect
*
* @packageDocumentation
*/
import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';
import { AppCheckTokenListener } from '@firebase/app-check-interop-types';
import { AppCheckTokenResult } from '@firebase/app-check-interop-types';
import { FirebaseApp } from '@firebase/app';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { FirebaseAuthTokenData } from '@firebase/auth-interop-types';
import { FirebaseError } from '@firebase/util';
import { LogLevelString } from '@firebase/logger';
import { Provider } from '@firebase/component';
export declare interface CancellableOperation<T>
extends PromiseLike<{
data: T;
}> {
cancel: () => void;
}
/**
* Connect to the DataConnect Emulator
* @param dc Data Connect instance
* @param host host of emulator server
* @param port port of emulator server
* @param sslEnabled use https
*/
export declare function connectDataConnectEmulator(
dc: DataConnect,
host: string,
port?: number,
sslEnabled?: boolean
): void;
/**
* Connector Config for calling Data Connect backend.
*/
export declare interface ConnectorConfig {
location: string;
connector: string;
service: string;
}
/**
* Class representing Firebase Data Connect
*/
export declare class DataConnect {
readonly app: FirebaseApp;
private readonly dataConnectOptions;
isEmulator: boolean;
constructor(
app: FirebaseApp,
dataConnectOptions: DataConnectOptions,
_authProvider: Provider<FirebaseAuthInternalName>,
_appCheckProvider: Provider<AppCheckInternalComponentName>
);
getSettings(): ConnectorConfig;
setInitialized(): void;
enableEmulator(transportOptions: TransportOptions): void;
}
/**
* DataConnectOptions including project id
*/
export declare interface DataConnectOptions extends ConnectorConfig {
projectId: string;
}
export declare interface DataConnectResult<Data, Variables>
extends OpResult<Data> {
ref: OperationRef<Data, Variables>;
}
/**
* Representation of user provided subscription options.
*/
export declare interface DataConnectSubscription<Data, Variables> {
userCallback: OnResultSubscription<Data, Variables>;
errCallback?: (e?: FirebaseError) => void;
unsubscribe: () => void;
}
/* Excluded from this release type: DataConnectTransport */
export declare type DataSource = typeof SOURCE_CACHE | typeof SOURCE_SERVER;
/**
* Execute Mutation
* @param mutationRef mutation to execute
* @returns `MutationRef`
*/
export declare function executeMutation<Data, Variables>(
mutationRef: MutationRef<Data, Variables>
): MutationPromise<Data, Variables>;
/**
* Execute Query
* @param queryRef query to execute.
* @returns `QueryPromise`
*/
export declare function executeQuery<Data, Variables>(
queryRef: QueryRef<Data, Variables>
): QueryPromise<Data, Variables>;
/**
* Initialize DataConnect instance
* @param options ConnectorConfig
*/
export declare function getDataConnect(options: ConnectorConfig): DataConnect;
/**
* Initialize DataConnect instance
* @param app FirebaseApp to initialize to.
* @param options ConnectorConfig
*/
export declare function getDataConnect(
app: FirebaseApp,
options: ConnectorConfig
): DataConnect;
export declare const MUTATION_STR = 'mutation';
/* Excluded from this release type: MutationManager */
/**
* Mutation return value from `executeMutation`
*/
export declare interface MutationPromise<Data, Variables>
extends PromiseLike<MutationResult<Data, Variables>> {}
export declare interface MutationRef<Data, Variables>
extends OperationRef<Data, Variables> {
refType: typeof MUTATION_STR;
}
/**
* Creates a `MutationRef`
* @param dcInstance Data Connect instance
* @param mutationName name of mutation
*/
export declare function mutationRef<Data>(
dcInstance: DataConnect,
mutationName: string
): MutationRef<Data, undefined>;
/**
*
* @param dcInstance Data Connect instance
* @param mutationName name of mutation
* @param variables variables to send with mutation
*/
export declare function mutationRef<Data, Variables>(
dcInstance: DataConnect,
mutationName: string,
variables: Variables
): MutationRef<Data, Variables>;
/**
* Mutation Result from `executeMutation`
*/
export declare interface MutationResult<Data, Variables>
extends DataConnectResult<Data, Variables> {
ref: MutationRef<Data, Variables>;
}
/**
* `OnCompleteSubscription`
*/
export declare type OnCompleteSubscription = () => void;
/**
* Signature for `OnErrorSubscription` for `subscribe`
*/
export declare type OnErrorSubscription = (err?: FirebaseError) => void;
/**
* Signature for `OnResultSubscription` for `subscribe`
*/
export declare type OnResultSubscription<Data, Variables> = (
res: QueryResult<Data, Variables>
) => void;
export declare interface OperationRef<_Data, Variables> {
name: string;
variables: Variables;
refType: ReferenceType;
dataConnect: DataConnect;
}
export declare interface OpResult<Data> {
data: Data;
source: DataSource;
fetchTime: string;
}
/* Excluded from this release type: parseOptions */
export declare const QUERY_STR = 'query';
/**
* Promise returned from `executeQuery`
*/
export declare interface QueryPromise<Data, Variables>
extends PromiseLike<QueryResult<Data, Variables>> {}
/**
* QueryRef object
*/
export declare interface QueryRef<Data, Variables>
extends OperationRef<Data, Variables> {
refType: typeof QUERY_STR;
}
/**
* Execute Query
* @param dcInstance Data Connect instance to use.
* @param queryName Query to execute
* @returns `QueryRef`
*/
export declare function queryRef<Data>(
dcInstance: DataConnect,
queryName: string
): QueryRef<Data, undefined>;
/**
* Execute Query
* @param dcInstance Data Connect instance to use.
* @param queryName Query to execute
* @param variables Variables to execute with
* @returns `QueryRef`
*/
export declare function queryRef<Data, Variables>(
dcInstance: DataConnect,
queryName: string,
variables: Variables
): QueryRef<Data, Variables>;
/**
* Result of `executeQuery`
*/
export declare interface QueryResult<Data, Variables>
extends DataConnectResult<Data, Variables> {
ref: QueryRef<Data, Variables>;
toJSON: () => SerializedRef<Data, Variables>;
}
/**
* Signature for unsubscribe from `subscribe`
*/
export declare type QueryUnsubscribe = () => void;
export declare type ReferenceType = typeof QUERY_STR | typeof MUTATION_STR;
/**
* Serialized RefInfo as a result of `QueryResult.toJSON().refInfo`
*/
export declare interface RefInfo<Variables> {
name: string;
variables: Variables;
connectorConfig: DataConnectOptions;
}
/**
* Serialized Ref as a result of `QueryResult.toJSON()`
*/
export declare interface SerializedRef<Data, Variables> extends OpResult<Data> {
refInfo: RefInfo<Variables>;
}
export declare function setLogLevel(logLevel: LogLevelString): void;
export declare const SOURCE_CACHE = 'CACHE';
export declare const SOURCE_SERVER = 'SERVER';
/**
* Subscribe to a `QueryRef`
* @param queryRefOrSerializedResult query ref or serialized result.
* @param observer observer object to use for subscribing.
* @returns `SubscriptionOptions`
*/
export declare function subscribe<Data, Variables>(
queryRefOrSerializedResult:
| QueryRef<Data, Variables>
| SerializedRef<Data, Variables>,
observer: SubscriptionOptions<Data, Variables>
): QueryUnsubscribe;
/**
* Subscribe to a `QueryRef`
* @param queryRefOrSerializedResult query ref or serialized result.
* @param onNext Callback to call when result comes back.
* @param onError Callback to call when error gets thrown.
* @param onComplete Called when subscription completes.
* @returns `SubscriptionOptions`
*/
export declare function subscribe<Data, Variables>(
queryRefOrSerializedResult:
| QueryRef<Data, Variables>
| SerializedRef<Data, Variables>,
onNext: OnResultSubscription<Data, Variables>,
onError?: OnErrorSubscription,
onComplete?: OnCompleteSubscription
): QueryUnsubscribe;
/**
* Representation of full observer options in `subscribe`
*/
export declare interface SubscriptionOptions<Data, Variables> {
onNext?: OnResultSubscription<Data, Variables>;
onErr?: OnErrorSubscription;
onComplete?: OnCompleteSubscription;
}
/**
* Delete DataConnect instance
* @param dataConnect DataConnect instance
* @returns
*/
export declare function terminate(dataConnect: DataConnect): Promise<void>;
/**
* Converts serialized ref to query ref
* @param serializedRef ref to convert to `QueryRef`
* @returns `QueryRef`
*/
export declare function toQueryRef<Data, Variables>(
serializedRef: SerializedRef<Data, Variables>
): QueryRef<Data, Variables>;
/* Excluded from this release type: TransportClass */
/**
* Options to connect to emulator
*/
export declare interface TransportOptions {
host: string;
sslEnabled?: boolean;
port?: number;
}
/* Excluded from this release type: validateArgs */
/* Excluded from this release type: validateDCOptions */
export {};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+223
View File
@@ -0,0 +1,223 @@
/**
* The Firebase Cloud Messaging Web SDK.
* This SDK does not work in a Node.js environment.
*
* @packageDocumentation
*/
import { FirebaseApp } from '@firebase/app';
import { NextFn } from '@firebase/util';
import { Observer } from '@firebase/util';
import { Unsubscribe } from '@firebase/util';
/**
* Deletes the registration token associated with this {@link Messaging} instance and unsubscribes
* the {@link Messaging} instance from the push subscription.
*
* @param messaging - The {@link Messaging} instance.
*
* @returns The promise resolves when the token has been successfully deleted.
*
* @public
*/
export declare function deleteToken(messaging: Messaging): Promise<boolean>;
/**
* Options for features provided by the FCM SDK for Web. See {@link
* https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions |
* WebpushFcmOptions}.
*
* @public
*/
export declare interface FcmOptions {
/**
* The link to open when the user clicks on the notification.
*/
link?: string;
/**
* The label associated with the message's analytics data.
*/
analyticsLabel?: string;
}
/* Excluded from this release type: _FirebaseMessagingName */
/**
* Retrieves a Firebase Cloud Messaging instance.
*
* @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
*
* @public
*/
export declare function getMessaging(app?: FirebaseApp): Messaging;
/**
* Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud
* Messaging registration token that can be used to send push messages to that {@link Messaging}
* instance.
*
* If notification permission isn't already granted, this method asks the user for permission. The
* returned promise rejects if the user does not allow the app to show notifications.
*
* @param messaging - The {@link Messaging} instance.
* @param options - Provides an optional vapid key and an optional service worker registration.
*
* @returns The promise resolves with an FCM registration token.
*
* @public
*/
export declare function getToken(
messaging: Messaging,
options?: GetTokenOptions
): Promise<string>;
/**
* Options for {@link getToken}.
*
* @public
*/
export declare interface GetTokenOptions {
/**
* The public server key provided to push services. The key is used to
* authenticate push subscribers to receive push messages only from sending servers that hold
* the corresponding private key. If it is not provided, a default VAPID key is used. Note that some
* push services (Chrome Push Service) require a non-default VAPID key. Therefore, it is recommended
* to generate and import a VAPID key for your project with
* {@link https://firebase.google.com/docs/cloud-messaging/js/client#configure_web_credentials_in_your_app | Configure Web Credentials with FCM}.
* See
* {@link https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol | The Web Push Protocol}
* for details on web push services.
*/
vapidKey?: string;
/**
* The service worker registration for receiving push
* messaging. If the registration is not provided explicitly, you need to have a
* `firebase-messaging-sw.js` at your root location. See
* {@link https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token | Access the registration token}
* for more details.
*/
serviceWorkerRegistration?: ServiceWorkerRegistration;
}
/**
* @license
* 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.
*/
/**
* Checks if all required APIs exist in the browser.
* @returns a Promise that resolves to a boolean.
*
* @public
*/
export declare function isSupported(): Promise<boolean>;
/**
* Message payload that contains the notification payload that is represented with
* {@link NotificationPayload} and the data payload that contains an arbitrary
* number of key-value pairs sent by developers through the
* {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}.
*
* @public
*/
export declare interface MessagePayload {
/**
* {@inheritdoc NotificationPayload}
*/
notification?: NotificationPayload;
/**
* Arbitrary key/value payload.
*/
data?: {
[key: string]: string;
};
/**
* {@inheritdoc FcmOptions}
*/
fcmOptions?: FcmOptions;
/**
* The sender of this message.
*/
from: string;
/**
* The collapse key of the message. See
* {@link https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages | Non-collapsible and collapsible messages}
*/
collapseKey: string;
/**
* The message ID of a message.
*/
messageId: string;
}
/**
* Public interface of the Firebase Cloud Messaging SDK.
*
* @public
*/
export declare interface Messaging {
/**
* The {@link @firebase/app#FirebaseApp} this `Messaging` instance is associated with.
*/
app: FirebaseApp;
}
export { NextFn };
/**
* Display notification details. Details are sent through the
* {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}.
*
* @public
*/
export declare interface NotificationPayload {
/**
* The notification's title.
*/
title?: string;
/**
* The notification's body text.
*/
body?: string;
/**
* The URL of an image that is downloaded on the device and displayed in the notification.
*/
image?: string;
/**
* The URL to use for the notification's icon. If you don't send this key in the request,
* FCM displays the launcher icon specified in your app manifest.
*/
icon?: string;
}
export { Observer };
/**
* When a push message is received and the user is currently on a page for your origin, the
* message is passed to the page and an `onMessage()` event is dispatched with the payload of
* the push message.
*
*
* @param messaging - The {@link Messaging} instance.
* @param nextOrObserver - This function, or observer object with `next` defined,
* is called when a message is received and the user is currently viewing your page.
* @returns To stop listening for messages execute this returned function.
*
* @public
*/
export declare function onMessage(
messaging: Messaging,
nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>
): Unsubscribe;
export { Unsubscribe };
export {};
+210
View File
@@ -0,0 +1,210 @@
/**
* The Firebase Cloud Messaging Web SDK.
* This SDK does not work in a Node.js environment.
*
* @packageDocumentation
*/
import { FirebaseApp } from '@firebase/app';
import { NextFn } from '@firebase/util';
import { Observer } from '@firebase/util';
import { Unsubscribe } from '@firebase/util';
/**
* Deletes the registration token associated with this {@link Messaging} instance and unsubscribes
* the {@link Messaging} instance from the push subscription.
*
* @param messaging - The {@link Messaging} instance.
*
* @returns The promise resolves when the token has been successfully deleted.
*
* @public
*/
export declare function deleteToken(messaging: Messaging): Promise<boolean>;
/**
* Options for features provided by the FCM SDK for Web. See {@link
* https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions |
* WebpushFcmOptions}.
*
* @public
*/
export declare interface FcmOptions {
/**
* The link to open when the user clicks on the notification.
*/
link?: string;
/**
* The label associated with the message's analytics data.
*/
analyticsLabel?: string;
}
/* Excluded from this release type: _FirebaseMessagingName */
/**
* Retrieves a Firebase Cloud Messaging instance.
*
* @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
*
* @public
*/
export declare function getMessaging(app?: FirebaseApp): Messaging;
/**
* Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud
* Messaging registration token that can be used to send push messages to that {@link Messaging}
* instance.
*
* If notification permission isn't already granted, this method asks the user for permission. The
* returned promise rejects if the user does not allow the app to show notifications.
*
* @param messaging - The {@link Messaging} instance.
* @param options - Provides an optional vapid key and an optional service worker registration.
*
* @returns The promise resolves with an FCM registration token.
*
* @public
*/
export declare function getToken(
messaging: Messaging,
options?: GetTokenOptions
): Promise<string>;
/**
* Options for {@link getToken}.
*
* @public
*/
export declare interface GetTokenOptions {
/**
* The public server key provided to push services. The key is used to
* authenticate push subscribers to receive push messages only from sending servers that hold
* the corresponding private key. If it is not provided, a default VAPID key is used. Note that some
* push services (Chrome Push Service) require a non-default VAPID key. Therefore, it is recommended
* to generate and import a VAPID key for your project with
* {@link https://firebase.google.com/docs/cloud-messaging/js/client#configure_web_credentials_in_your_app | Configure Web Credentials with FCM}.
* See
* {@link https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol | The Web Push Protocol}
* for details on web push services.
*/
vapidKey?: string;
/**
* The service worker registration for receiving push
* messaging. If the registration is not provided explicitly, you need to have a
* `firebase-messaging-sw.js` at your root location. See
* {@link https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token | Access the registration token}
* for more details.
*/
serviceWorkerRegistration?: ServiceWorkerRegistration;
}
/**
* @license
* 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.
*/
/**
* Checks if all required APIs exist in the browser.
* @returns a Promise that resolves to a boolean.
*
* @public
*/
export declare function isSupported(): Promise<boolean>;
/**
* Message payload that contains the notification payload that is represented with
* {@link NotificationPayload} and the data payload that contains an arbitrary
* number of key-value pairs sent by developers through the
* {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}.
*
* @public
*/
export declare interface MessagePayload {
/**
* {@inheritdoc NotificationPayload}
*/
notification?: NotificationPayload;
/**
* Arbitrary key/value payload.
*/
data?: {
[key: string]: string;
};
/**
* {@inheritdoc FcmOptions}
*/
fcmOptions?: FcmOptions;
/**
* The sender of this message.
*/
from: string;
/**
* The collapse key of the message. See
* {@link https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages | Non-collapsible and collapsible messages}
*/
collapseKey: string;
/**
* The message ID of a message.
*/
messageId: string;
}
/**
* Public interface of the Firebase Cloud Messaging SDK.
*
* @public
*/
export declare interface Messaging {
/**
* The {@link @firebase/app#FirebaseApp} this `Messaging` instance is associated with.
*/
app: FirebaseApp;
}
export { NextFn };
/**
* Display notification details. Details are sent through the
* {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}.
*
* @public
*/
export declare interface NotificationPayload {
/**
* The notification's title.
*/
title?: string;
/**
* The notification's body text.
*/
body?: string;
/**
* The URL of an image that is downloaded on the device and displayed in the notification.
*/
image?: string;
/**
* The URL to use for the notification's icon. If you don't send this key in the request,
* FCM displays the launcher icon specified in your app manifest.
*/
icon?: string;
}
export { Observer };
/**
* When a push message is received and the user is currently on a page for your origin, the
* message is passed to the page and an `onMessage()` event is dispatched with the payload of
* the push message.
*
*
* @param messaging - The {@link Messaging} instance.
* @param nextOrObserver - This function, or observer object with `next` defined,
* is called when a message is received and the user is currently viewing your page.
* @returns To stop listening for messages execute this returned function.
*
* @public
*/
export declare function onMessage(
messaging: Messaging,
nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>
): Unsubscribe;
export { Unsubscribe };
export {};
File diff suppressed because it is too large Load Diff
+796
View File
@@ -0,0 +1,796 @@
/**
* Cloud Storage for Firebase
*
* @packageDocumentation
*/
import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';
import { CompleteFn } from '@firebase/util';
import { EmulatorMockTokenOptions } from '@firebase/util';
import { FirebaseApp } from '@firebase/app';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { FirebaseError } from '@firebase/util';
import { NextFn } from '@firebase/util';
import { Provider } from '@firebase/component';
import { Subscribe } from '@firebase/util';
import { Unsubscribe } from '@firebase/util';
/**
* Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.
*
* @param storage - The {@link FirebaseStorage} instance
* @param host - The emulator host (ex: localhost)
* @param port - The emulator port (ex: 5001)
* @param options - Emulator options. `options.mockUserToken` is the mock auth
* token to use for unit testing Security Rules.
* @public
*/
export declare function connectStorageEmulator(
storage: FirebaseStorage,
host: string,
port: number,
options?: {
mockUserToken?: EmulatorMockTokenOptions | string;
}
): void;
/* Excluded from this release type: _dataFromString */
/**
* Deletes the object at this location.
* @public
* @param ref - {@link StorageReference} for object to delete.
* @returns A `Promise` that resolves if the deletion succeeds.
*/
export declare function deleteObject(ref: StorageReference): Promise<void>;
export { EmulatorMockTokenOptions };
/* Excluded from this release type: _FbsBlob */
/* Excluded from this release type: _FirebaseService */
/**
* A Firebase Storage instance.
* @public
*/
export declare interface FirebaseStorage {
/**
* The {@link @firebase/app#FirebaseApp} associated with this `FirebaseStorage` instance.
*/
readonly app: FirebaseApp;
/**
* The maximum time to retry uploads in milliseconds.
*/
maxUploadRetryTime: number;
/**
* The maximum time to retry operations other than uploads or downloads in
* milliseconds.
*/
maxOperationRetryTime: number;
}
/* Excluded from this release type: _FirebaseStorageImpl */
/**
* The full set of object metadata, including read-only properties.
* @public
*/
export declare interface FullMetadata extends UploadMetadata {
/**
* The bucket this object is contained in.
*/
bucket: string;
/**
* The full path of this object.
*/
fullPath: string;
/**
* The object's generation.
* {@link https://cloud.google.com/storage/docs/metadata#generation-number}
*/
generation: string;
/**
* The object's metageneration.
* {@link https://cloud.google.com/storage/docs/metadata#generation-number}
*/
metageneration: string;
/**
* The short name of this object, which is the last component of the full path.
* For example, if fullPath is 'full/path/image.png', name is 'image.png'.
*/
name: string;
/**
* The size of this object, in bytes.
*/
size: number;
/**
* A date string representing when this object was created.
*/
timeCreated: string;
/**
* A date string representing when this object was last updated.
*/
updated: string;
/**
* Tokens to allow access to the download URL.
*/
downloadTokens: string[] | undefined;
/**
* `StorageReference` associated with this upload.
*/
ref?: StorageReference | undefined;
}
/**
* Downloads the data at the object's location. Returns an error if the object
* is not found.
*
* To use this functionality, you have to whitelist your app's origin in your
* Cloud Storage bucket. See also
* https://cloud.google.com/storage/docs/configuring-cors
*
* This API is not available in Node.
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A Promise that resolves with a Blob containing the object's bytes
*/
export declare function getBlob(
ref: StorageReference,
maxDownloadSizeBytes?: number
): Promise<Blob>;
/**
* Downloads the data at the object's location. Returns an error if the object
* is not found.
*
* To use this functionality, you have to whitelist your app's origin in your
* Cloud Storage bucket. See also
* https://cloud.google.com/storage/docs/configuring-cors
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A Promise containing the object's bytes
*/
export declare function getBytes(
ref: StorageReference,
maxDownloadSizeBytes?: number
): Promise<ArrayBuffer>;
/* Excluded from this release type: _getChild */
/**
* Returns the download URL for the given {@link StorageReference}.
* @public
* @param ref - {@link StorageReference} to get the download URL for.
* @returns A `Promise` that resolves with the download
* URL for this object.
*/
export declare function getDownloadURL(ref: StorageReference): Promise<string>;
/**
* A `Promise` that resolves with the metadata for this object. If this
* object doesn't exist or metadata cannot be retrieved, the promise is
* rejected.
* @public
* @param ref - {@link StorageReference} to get metadata from.
*/
export declare function getMetadata(
ref: StorageReference
): Promise<FullMetadata>;
/**
* Gets a {@link FirebaseStorage} instance for the given Firebase app.
* @public
* @param app - Firebase app to get {@link FirebaseStorage} instance for.
* @param bucketUrl - The gs:// url to your Firebase Storage Bucket.
* If not passed, uses the app's default Storage Bucket.
* @returns A {@link FirebaseStorage} instance.
*/
export declare function getStorage(
app?: FirebaseApp,
bucketUrl?: string
): FirebaseStorage;
/**
* Downloads the data at the object's location. Raises an error event if the
* object is not found.
*
* This API is only available in Node.
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A stream with the object's data as bytes
*/
export declare function getStream(
ref: StorageReference,
maxDownloadSizeBytes?: number
): ReadableStream;
/* Excluded from this release type: _invalidArgument */
/* Excluded from this release type: _invalidRootOperation */
/**
* List items (files) and prefixes (folders) under this storage reference.
*
* List API is only available for Firebase Rules Version 2.
*
* GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
* delimited folder structure.
* Refer to GCS's List API if you want to learn more.
*
* To adhere to Firebase Rules's Semantics, Firebase Storage does not
* support objects whose paths end with "/" or contain two consecutive
* "/"s. Firebase Storage List API will filter these unsupported objects.
* list() may fail if there are too many unsupported objects in the bucket.
* @public
*
* @param ref - {@link StorageReference} to get list from.
* @param options - See {@link ListOptions} for details.
* @returns A `Promise` that resolves with the items and prefixes.
* `prefixes` contains references to sub-folders and `items`
* contains references to objects in this folder. `nextPageToken`
* can be used to get the rest of the results.
*/
export declare function list(
ref: StorageReference,
options?: ListOptions
): Promise<ListResult>;
/**
* List all items (files) and prefixes (folders) under this storage reference.
*
* This is a helper method for calling list() repeatedly until there are
* no more results. The default pagination size is 1000.
*
* Note: The results may not be consistent if objects are changed while this
* operation is running.
*
* Warning: `listAll` may potentially consume too many resources if there are
* too many results.
* @public
* @param ref - {@link StorageReference} to get list from.
*
* @returns A `Promise` that resolves with all the items and prefixes under
* the current storage reference. `prefixes` contains references to
* sub-directories and `items` contains references to objects in this
* folder. `nextPageToken` is never returned.
*/
export declare function listAll(ref: StorageReference): Promise<ListResult>;
/**
* The options `list()` accepts.
* @public
*/
export declare interface ListOptions {
/**
* If set, limits the total number of `prefixes` and `items` to return.
* The default and maximum maxResults is 1000.
*/
maxResults?: number | null;
/**
* The `nextPageToken` from a previous call to `list()`. If provided,
* listing is resumed from the previous position.
*/
pageToken?: string | null;
}
/**
* Result returned by list().
* @public
*/
export declare interface ListResult {
/**
* References to prefixes (sub-folders). You can call list() on them to
* get its contents.
*
* Folders are implicit based on '/' in the object paths.
* For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a')
* will return '/a/b' as a prefix.
*/
prefixes: StorageReference[];
/**
* Objects in this directory.
* You can call getMetadata() and getDownloadUrl() on them.
*/
items: StorageReference[];
/**
* If set, there might be more results for this list. Use this token to resume the list.
*/
nextPageToken?: string;
}
/**
* Returns a {@link StorageReference} for the given url.
* @param storage - {@link FirebaseStorage} instance.
* @param url - URL. If empty, returns root reference.
* @public
*/
export declare function ref(
storage: FirebaseStorage,
url?: string
): StorageReference;
/**
* Returns a {@link StorageReference} for the given path in the
* default bucket.
* @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}.
* @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage}
* instance provided) or returns same reference (if {@link StorageReference} provided).
* @public
*/
export declare function ref(
storageOrRef: FirebaseStorage | StorageReference,
path?: string
): StorageReference;
/**
* Object metadata that can be set at any time.
* @public
*/
export declare interface SettableMetadata {
/**
* Served as the 'Cache-Control' header on object download.
*/
cacheControl?: string | undefined;
/**
* Served as the 'Content-Disposition' header on object download.
*/
contentDisposition?: string | undefined;
/**
* Served as the 'Content-Encoding' header on object download.
*/
contentEncoding?: string | undefined;
/**
* Served as the 'Content-Language' header on object download.
*/
contentLanguage?: string | undefined;
/**
* Served as the 'Content-Type' header on object download.
*/
contentType?: string | undefined;
/**
* Additional user-defined custom metadata.
*/
customMetadata?:
| {
[key: string]: string;
}
| undefined;
}
/**
* An error returned by the Firebase Storage SDK.
* @public
*/
export declare class StorageError extends FirebaseError {
private status_;
/**
* Stores custom error data unique to the `StorageError`.
*/
customData: {
serverResponse: string | null;
};
/**
* @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
* added to the end of the message.
* @param message - Error message.
* @param status_ - Corresponding HTTP Status Code
*/
constructor(code: StorageErrorCode, message: string, status_?: number);
get status(): number;
set status(status: number);
/**
* Optional response message that was added by the server.
*/
get serverResponse(): null | string;
set serverResponse(serverResponse: string | null);
}
/**
* @public
* Error codes that can be attached to `StorageError` objects.
*/
export declare enum StorageErrorCode {
UNKNOWN = 'unknown',
OBJECT_NOT_FOUND = 'object-not-found',
BUCKET_NOT_FOUND = 'bucket-not-found',
PROJECT_NOT_FOUND = 'project-not-found',
QUOTA_EXCEEDED = 'quota-exceeded',
UNAUTHENTICATED = 'unauthenticated',
UNAUTHORIZED = 'unauthorized',
UNAUTHORIZED_APP = 'unauthorized-app',
RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded',
INVALID_CHECKSUM = 'invalid-checksum',
CANCELED = 'canceled',
INVALID_EVENT_NAME = 'invalid-event-name',
INVALID_URL = 'invalid-url',
INVALID_DEFAULT_BUCKET = 'invalid-default-bucket',
NO_DEFAULT_BUCKET = 'no-default-bucket',
CANNOT_SLICE_BLOB = 'cannot-slice-blob',
SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size',
NO_DOWNLOAD_URL = 'no-download-url',
INVALID_ARGUMENT = 'invalid-argument',
INVALID_ARGUMENT_COUNT = 'invalid-argument-count',
APP_DELETED = 'app-deleted',
INVALID_ROOT_OPERATION = 'invalid-root-operation',
INVALID_FORMAT = 'invalid-format',
INTERNAL_ERROR = 'internal-error',
UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'
}
/**
* A stream observer for Firebase Storage.
* @public
*/
export declare interface StorageObserver<T> {
next?: NextFn<T> | null;
error?: (error: StorageError) => void | null;
complete?: CompleteFn | null;
}
/**
* Represents a reference to a Google Cloud Storage object. Developers can
* upload, download, and delete objects, as well as get/set object metadata.
* @public
*/
export declare interface StorageReference {
/**
* Returns a gs:// URL for this object in the form
* `gs://<bucket>/<path>/<to>/<object>`
* @returns The gs:// URL.
*/
toString(): string;
/**
* A reference to the root of this object's bucket.
*/
root: StorageReference;
/**
* The name of the bucket containing this reference's object.
*/
bucket: string;
/**
* The full path of this object.
*/
fullPath: string;
/**
* The short name of this object, which is the last component of the full path.
* For example, if fullPath is 'full/path/image.png', name is 'image.png'.
*/
name: string;
/**
* The {@link FirebaseStorage} instance associated with this reference.
*/
storage: FirebaseStorage;
/**
* A reference pointing to the parent location of this reference, or null if
* this reference is the root.
*/
parent: StorageReference | null;
}
/**
* @license
* Copyright 2017 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.
*/
/**
* An enumeration of the possible string formats for upload.
* @public
*/
export declare type StringFormat =
(typeof StringFormat)[keyof typeof StringFormat];
/**
* An enumeration of the possible string formats for upload.
* @public
*/
export declare const StringFormat: {
/**
* Indicates the string should be interpreted "raw", that is, as normal text.
* The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
* sequence.
* Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
* 48 65 6c 6c 6f 21 20 f0 9f 98 8a
*/
readonly RAW: 'raw';
/**
* Indicates the string should be interpreted as base64-encoded data.
* Padding characters (trailing '='s) are optional.
* Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
* ad 69 8e fb e1 3a b7 bf eb 97
*/
readonly BASE64: 'base64';
/**
* Indicates the string should be interpreted as base64url-encoded data.
* Padding characters (trailing '='s) are optional.
* Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
* ad 69 8e fb e1 3a b7 bf eb 97
*/
readonly BASE64URL: 'base64url';
/**
* Indicates the string is a data URL, such as one obtained from
* canvas.toDataURL().
* Example: the string 'data:application/octet-stream;base64,aaaa'
* becomes the byte sequence
* 69 a6 9a
* (the content-type "application/octet-stream" is also applied, but can
* be overridden in the metadata object).
*/
readonly DATA_URL: 'data_url';
};
/**
* An event that is triggered on a task.
* @public
*/
export declare type TaskEvent = 'state_changed';
/* Excluded from this release type: _TaskEvent */
/**
* Represents the current state of a running upload.
* @public
*/
export declare type TaskState =
| 'running'
| 'paused'
| 'success'
| 'canceled'
| 'error';
/**
* Updates the metadata for this object.
* @public
* @param ref - {@link StorageReference} to update metadata for.
* @param metadata - The new metadata for the object.
* Only values that have been explicitly set will be changed. Explicitly
* setting a value to null will remove the metadata.
* @returns A `Promise` that resolves with the new metadata for this object.
*/
export declare function updateMetadata(
ref: StorageReference,
metadata: SettableMetadata
): Promise<FullMetadata>;
/**
* Uploads data to this object's location.
* The upload is not resumable.
* @public
* @param ref - {@link StorageReference} where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the data to upload.
* @returns A Promise containing an UploadResult
*/
export declare function uploadBytes(
ref: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata
): Promise<UploadResult>;
/**
* Uploads data to this object's location.
* The upload can be paused and resumed, and exposes progress updates.
* @public
* @param ref - {@link StorageReference} where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the data to upload.
* @returns An UploadTask
*/
export declare function uploadBytesResumable(
ref: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata
): UploadTask;
/**
* Object metadata that can be set at upload.
* @public
*/
export declare interface UploadMetadata extends SettableMetadata {
/**
* A Base64-encoded MD5 hash of the object being uploaded.
*/
md5Hash?: string | undefined;
}
/**
* Result returned from a non-resumable upload.
* @public
*/
export declare interface UploadResult {
/**
* Contains the metadata sent back from the server.
*/
readonly metadata: FullMetadata;
/**
* The reference that spawned this upload.
*/
readonly ref: StorageReference;
}
/**
* Uploads a string to this object's location.
* The upload is not resumable.
* @public
* @param ref - {@link StorageReference} where string should be uploaded.
* @param value - The string to upload.
* @param format - The format of the string to upload.
* @param metadata - Metadata for the string to upload.
* @returns A Promise containing an UploadResult
*/
export declare function uploadString(
ref: StorageReference,
value: string,
format?: StringFormat,
metadata?: UploadMetadata
): Promise<UploadResult>;
/**
* Represents the process of uploading an object. Allows you to monitor and
* manage the upload.
* @public
*/
export declare interface UploadTask {
/**
* Cancels a running task. Has no effect on a complete or failed task.
* @returns True if the cancel had an effect.
*/
cancel(): boolean;
/**
* Equivalent to calling `then(null, onRejected)`.
*/
catch(onRejected: (error: StorageError) => unknown): Promise<unknown>;
/**
* Listens for events on this task.
*
* Events have three callback functions (referred to as `next`, `error`, and
* `complete`).
*
* If only the event is passed, a function that can be used to register the
* callbacks is returned. Otherwise, the callbacks are passed after the event.
*
* Callbacks can be passed either as three separate arguments <em>or</em> as the
* `next`, `error`, and `complete` properties of an object. Any of the three
* callbacks is optional, as long as at least one is specified. In addition,
* when you add your callbacks, you get a function back. You can call this
* function to unregister the associated callbacks.
*
* @example **Pass callbacks separately or in an object.**
* ```javascript
* var next = function(snapshot) {};
* var error = function(error) {};
* var complete = function() {};
*
* // The first example.
* uploadTask.on(
* firebase.storage.TaskEvent.STATE_CHANGED,
* next,
* error,
* complete);
*
* // This is equivalent to the first example.
* uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
* 'next': next,
* 'error': error,
* 'complete': complete
* });
*
* // This is equivalent to the first example.
* var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
* subscribe(next, error, complete);
*
* // This is equivalent to the first example.
* var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
* subscribe({
* 'next': next,
* 'error': error,
* 'complete': complete
* });
* ```
*
* @example **Any callback is optional.**
* ```javascript
* // Just listening for completion, this is legal.
* uploadTask.on(
* firebase.storage.TaskEvent.STATE_CHANGED,
* null,
* null,
* function() {
* console.log('upload complete!');
* });
*
* // Just listening for progress/state changes, this is legal.
* uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) {
* var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
* console.log(percent + "% done");
* });
*
* // This is also legal.
* uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
* 'complete': function() {
* console.log('upload complete!');
* }
* });
* ```
*
* @example **Use the returned function to remove callbacks.**
* ```javascript
* var unsubscribe = uploadTask.on(
* firebase.storage.TaskEvent.STATE_CHANGED,
* function(snapshot) {
* var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
* console.log(percent + "% done");
* // Stop after receiving one update.
* unsubscribe();
* });
*
* // This code is equivalent to the above.
* var handle = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
* unsubscribe = handle(function(snapshot) {
* var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
* console.log(percent + "% done");
* // Stop after receiving one update.
* unsubscribe();
* });
* ```
*
* @param event - The type of event to listen for.
* @param nextOrObserver -
* The `next` function, which gets called for each item in
* the event stream, or an observer object with some or all of these three
* properties (`next`, `error`, `complete`).
* @param error - A function that gets called with a `StorageError`
* if the event stream ends due to an error.
* @param completed - A function that gets called if the
* event stream ends normally.
* @returns
* If only the event argument is passed, returns a function you can use to
* add callbacks (see the examples above). If more than just the event
* argument is passed, returns a function you can call to unregister the
* callbacks.
*/
on(
event: TaskEvent,
nextOrObserver?:
| StorageObserver<UploadTaskSnapshot>
| null
| ((snapshot: UploadTaskSnapshot) => unknown),
error?: ((a: StorageError) => unknown) | null,
complete?: Unsubscribe | null
): Unsubscribe | Subscribe<UploadTaskSnapshot>;
/**
* Pauses a currently running task. Has no effect on a paused or failed task.
* @returns True if the operation took effect, false if ignored.
*/
pause(): boolean;
/**
* Resumes a paused task. Has no effect on a currently running or failed task.
* @returns True if the operation took effect, false if ignored.
*/
resume(): boolean;
/**
* A snapshot of the current task state.
*/
snapshot: UploadTaskSnapshot;
/**
* This object behaves like a Promise, and resolves with its snapshot data
* when the upload completes.
* @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
* @param onRejected - The rejection callback.
*/
then(
onFulfilled?: ((snapshot: UploadTaskSnapshot) => unknown) | null,
onRejected?: ((error: StorageError) => unknown) | null
): Promise<unknown>;
}
/* Excluded from this release type: _UploadTask */
/**
* Holds data about the current state of the upload task.
* @public
*/
export declare interface UploadTaskSnapshot {
/**
* The number of bytes that have been successfully uploaded so far.
*/
bytesTransferred: number;
/**
* Before the upload completes, contains the metadata sent to the server.
* After the upload completes, contains the metadata sent back from the server.
*/
metadata: FullMetadata;
/**
* The reference that spawned this snapshot's upload task.
*/
ref: StorageReference;
/**
* The current state of the task.
*/
state: TaskState;
/**
* The task of which this is a snapshot.
*/
task: UploadTask;
/**
* The total number of bytes to be uploaded.
*/
totalBytes: number;
}
export {};
+2 -1
View File
@@ -8,7 +8,8 @@
"target": "es2017",
"esModuleInterop": true,
"declaration": true,
"strict": true
"strict": true,
"sourceMap": true
},
"exclude": ["dist/**/*"]
}
+1 -1
View File
@@ -32,7 +32,7 @@
"child-process-promise": "2.2.1",
"memfs": "3.5.3",
"tmp": "0.2.1",
"typescript": "4.7.4",
"typescript": "5.5.4",
"terser": "5.16.1",
"yargs": "17.7.2",
"@firebase/util": "1.10.1",

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