link
This commit is contained in:
21
node_modules/firebase-functions/LICENSE
generated
vendored
Normal file
21
node_modules/firebase-functions/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 Firebase
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
42
node_modules/firebase-functions/README.md
generated
vendored
Normal file
42
node_modules/firebase-functions/README.md
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
# Firebase SDK for Cloud Functions
|
||||
|
||||
The `firebase-functions` package provides an SDK for defining Cloud Functions for Firebase.
|
||||
|
||||
Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. The Firebase SDK for Cloud Functions integrates the Firebase platform by letting you write code that responds to events and invokes functionality exposed by other Firebase features.
|
||||
|
||||
## Learn more
|
||||
|
||||
Learn more about the Firebase SDK for Cloud Functions in the [Firebase documentation](https://firebase.google.com/docs/functions/) or [check out our samples](https://github.com/firebase/functions-samples).
|
||||
|
||||
Here are some resources to get help:
|
||||
|
||||
- Start with the quickstart: https://firebase.google.com/docs/functions/write-firebase-functions
|
||||
- Go through the guide: https://firebase.google.com/docs/functions/
|
||||
- Read the full API reference: https://firebase.google.com/docs/reference/functions/
|
||||
- Browse some examples: https://github.com/firebase/functions-samples
|
||||
|
||||
If the official documentation doesn't help, try asking through our official support channels: https://firebase.google.com/support/
|
||||
|
||||
_Please avoid double posting across multiple channels!_
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
// functions/index.js
|
||||
const { onValueCreated } = require("firebase-functions/database");
|
||||
const logger = require("firebase-functions/logger");
|
||||
const notifyUsers = require("./notify-users");
|
||||
|
||||
exports.newPost = onValueCreated({ ref: "/posts/{postId}" }, (event) => {
|
||||
logger.info("Received new post with ID:", event.params.postId);
|
||||
return notifyUsers(event.data.val());
|
||||
});
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
To contribute a change, [check out the contributing guide](.github/CONTRIBUTING.md).
|
||||
|
||||
## License
|
||||
|
||||
© Google, 2017. Licensed under [The MIT License](LICENSE).
|
||||
2
node_modules/firebase-functions/lib/bin/firebase-functions.d.ts
generated
vendored
Normal file
2
node_modules/firebase-functions/lib/bin/firebase-functions.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
71
node_modules/firebase-functions/lib/bin/firebase-functions.js
generated
vendored
Executable file
71
node_modules/firebase-functions/lib/bin/firebase-functions.js
generated
vendored
Executable file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express = require("express");
|
||||
const loader_1 = require("../runtime/loader");
|
||||
const manifest_1 = require("../runtime/manifest");
|
||||
function printUsageAndExit() {
|
||||
console.error(`
|
||||
Usage: firebase-functions [functionsDir]
|
||||
|
||||
Arguments:
|
||||
- functionsDir: Directory containing source code for Firebase Functions.
|
||||
`);
|
||||
process.exit(1);
|
||||
}
|
||||
let functionsDir = ".";
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length > 1) {
|
||||
if (args[0] === "-h" || args[0] === "--help") {
|
||||
printUsageAndExit();
|
||||
}
|
||||
functionsDir = args[0];
|
||||
}
|
||||
let server = undefined;
|
||||
const app = express();
|
||||
function handleQuitquitquit(req, res) {
|
||||
res.send("ok");
|
||||
server.close();
|
||||
}
|
||||
app.get("/__/quitquitquit", handleQuitquitquit);
|
||||
app.post("/__/quitquitquit", handleQuitquitquit);
|
||||
if (process.env.FUNCTIONS_CONTROL_API === "true") {
|
||||
app.get("/__/functions.yaml", async (req, res) => {
|
||||
try {
|
||||
const stack = await (0, loader_1.loadStack)(functionsDir);
|
||||
res.setHeader("content-type", "text/yaml");
|
||||
res.send(JSON.stringify((0, manifest_1.stackToWire)(stack)));
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e);
|
||||
res.status(400).send(`Failed to generate manifest from function source: ${e}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
let port = 8080;
|
||||
if (process.env.PORT) {
|
||||
port = Number.parseInt(process.env.PORT);
|
||||
}
|
||||
console.log("Serving at port", port);
|
||||
server = app.listen(port);
|
||||
14
node_modules/firebase-functions/lib/common/app.d.ts
generated
vendored
Normal file
14
node_modules/firebase-functions/lib/common/app.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
import { App } from "firebase-admin/app";
|
||||
export declare function getApp(): App;
|
||||
/**
|
||||
* This function allows the Firebase Emulator Suite to override the FirebaseApp instance
|
||||
* used by the Firebase Functions SDK. Developers should never call this function for
|
||||
* other purposes.
|
||||
* N.B. For clarity for use in testing this name has no mention of emulation, but
|
||||
* it must be exported from index as app.setEmulatedAdminApp or we break the emulator.
|
||||
* We can remove this export when:
|
||||
* A) We complete the new emulator and no longer depend on monkeypatching
|
||||
* B) We tweak the CLI to look for different APIs to monkeypatch depending on versions.
|
||||
* @alpha
|
||||
*/
|
||||
export declare function setApp(app?: App): void;
|
||||
62
node_modules/firebase-functions/lib/common/app.js
generated
vendored
Normal file
62
node_modules/firebase-functions/lib/common/app.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.setApp = exports.getApp = void 0;
|
||||
const app_1 = require("firebase-admin/app");
|
||||
const config_1 = require("./config");
|
||||
const APP_NAME = "__FIREBASE_FUNCTIONS_SDK__";
|
||||
let cache;
|
||||
function getApp() {
|
||||
if (typeof cache === "undefined") {
|
||||
try {
|
||||
cache = (0, app_1.getApp)( /* default */);
|
||||
}
|
||||
catch {
|
||||
// Default app does not exist. Initialize app.
|
||||
cache = (0, app_1.initializeApp)({
|
||||
...(0, config_1.firebaseConfig)(),
|
||||
credential: (0, app_1.applicationDefault)(),
|
||||
}, APP_NAME);
|
||||
}
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
exports.getApp = getApp;
|
||||
/**
|
||||
* This function allows the Firebase Emulator Suite to override the FirebaseApp instance
|
||||
* used by the Firebase Functions SDK. Developers should never call this function for
|
||||
* other purposes.
|
||||
* N.B. For clarity for use in testing this name has no mention of emulation, but
|
||||
* it must be exported from index as app.setEmulatedAdminApp or we break the emulator.
|
||||
* We can remove this export when:
|
||||
* A) We complete the new emulator and no longer depend on monkeypatching
|
||||
* B) We tweak the CLI to look for different APIs to monkeypatch depending on versions.
|
||||
* @alpha
|
||||
*/
|
||||
function setApp(app) {
|
||||
if ((cache === null || cache === void 0 ? void 0 : cache.name) === APP_NAME) {
|
||||
void (0, app_1.deleteApp)(cache);
|
||||
}
|
||||
cache = app;
|
||||
}
|
||||
exports.setApp = setApp;
|
||||
41
node_modules/firebase-functions/lib/common/change.d.ts
generated
vendored
Normal file
41
node_modules/firebase-functions/lib/common/change.d.ts
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* `ChangeJson` is the JSON format used to construct a `Change` object.
|
||||
*/
|
||||
export interface ChangeJson {
|
||||
/**
|
||||
* Key-value pairs representing state of data after the change.
|
||||
*/
|
||||
after?: any;
|
||||
/**
|
||||
* Key-value pairs representing state of data before the change. If
|
||||
* `fieldMask` is set, then only fields that changed are present in `before`.
|
||||
*/
|
||||
before?: any;
|
||||
/**
|
||||
* Comma-separated string that represents names of fields that changed.
|
||||
*/
|
||||
fieldMask?: string;
|
||||
}
|
||||
/**
|
||||
* The Cloud Functions interface for events that change state, such as
|
||||
* Realtime Database or Cloud Firestore `onWrite` and `onUpdate` events.
|
||||
*
|
||||
* For more information about the format used to construct `Change` objects, see
|
||||
* {@link ChangeJson} below.
|
||||
*
|
||||
*/
|
||||
export declare class Change<T> {
|
||||
before: T;
|
||||
after: T;
|
||||
/**
|
||||
* Factory method for creating a `Change` from a `before` object and an `after`
|
||||
* object.
|
||||
*/
|
||||
static fromObjects<T>(before: T, after: T): Change<T>;
|
||||
/**
|
||||
* Factory method for creating a `Change` from JSON and an optional customizer
|
||||
* function to be applied to both the `before` and the `after` fields.
|
||||
*/
|
||||
static fromJSON<T>(json: ChangeJson, customizer?: (x: any) => T): Change<T>;
|
||||
constructor(before: T, after: T);
|
||||
}
|
||||
80
node_modules/firebase-functions/lib/common/change.js
generated
vendored
Normal file
80
node_modules/firebase-functions/lib/common/change.js
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Change = exports.applyFieldMask = void 0;
|
||||
/** @internal */
|
||||
function applyFieldMask(sparseBefore, after, fieldMask) {
|
||||
const before = { ...after };
|
||||
const masks = fieldMask.split(",");
|
||||
for (const mask of masks) {
|
||||
const parts = mask.split(".");
|
||||
const head = parts[0];
|
||||
const tail = parts.slice(1).join(".");
|
||||
if (parts.length > 1) {
|
||||
before[head] = applyFieldMask(sparseBefore === null || sparseBefore === void 0 ? void 0 : sparseBefore[head], after[head], tail);
|
||||
continue;
|
||||
}
|
||||
const val = sparseBefore === null || sparseBefore === void 0 ? void 0 : sparseBefore[head];
|
||||
if (typeof val === "undefined") {
|
||||
delete before[mask];
|
||||
}
|
||||
else {
|
||||
before[mask] = val;
|
||||
}
|
||||
}
|
||||
return before;
|
||||
}
|
||||
exports.applyFieldMask = applyFieldMask;
|
||||
/**
|
||||
* The Cloud Functions interface for events that change state, such as
|
||||
* Realtime Database or Cloud Firestore `onWrite` and `onUpdate` events.
|
||||
*
|
||||
* For more information about the format used to construct `Change` objects, see
|
||||
* {@link ChangeJson} below.
|
||||
*
|
||||
*/
|
||||
class Change {
|
||||
/**
|
||||
* Factory method for creating a `Change` from a `before` object and an `after`
|
||||
* object.
|
||||
*/
|
||||
static fromObjects(before, after) {
|
||||
return new Change(before, after);
|
||||
}
|
||||
/**
|
||||
* Factory method for creating a `Change` from JSON and an optional customizer
|
||||
* function to be applied to both the `before` and the `after` fields.
|
||||
*/
|
||||
static fromJSON(json, customizer = (x) => x) {
|
||||
let before = { ...json.before };
|
||||
if (json.fieldMask) {
|
||||
before = applyFieldMask(before, json.after, json.fieldMask);
|
||||
}
|
||||
return Change.fromObjects(customizer(before || {}), customizer(json.after || {}));
|
||||
}
|
||||
constructor(before, after) {
|
||||
this.before = before;
|
||||
this.after = after;
|
||||
}
|
||||
}
|
||||
exports.Change = Change;
|
||||
6
node_modules/firebase-functions/lib/common/config.d.ts
generated
vendored
Normal file
6
node_modules/firebase-functions/lib/common/config.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import { AppOptions } from "firebase-admin/app";
|
||||
/**
|
||||
* Get the fields you need to initialize a Firebase app
|
||||
* @alpha
|
||||
*/
|
||||
export declare function firebaseConfig(): AppOptions | null;
|
||||
49
node_modules/firebase-functions/lib/common/config.js
generated
vendored
Normal file
49
node_modules/firebase-functions/lib/common/config.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.firebaseConfig = exports.resetCache = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const path = require("path");
|
||||
const logger = require("../logger");
|
||||
let cache = null;
|
||||
/**
|
||||
* @internal
|
||||
* @alpha
|
||||
*/
|
||||
function resetCache(newCache = null) {
|
||||
cache = newCache;
|
||||
}
|
||||
exports.resetCache = resetCache;
|
||||
/**
|
||||
* Get the fields you need to initialize a Firebase app
|
||||
* @alpha
|
||||
*/
|
||||
function firebaseConfig() {
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
let env = process.env.FIREBASE_CONFIG;
|
||||
if (env) {
|
||||
// Firebase Tools will always use a JSON blob in prod, but docs
|
||||
// explicitly state that the user can set the env to a file:
|
||||
// https://firebase.google.com/docs/admin/setup#initialize-without-parameters
|
||||
if (!env.startsWith("{")) {
|
||||
env = (0, fs_1.readFileSync)(path.join(process.env.PWD, env)).toString("utf8");
|
||||
}
|
||||
cache = JSON.parse(env);
|
||||
return cache;
|
||||
}
|
||||
if (process.env.GCLOUD_PROJECT) {
|
||||
logger.warn("Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail");
|
||||
cache = {
|
||||
databaseURL: process.env.DATABASE_URL || `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
|
||||
storageBucket: process.env.STORAGE_BUCKET_URL || `${process.env.GCLOUD_PROJECT}.appspot.com`,
|
||||
projectId: process.env.GCLOUD_PROJECT,
|
||||
};
|
||||
return cache;
|
||||
}
|
||||
else {
|
||||
logger.warn("Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
exports.firebaseConfig = firebaseConfig;
|
||||
1
node_modules/firebase-functions/lib/common/debug.d.ts
generated
vendored
Normal file
1
node_modules/firebase-functions/lib/common/debug.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
54
node_modules/firebase-functions/lib/common/debug.js
generated
vendored
Normal file
54
node_modules/firebase-functions/lib/common/debug.js
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isDebugFeatureEnabled = exports.debugFeatureValue = void 0;
|
||||
// Do NOT turn on a debug feature in production.
|
||||
const debugMode = process.env.FIREBASE_DEBUG_MODE === "true";
|
||||
function loadDebugFeatures() {
|
||||
if (!debugMode) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
const obj = JSON.parse(process.env.FIREBASE_DEBUG_FEATURES);
|
||||
if (typeof obj !== "object") {
|
||||
return {};
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
/* @internal */
|
||||
function debugFeatureValue(feat) {
|
||||
if (!debugMode) {
|
||||
return;
|
||||
}
|
||||
return loadDebugFeatures()[feat];
|
||||
}
|
||||
exports.debugFeatureValue = debugFeatureValue;
|
||||
/* @internal */
|
||||
function isDebugFeatureEnabled(feat) {
|
||||
return debugMode && !!debugFeatureValue(feat);
|
||||
}
|
||||
exports.isDebugFeatureEnabled = isDebugFeatureEnabled;
|
||||
17
node_modules/firebase-functions/lib/common/encoding.d.ts
generated
vendored
Normal file
17
node_modules/firebase-functions/lib/common/encoding.d.ts
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Expression } from "../params";
|
||||
/**
|
||||
* A type alias used to annotate interfaces as using a google.protobuf.Duration.
|
||||
* This type is parsed/encoded as a string of seconds + the "s" prefix.
|
||||
*/
|
||||
export type Duration = string;
|
||||
/** Get a google.protobuf.Duration for a number of seconds. */
|
||||
export declare function durationFromSeconds(s: number): Duration;
|
||||
/**
|
||||
* Utility function to help copy fields from type A to B.
|
||||
* As a safety net, catches typos or fields that aren't named the same
|
||||
* in A and B, but cannot verify that both Src and Dest have the same type for the same field.
|
||||
*/
|
||||
export declare function copyIfPresent<Src, Dest>(dest: Dest, src: Src, ...fields: Array<keyof Src & keyof Dest>): void;
|
||||
export declare function convertIfPresent<Src, Dest>(dest: Dest, src: Src, destField: keyof Dest, srcField: keyof Src, converter?: (from: any) => any): void;
|
||||
export declare function serviceAccountFromShorthand(serviceAccount: string | Expression<string>): string | Expression<string> | null;
|
||||
export declare function convertInvoker(invoker: string | string[]): string[];
|
||||
96
node_modules/firebase-functions/lib/common/encoding.js
generated
vendored
Normal file
96
node_modules/firebase-functions/lib/common/encoding.js
generated
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.convertInvoker = exports.serviceAccountFromShorthand = exports.convertIfPresent = exports.copyIfPresent = exports.durationFromSeconds = void 0;
|
||||
const params_1 = require("../params");
|
||||
/** Get a google.protobuf.Duration for a number of seconds. */
|
||||
function durationFromSeconds(s) {
|
||||
return `${s}s`;
|
||||
}
|
||||
exports.durationFromSeconds = durationFromSeconds;
|
||||
/**
|
||||
* Utility function to help copy fields from type A to B.
|
||||
* As a safety net, catches typos or fields that aren't named the same
|
||||
* in A and B, but cannot verify that both Src and Dest have the same type for the same field.
|
||||
*/
|
||||
function copyIfPresent(dest, src, ...fields) {
|
||||
if (!src) {
|
||||
return;
|
||||
}
|
||||
for (const field of fields) {
|
||||
if (!Object.prototype.hasOwnProperty.call(src, field)) {
|
||||
continue;
|
||||
}
|
||||
dest[field] = src[field];
|
||||
}
|
||||
}
|
||||
exports.copyIfPresent = copyIfPresent;
|
||||
function convertIfPresent(dest, src, destField, srcField, converter = (from) => {
|
||||
return from;
|
||||
}) {
|
||||
if (!src) {
|
||||
return;
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(src, srcField)) {
|
||||
return;
|
||||
}
|
||||
dest[destField] = converter(src[srcField]);
|
||||
}
|
||||
exports.convertIfPresent = convertIfPresent;
|
||||
function serviceAccountFromShorthand(serviceAccount) {
|
||||
if (serviceAccount === "default") {
|
||||
return null;
|
||||
}
|
||||
else if (serviceAccount instanceof params_1.Expression) {
|
||||
return serviceAccount;
|
||||
}
|
||||
else if (serviceAccount.endsWith("@")) {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error(`Unable to determine email for service account '${serviceAccount}' because process.env.GCLOUD_PROJECT is not set.`);
|
||||
}
|
||||
return `${serviceAccount}${process.env.GCLOUD_PROJECT}.iam.gserviceaccount.com`;
|
||||
}
|
||||
else if (serviceAccount.includes("@")) {
|
||||
return serviceAccount;
|
||||
}
|
||||
else {
|
||||
throw new Error(`Invalid option for serviceAccount: '${serviceAccount}'. Valid options are 'default', a service account email, or '{serviceAccountName}@'`);
|
||||
}
|
||||
}
|
||||
exports.serviceAccountFromShorthand = serviceAccountFromShorthand;
|
||||
function convertInvoker(invoker) {
|
||||
if (typeof invoker === "string") {
|
||||
invoker = [invoker];
|
||||
}
|
||||
if (invoker.length === 0) {
|
||||
throw new Error("Invalid option for invoker: Must be a non-empty array.");
|
||||
}
|
||||
if (invoker.find((inv) => inv.length === 0)) {
|
||||
throw new Error("Invalid option for invoker: Must be a non-empty string.");
|
||||
}
|
||||
if (invoker.length > 1 && invoker.find((inv) => inv === "public" || inv === "private")) {
|
||||
throw new Error("Invalid option for invoker: Cannot have 'public' or 'private' in an array of service accounts.");
|
||||
}
|
||||
return invoker;
|
||||
}
|
||||
exports.convertInvoker = convertInvoker;
|
||||
7
node_modules/firebase-functions/lib/common/onInit.d.ts
generated
vendored
Normal file
7
node_modules/firebase-functions/lib/common/onInit.d.ts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Registers a callback that should be run when in a production environment
|
||||
* before executing any functions code.
|
||||
* Calling this function more than once leads to undefined behavior.
|
||||
* @param callback initialization callback to be run before any function executes.
|
||||
*/
|
||||
export declare function onInit(callback: () => unknown): void;
|
||||
36
node_modules/firebase-functions/lib/common/onInit.js
generated
vendored
Normal file
36
node_modules/firebase-functions/lib/common/onInit.js
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.withInit = exports.onInit = void 0;
|
||||
const logger = require("../logger");
|
||||
let initCallback = null;
|
||||
let didInit = false;
|
||||
/**
|
||||
* Registers a callback that should be run when in a production environment
|
||||
* before executing any functions code.
|
||||
* Calling this function more than once leads to undefined behavior.
|
||||
* @param callback initialization callback to be run before any function executes.
|
||||
*/
|
||||
function onInit(callback) {
|
||||
if (initCallback) {
|
||||
logger.warn("Setting onInit callback more than once. Only the most recent callback will be called");
|
||||
}
|
||||
initCallback = callback;
|
||||
didInit = false;
|
||||
}
|
||||
exports.onInit = onInit;
|
||||
/** @internal */
|
||||
function withInit(func) {
|
||||
return async (...args) => {
|
||||
if (!didInit) {
|
||||
if (initCallback) {
|
||||
await initCallback();
|
||||
}
|
||||
didInit = true;
|
||||
}
|
||||
// Note: This cast is actually inaccurate because it may be a promise, but
|
||||
// it doesn't actually matter because the async function will promisify
|
||||
// non-promises and forward promises.
|
||||
return func(...args);
|
||||
};
|
||||
}
|
||||
exports.withInit = withInit;
|
||||
14
node_modules/firebase-functions/lib/common/options.d.ts
generated
vendored
Normal file
14
node_modules/firebase-functions/lib/common/options.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Special configuration type to reset configuration to platform default.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export declare class ResetValue {
|
||||
toJSON(): null;
|
||||
private constructor();
|
||||
static getInstance(): ResetValue;
|
||||
}
|
||||
/**
|
||||
* Special configuration value to reset configuration to platform default.
|
||||
*/
|
||||
export declare const RESET_VALUE: ResetValue;
|
||||
44
node_modules/firebase-functions/lib/common/options.js
generated
vendored
Normal file
44
node_modules/firebase-functions/lib/common/options.js
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.RESET_VALUE = exports.ResetValue = void 0;
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
/**
|
||||
* Special configuration type to reset configuration to platform default.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
class ResetValue {
|
||||
toJSON() {
|
||||
return null;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
constructor() { }
|
||||
static getInstance() {
|
||||
return new ResetValue();
|
||||
}
|
||||
}
|
||||
exports.ResetValue = ResetValue;
|
||||
/**
|
||||
* Special configuration value to reset configuration to platform default.
|
||||
*/
|
||||
exports.RESET_VALUE = ResetValue.getInstance();
|
||||
33
node_modules/firebase-functions/lib/common/params.d.ts
generated
vendored
Normal file
33
node_modules/firebase-functions/lib/common/params.d.ts
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Expression } from "../params";
|
||||
/**
|
||||
* A type that splits literal string S with delimiter D.
|
||||
*
|
||||
* For example Split<"a/b/c", "/"> is ['a' | "b" | "c"]
|
||||
*/
|
||||
export type Split<S extends string, D extends string> = string extends S ? string[] : S extends "" ? [] : S extends `${D}${infer Tail}` ? [...Split<Tail, D>] : S extends `${infer Head}${D}${infer Tail}` ? string extends Head ? [...Split<Tail, D>] : [Head, ...Split<Tail, D>] : [
|
||||
S
|
||||
];
|
||||
/**
|
||||
* A type that ensure that type S is not null or undefined.
|
||||
*/
|
||||
export type NullSafe<S extends null | undefined | string> = S extends null ? never : S extends undefined ? never : S extends string ? S : never;
|
||||
/**
|
||||
* A type that extracts parameter name enclosed in bracket as string.
|
||||
* Ignore wildcard matches
|
||||
*
|
||||
* For example, Extract<"{uid}"> is "uid".
|
||||
* For example, Extract<"{uid=*}"> is "uid".
|
||||
* For example, Extract<"{uid=**}"> is "uid".
|
||||
*/
|
||||
export type Extract<Part extends string> = Part extends `{${infer Param}=**}` ? Param : Part extends `{${infer Param}=*}` ? Param : Part extends `{${infer Param}}` ? Param : never;
|
||||
/**
|
||||
* A type that maps all parameter capture gropus into keys of a record.
|
||||
* For example, ParamsOf<"users/{uid}"> is { uid: string }
|
||||
* ParamsOf<"users/{uid}/logs/{log}"> is { uid: string; log: string }
|
||||
* ParamsOf<"some/static/data"> is {}
|
||||
*
|
||||
* For flexibility reasons, ParamsOf<string> is Record<string, string>
|
||||
*/
|
||||
export type ParamsOf<PathPattern extends string | Expression<string>> = PathPattern extends Expression<string> ? Record<string, string> : string extends PathPattern ? Record<string, string> : {
|
||||
[Key in Extract<Split<NullSafe<Exclude<PathPattern, Expression<string>>>, "/">[number]>]: string;
|
||||
};
|
||||
23
node_modules/firebase-functions/lib/common/params.js
generated
vendored
Normal file
23
node_modules/firebase-functions/lib/common/params.js
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
151
node_modules/firebase-functions/lib/common/providers/database.d.ts
generated
vendored
Normal file
151
node_modules/firebase-functions/lib/common/providers/database.d.ts
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
import { App } from "firebase-admin/app";
|
||||
import * as database from "firebase-admin/database";
|
||||
/**
|
||||
* Pulled from @firebase/database-types, make sure the interface is updated on dependencies upgrades.
|
||||
* Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.
|
||||
*/
|
||||
interface IteratedDataSnapshot extends DataSnapshot {
|
||||
key: string;
|
||||
}
|
||||
/**
|
||||
* Interface representing a Firebase Realtime database data snapshot.
|
||||
*/
|
||||
export declare class DataSnapshot implements database.DataSnapshot {
|
||||
private app?;
|
||||
instance: string;
|
||||
/** @hidden */
|
||||
private _ref;
|
||||
/** @hidden */
|
||||
private _path;
|
||||
/** @hidden */
|
||||
private _data;
|
||||
/** @hidden */
|
||||
private _childPath;
|
||||
constructor(data: any, path?: string, // path is undefined for the database root
|
||||
app?: App, instance?: string);
|
||||
/**
|
||||
* Returns a [`Reference`](/docs/reference/admin/node/admin.database.Reference)
|
||||
* to the database location where the triggering write occurred. Has
|
||||
* full read and write access.
|
||||
*/
|
||||
get ref(): database.Reference;
|
||||
/**
|
||||
* The key (last part of the path) of the location of this `DataSnapshot`.
|
||||
*
|
||||
* The last token in a database location is considered its key. For example,
|
||||
* "ada" is the key for the `/users/ada/` node. Accessing the key on any
|
||||
* `DataSnapshot` returns the key for the location that generated it.
|
||||
* However, accessing the key on the root URL of a database returns `null`.
|
||||
*/
|
||||
get key(): string | null;
|
||||
/**
|
||||
* Extracts a JavaScript value from a `DataSnapshot`.
|
||||
*
|
||||
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
|
||||
* scalar type (string, number, or boolean), an array, or an object. It may also
|
||||
* return `null`, indicating that the `DataSnapshot` is empty (contains no
|
||||
* data).
|
||||
*
|
||||
* @return The snapshot's contents as a JavaScript value (Object,
|
||||
* Array, string, number, boolean, or `null`).
|
||||
*/
|
||||
val(): any;
|
||||
/**
|
||||
* Exports the entire contents of the `DataSnapshot` as a JavaScript object.
|
||||
*
|
||||
* @return The contents of the `DataSnapshot` as a JavaScript value
|
||||
* (Object, Array, string, number, boolean, or `null`).
|
||||
*/
|
||||
exportVal(): any;
|
||||
/**
|
||||
* Gets the priority value of the data in this `DataSnapshot`.
|
||||
*
|
||||
* As an alternative to using priority, applications can order collections by
|
||||
* ordinary properties. See [Sorting and filtering
|
||||
* data](/docs/database/web/lists-of-data#sorting_and_filtering_data).
|
||||
*
|
||||
* @return The priority value of the data.
|
||||
*/
|
||||
getPriority(): string | number | null;
|
||||
/**
|
||||
* Returns `true` if this `DataSnapshot` contains any data. It is slightly more
|
||||
* efficient than using `snapshot.val() !== null`.
|
||||
*
|
||||
* @return `true` if this `DataSnapshot` contains any data; otherwise, `false`.
|
||||
*/
|
||||
exists(): boolean;
|
||||
/**
|
||||
* Gets a `DataSnapshot` for the location at the specified relative path.
|
||||
*
|
||||
* The relative path can either be a simple child name (for example, "ada") or
|
||||
* a deeper slash-separated path (for example, "ada/name/first").
|
||||
*
|
||||
* @param path A relative path from this location to the desired child
|
||||
* location.
|
||||
* @return The specified child location.
|
||||
*/
|
||||
child(childPath: string): DataSnapshot;
|
||||
/**
|
||||
* Enumerates the `DataSnapshot`s of the children items.
|
||||
*
|
||||
* Because of the way JavaScript objects work, the ordering of data in the
|
||||
* JavaScript object returned by `val()` is not guaranteed to match the ordering
|
||||
* on the server nor the ordering of `child_added` events. That is where
|
||||
* `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
|
||||
* can be iterated in their query order.
|
||||
*
|
||||
* If no explicit `orderBy*()` method is used, results are returned
|
||||
* ordered by key (unless priorities are used, in which case, results are
|
||||
* returned by priority).
|
||||
*
|
||||
* @param action A function that is called for each child `DataSnapshot`.
|
||||
* The callback can return `true` to cancel further enumeration.
|
||||
*
|
||||
* @return `true` if enumeration was canceled due to your callback
|
||||
* returning `true`.
|
||||
*/
|
||||
forEach(action: (a: IteratedDataSnapshot) => boolean | void): boolean;
|
||||
/**
|
||||
* Returns `true` if the specified child path has (non-`null`) data.
|
||||
*
|
||||
* @param path A relative path to the location of a potential child.
|
||||
* @return `true` if data exists at the specified child path; otherwise,
|
||||
* `false`.
|
||||
*/
|
||||
hasChild(childPath: string): boolean;
|
||||
/**
|
||||
* Returns whether or not the `DataSnapshot` has any non-`null` child
|
||||
* properties.
|
||||
*
|
||||
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
|
||||
* children. If it does, you can enumerate them using `forEach()`. If it
|
||||
* doesn't, then either this snapshot contains a primitive value (which can be
|
||||
* retrieved with `val()`) or it is empty (in which case, `val()` returns
|
||||
* `null`).
|
||||
*
|
||||
* @return `true` if this snapshot has any children; else `false`.
|
||||
*/
|
||||
hasChildren(): boolean;
|
||||
/**
|
||||
* Returns the number of child properties of this `DataSnapshot`.
|
||||
*
|
||||
* @return Number of child properties of this `DataSnapshot`.
|
||||
*/
|
||||
numChildren(): number;
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*
|
||||
* @return A JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON(): Record<string, unknown>;
|
||||
/** Recursive function to check if keys are numeric & convert node object to array if they are
|
||||
*
|
||||
* @hidden
|
||||
*/
|
||||
private _checkAndConvertToArray;
|
||||
/** @hidden */
|
||||
private _dup;
|
||||
/** @hidden */
|
||||
private _fullPath;
|
||||
}
|
||||
export {};
|
||||
298
node_modules/firebase-functions/lib/common/providers/database.js
generated
vendored
Normal file
298
node_modules/firebase-functions/lib/common/providers/database.js
generated
vendored
Normal file
@@ -0,0 +1,298 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DataSnapshot = void 0;
|
||||
const database = require("firebase-admin/database");
|
||||
const config_1 = require("../../common/config");
|
||||
const path_1 = require("../../common/utilities/path");
|
||||
/**
|
||||
* Interface representing a Firebase Realtime database data snapshot.
|
||||
*/
|
||||
class DataSnapshot {
|
||||
constructor(data, path, // path is undefined for the database root
|
||||
app, instance) {
|
||||
this.app = app;
|
||||
const config = (0, config_1.firebaseConfig)();
|
||||
if (instance) {
|
||||
// SDK always supplies instance, but user's unit tests may not
|
||||
this.instance = instance;
|
||||
}
|
||||
else if (app) {
|
||||
this.instance = app.options.databaseURL;
|
||||
}
|
||||
else if (config.databaseURL) {
|
||||
this.instance = config.databaseURL;
|
||||
}
|
||||
else if (process.env.GCLOUD_PROJECT) {
|
||||
this.instance = "https://" + process.env.GCLOUD_PROJECT + "-default-rtdb.firebaseio.com";
|
||||
}
|
||||
this._path = path;
|
||||
this._data = data;
|
||||
}
|
||||
/**
|
||||
* Returns a [`Reference`](/docs/reference/admin/node/admin.database.Reference)
|
||||
* to the database location where the triggering write occurred. Has
|
||||
* full read and write access.
|
||||
*/
|
||||
get ref() {
|
||||
if (!this.app) {
|
||||
// may be unpopulated in user's unit tests
|
||||
throw new Error("Please supply a Firebase app in the constructor for DataSnapshot" +
|
||||
" in order to use the .ref method.");
|
||||
}
|
||||
if (!this._ref) {
|
||||
let db;
|
||||
if (this.instance) {
|
||||
db = database.getDatabaseWithUrl(this.instance, this.app);
|
||||
}
|
||||
else {
|
||||
db = database.getDatabase(this.app);
|
||||
}
|
||||
this._ref = db.ref(this._fullPath());
|
||||
}
|
||||
return this._ref;
|
||||
}
|
||||
/**
|
||||
* The key (last part of the path) of the location of this `DataSnapshot`.
|
||||
*
|
||||
* The last token in a database location is considered its key. For example,
|
||||
* "ada" is the key for the `/users/ada/` node. Accessing the key on any
|
||||
* `DataSnapshot` returns the key for the location that generated it.
|
||||
* However, accessing the key on the root URL of a database returns `null`.
|
||||
*/
|
||||
get key() {
|
||||
const segments = (0, path_1.pathParts)(this._fullPath());
|
||||
const last = segments[segments.length - 1];
|
||||
return !last || last === "" ? null : last;
|
||||
}
|
||||
/**
|
||||
* Extracts a JavaScript value from a `DataSnapshot`.
|
||||
*
|
||||
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
|
||||
* scalar type (string, number, or boolean), an array, or an object. It may also
|
||||
* return `null`, indicating that the `DataSnapshot` is empty (contains no
|
||||
* data).
|
||||
*
|
||||
* @return The snapshot's contents as a JavaScript value (Object,
|
||||
* Array, string, number, boolean, or `null`).
|
||||
*/
|
||||
val() {
|
||||
const parts = (0, path_1.pathParts)(this._childPath);
|
||||
let source = this._data;
|
||||
if (parts.length) {
|
||||
for (const part of parts) {
|
||||
if (source[part] === undefined) {
|
||||
return null;
|
||||
}
|
||||
source = source[part];
|
||||
}
|
||||
}
|
||||
const node = source !== null && source !== void 0 ? source : null;
|
||||
return this._checkAndConvertToArray(node);
|
||||
}
|
||||
/**
|
||||
* Exports the entire contents of the `DataSnapshot` as a JavaScript object.
|
||||
*
|
||||
* @return The contents of the `DataSnapshot` as a JavaScript value
|
||||
* (Object, Array, string, number, boolean, or `null`).
|
||||
*/
|
||||
exportVal() {
|
||||
return this.val();
|
||||
}
|
||||
/**
|
||||
* Gets the priority value of the data in this `DataSnapshot`.
|
||||
*
|
||||
* As an alternative to using priority, applications can order collections by
|
||||
* ordinary properties. See [Sorting and filtering
|
||||
* data](/docs/database/web/lists-of-data#sorting_and_filtering_data).
|
||||
*
|
||||
* @return The priority value of the data.
|
||||
*/
|
||||
getPriority() {
|
||||
return 0;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if this `DataSnapshot` contains any data. It is slightly more
|
||||
* efficient than using `snapshot.val() !== null`.
|
||||
*
|
||||
* @return `true` if this `DataSnapshot` contains any data; otherwise, `false`.
|
||||
*/
|
||||
exists() {
|
||||
const val = this.val();
|
||||
if (typeof val === "undefined" || val === null) {
|
||||
return false;
|
||||
}
|
||||
if (typeof val === "object" && Object.keys(val).length === 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Gets a `DataSnapshot` for the location at the specified relative path.
|
||||
*
|
||||
* The relative path can either be a simple child name (for example, "ada") or
|
||||
* a deeper slash-separated path (for example, "ada/name/first").
|
||||
*
|
||||
* @param path A relative path from this location to the desired child
|
||||
* location.
|
||||
* @return The specified child location.
|
||||
*/
|
||||
child(childPath) {
|
||||
if (!childPath) {
|
||||
return this;
|
||||
}
|
||||
return this._dup(childPath);
|
||||
}
|
||||
/**
|
||||
* Enumerates the `DataSnapshot`s of the children items.
|
||||
*
|
||||
* Because of the way JavaScript objects work, the ordering of data in the
|
||||
* JavaScript object returned by `val()` is not guaranteed to match the ordering
|
||||
* on the server nor the ordering of `child_added` events. That is where
|
||||
* `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
|
||||
* can be iterated in their query order.
|
||||
*
|
||||
* If no explicit `orderBy*()` method is used, results are returned
|
||||
* ordered by key (unless priorities are used, in which case, results are
|
||||
* returned by priority).
|
||||
*
|
||||
* @param action A function that is called for each child `DataSnapshot`.
|
||||
* The callback can return `true` to cancel further enumeration.
|
||||
*
|
||||
* @return `true` if enumeration was canceled due to your callback
|
||||
* returning `true`.
|
||||
*/
|
||||
forEach(action) {
|
||||
const val = this.val() || {};
|
||||
if (typeof val === "object") {
|
||||
return Object.keys(val).some((key) => action(this.child(key)) === true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Returns `true` if the specified child path has (non-`null`) data.
|
||||
*
|
||||
* @param path A relative path to the location of a potential child.
|
||||
* @return `true` if data exists at the specified child path; otherwise,
|
||||
* `false`.
|
||||
*/
|
||||
hasChild(childPath) {
|
||||
return this.child(childPath).exists();
|
||||
}
|
||||
/**
|
||||
* Returns whether or not the `DataSnapshot` has any non-`null` child
|
||||
* properties.
|
||||
*
|
||||
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
|
||||
* children. If it does, you can enumerate them using `forEach()`. If it
|
||||
* doesn't, then either this snapshot contains a primitive value (which can be
|
||||
* retrieved with `val()`) or it is empty (in which case, `val()` returns
|
||||
* `null`).
|
||||
*
|
||||
* @return `true` if this snapshot has any children; else `false`.
|
||||
*/
|
||||
hasChildren() {
|
||||
const val = this.val();
|
||||
return val !== null && typeof val === "object" && Object.keys(val).length > 0;
|
||||
}
|
||||
/**
|
||||
* Returns the number of child properties of this `DataSnapshot`.
|
||||
*
|
||||
* @return Number of child properties of this `DataSnapshot`.
|
||||
*/
|
||||
numChildren() {
|
||||
const val = this.val();
|
||||
return val !== null && typeof val === "object" ? Object.keys(val).length : 0;
|
||||
}
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*
|
||||
* @return A JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON() {
|
||||
return this.val();
|
||||
}
|
||||
/** Recursive function to check if keys are numeric & convert node object to array if they are
|
||||
*
|
||||
* @hidden
|
||||
*/
|
||||
_checkAndConvertToArray(node) {
|
||||
if (node === null || typeof node === "undefined") {
|
||||
return null;
|
||||
}
|
||||
if (typeof node !== "object") {
|
||||
return node;
|
||||
}
|
||||
const obj = {};
|
||||
let numKeys = 0;
|
||||
let maxKey = 0;
|
||||
let allIntegerKeys = true;
|
||||
for (const key in node) {
|
||||
if (!node.hasOwnProperty(key)) {
|
||||
continue;
|
||||
}
|
||||
const childNode = node[key];
|
||||
const v = this._checkAndConvertToArray(childNode);
|
||||
if (v === null) {
|
||||
// Empty child node
|
||||
continue;
|
||||
}
|
||||
obj[key] = v;
|
||||
numKeys++;
|
||||
const integerRegExp = /^(0|[1-9]\d*)$/;
|
||||
if (allIntegerKeys && integerRegExp.test(key)) {
|
||||
maxKey = Math.max(maxKey, Number(key));
|
||||
}
|
||||
else {
|
||||
allIntegerKeys = false;
|
||||
}
|
||||
}
|
||||
if (numKeys === 0) {
|
||||
// Empty node
|
||||
return null;
|
||||
}
|
||||
if (allIntegerKeys && maxKey < 2 * numKeys) {
|
||||
// convert to array.
|
||||
const array = [];
|
||||
for (const key of Object.keys(obj)) {
|
||||
array[key] = obj[key];
|
||||
}
|
||||
return array;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
/** @hidden */
|
||||
_dup(childPath) {
|
||||
const dup = new DataSnapshot(this._data, undefined, this.app, this.instance);
|
||||
[dup._path, dup._childPath] = [this._path, this._childPath];
|
||||
if (childPath) {
|
||||
dup._childPath = (0, path_1.joinPath)(dup._childPath, childPath);
|
||||
}
|
||||
return dup;
|
||||
}
|
||||
/** @hidden */
|
||||
_fullPath() {
|
||||
return (this._path || "") + "/" + (this._childPath || "");
|
||||
}
|
||||
}
|
||||
exports.DataSnapshot = DataSnapshot;
|
||||
1
node_modules/firebase-functions/lib/common/providers/firestore.d.ts
generated
vendored
Normal file
1
node_modules/firebase-functions/lib/common/providers/firestore.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
110
node_modules/firebase-functions/lib/common/providers/firestore.js
generated
vendored
Normal file
110
node_modules/firebase-functions/lib/common/providers/firestore.js
generated
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2023 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createBeforeSnapshotFromJson = exports.createSnapshotFromJson = exports.createBeforeSnapshotFromProtobuf = exports.createSnapshotFromProtobuf = void 0;
|
||||
const firestore = require("firebase-admin/firestore");
|
||||
const logger = require("../../logger");
|
||||
const app_1 = require("../../common/app");
|
||||
const compiledFirestore_1 = require("../../../protos/compiledFirestore");
|
||||
const encoder_1 = require("../../common/utilities/encoder");
|
||||
/** static-complied protobufs */
|
||||
const DocumentEventData = compiledFirestore_1.google.events.cloud.firestore.v1.DocumentEventData;
|
||||
let firestoreInstance;
|
||||
/** @hidden */
|
||||
function _getValueProto(data, resource, valueFieldName) {
|
||||
const value = data === null || data === void 0 ? void 0 : data[valueFieldName];
|
||||
if (typeof value === "undefined" ||
|
||||
value === null ||
|
||||
(typeof value === "object" && !Object.keys(value).length)) {
|
||||
// Firestore#snapshot_ takes resource string instead of proto for a non-existent snapshot
|
||||
return resource;
|
||||
}
|
||||
const proto = {
|
||||
fields: (value === null || value === void 0 ? void 0 : value.fields) || {},
|
||||
createTime: (0, encoder_1.dateToTimestampProto)(value === null || value === void 0 ? void 0 : value.createTime),
|
||||
updateTime: (0, encoder_1.dateToTimestampProto)(value === null || value === void 0 ? void 0 : value.updateTime),
|
||||
name: (value === null || value === void 0 ? void 0 : value.name) || resource,
|
||||
};
|
||||
return proto;
|
||||
}
|
||||
/** @internal */
|
||||
function createSnapshotFromProtobuf(data, path, databaseId) {
|
||||
if (!firestoreInstance) {
|
||||
firestoreInstance = firestore.getFirestore((0, app_1.getApp)(), databaseId);
|
||||
}
|
||||
try {
|
||||
const dataBuffer = Buffer.from(data);
|
||||
const firestoreDecoded = DocumentEventData.decode(dataBuffer);
|
||||
return firestoreInstance.snapshot_(firestoreDecoded.value || path, null, "protobufJS");
|
||||
}
|
||||
catch (err) {
|
||||
logger.error("Failed to decode protobuf and create a snapshot.");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
exports.createSnapshotFromProtobuf = createSnapshotFromProtobuf;
|
||||
/** @internal */
|
||||
function createBeforeSnapshotFromProtobuf(data, path, databaseId) {
|
||||
if (!firestoreInstance) {
|
||||
firestoreInstance = firestore.getFirestore((0, app_1.getApp)(), databaseId);
|
||||
}
|
||||
try {
|
||||
const dataBuffer = Buffer.from(data);
|
||||
const firestoreDecoded = DocumentEventData.decode(dataBuffer);
|
||||
return firestoreInstance.snapshot_(firestoreDecoded.oldValue || path, null, "protobufJS");
|
||||
}
|
||||
catch (err) {
|
||||
logger.error("Failed to decode protobuf and create a before snapshot.");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
exports.createBeforeSnapshotFromProtobuf = createBeforeSnapshotFromProtobuf;
|
||||
/** @internal */
|
||||
function createSnapshotFromJson(data, source, createTime, updateTime, databaseId) {
|
||||
if (!firestoreInstance) {
|
||||
firestoreInstance = databaseId
|
||||
? firestore.getFirestore((0, app_1.getApp)(), databaseId)
|
||||
: firestore.getFirestore((0, app_1.getApp)());
|
||||
}
|
||||
const valueProto = _getValueProto(data, source, "value");
|
||||
let timeString = createTime || updateTime;
|
||||
if (!timeString) {
|
||||
logger.warn("Snapshot has no readTime. Using now()");
|
||||
timeString = new Date().toISOString();
|
||||
}
|
||||
const readTime = (0, encoder_1.dateToTimestampProto)(timeString);
|
||||
return firestoreInstance.snapshot_(valueProto, readTime, "json");
|
||||
}
|
||||
exports.createSnapshotFromJson = createSnapshotFromJson;
|
||||
/** @internal */
|
||||
function createBeforeSnapshotFromJson(data, source, createTime, updateTime, databaseId) {
|
||||
if (!firestoreInstance) {
|
||||
firestoreInstance = databaseId
|
||||
? firestore.getFirestore((0, app_1.getApp)(), databaseId)
|
||||
: firestore.getFirestore((0, app_1.getApp)());
|
||||
}
|
||||
const oldValueProto = _getValueProto(data, source, "oldValue");
|
||||
const oldReadTime = (0, encoder_1.dateToTimestampProto)(createTime || updateTime);
|
||||
return firestoreInstance.snapshot_(oldValueProto, oldReadTime, "json");
|
||||
}
|
||||
exports.createBeforeSnapshotFromJson = createBeforeSnapshotFromJson;
|
||||
240
node_modules/firebase-functions/lib/common/providers/https.d.ts
generated
vendored
Normal file
240
node_modules/firebase-functions/lib/common/providers/https.d.ts
generated
vendored
Normal file
@@ -0,0 +1,240 @@
|
||||
/// <reference types="node" />
|
||||
import * as express from "express";
|
||||
import { DecodedAppCheckToken } from "firebase-admin/app-check";
|
||||
import { DecodedIdToken } from "firebase-admin/auth";
|
||||
import { TaskContext } from "./tasks";
|
||||
/** An express request with the wire format representation of the request body. */
|
||||
export interface Request extends express.Request {
|
||||
/** The wire format representation of the request body. */
|
||||
rawBody: Buffer;
|
||||
}
|
||||
/**
|
||||
* The interface for AppCheck tokens verified in Callable functions
|
||||
*/
|
||||
export interface AppCheckData {
|
||||
/**
|
||||
* The app ID of a Firebase App attested by the App Check token.
|
||||
*/
|
||||
appId: string;
|
||||
/**
|
||||
* Decoded App Check token.
|
||||
*/
|
||||
token: DecodedAppCheckToken;
|
||||
/**
|
||||
* Indicates if the token has been consumed.
|
||||
*
|
||||
* @remarks
|
||||
* `false` value indicates that this is the first time the App Check service has seen this token and marked the
|
||||
* token as consumed for future use of the token.
|
||||
*
|
||||
* `true` value indicates the token has previously been marked as consumed by the App Check service. In this case,
|
||||
* consider taking extra precautions, such as rejecting the request or requiring additional security checks.
|
||||
*/
|
||||
alreadyConsumed?: boolean;
|
||||
}
|
||||
/**
|
||||
* The interface for Auth tokens verified in Callable functions
|
||||
*/
|
||||
export interface AuthData {
|
||||
uid: string;
|
||||
token: DecodedIdToken;
|
||||
}
|
||||
/**
|
||||
* The interface for metadata for the API as passed to the handler.
|
||||
*/
|
||||
export interface CallableContext {
|
||||
/**
|
||||
* The result of decoding and verifying a Firebase AppCheck token.
|
||||
*/
|
||||
app?: AppCheckData;
|
||||
/**
|
||||
* The result of decoding and verifying a Firebase Auth ID token.
|
||||
*/
|
||||
auth?: AuthData;
|
||||
/**
|
||||
* An unverified token for a Firebase Instance ID.
|
||||
*/
|
||||
instanceIdToken?: string;
|
||||
/**
|
||||
* The raw request handled by the callable.
|
||||
*/
|
||||
rawRequest: Request;
|
||||
}
|
||||
/**
|
||||
* The request used to call a callable function.
|
||||
*/
|
||||
export interface CallableRequest<T = any> {
|
||||
/**
|
||||
* The parameters used by a client when calling this function.
|
||||
*/
|
||||
data: T;
|
||||
/**
|
||||
* The result of decoding and verifying a Firebase App Check token.
|
||||
*/
|
||||
app?: AppCheckData;
|
||||
/**
|
||||
* The result of decoding and verifying a Firebase Auth ID token.
|
||||
*/
|
||||
auth?: AuthData;
|
||||
/**
|
||||
* An unverified token for a Firebase Instance ID.
|
||||
*/
|
||||
instanceIdToken?: string;
|
||||
/**
|
||||
* The raw request handled by the callable.
|
||||
*/
|
||||
rawRequest: Request;
|
||||
/**
|
||||
* Whether this is a streaming request.
|
||||
* Code can be optimized by not trying to generate a stream of chunks to
|
||||
* call `response.sendChunk` if `request.acceptsStreaming` is false.
|
||||
* It is always safe, however, to call `response.sendChunk` as this will
|
||||
* noop if `acceptsStreaming` is false.
|
||||
*/
|
||||
acceptsStreaming: boolean;
|
||||
}
|
||||
/**
|
||||
* `CallableProxyResponse` allows streaming response chunks and listening to signals
|
||||
* triggered in events such as a disconnect.
|
||||
*/
|
||||
export interface CallableResponse<T = unknown> {
|
||||
/**
|
||||
* Writes a chunk of the response body to the client. This method can be called
|
||||
* multiple times to stream data progressively.
|
||||
* Returns a promise of whether the data was written. This can be false, for example,
|
||||
* if the request was not a streaming request. Rejects if there is a network error.
|
||||
*/
|
||||
sendChunk: (chunk: T) => Promise<boolean>;
|
||||
/**
|
||||
* An `AbortSignal` that is triggered when the client disconnects or the
|
||||
* request is terminated prematurely.
|
||||
*/
|
||||
signal: AbortSignal;
|
||||
}
|
||||
/**
|
||||
* The set of Firebase Functions status codes. The codes are the same at the
|
||||
* ones exposed by {@link https://github.com/grpc/grpc/blob/master/doc/statuscodes.md | gRPC}.
|
||||
*
|
||||
* @remarks
|
||||
* Possible values:
|
||||
*
|
||||
* - `cancelled`: The operation was cancelled (typically by the caller).
|
||||
*
|
||||
* - `unknown`: Unknown error or an error from a different error domain.
|
||||
*
|
||||
* - `invalid-argument`: Client specified an invalid argument. Note that this
|
||||
* differs from `failed-precondition`. `invalid-argument` indicates
|
||||
* arguments that are problematic regardless of the state of the system
|
||||
* (e.g. an invalid field name).
|
||||
*
|
||||
* - `deadline-exceeded`: Deadline expired before operation could complete.
|
||||
* For operations that change the state of the system, this error may be
|
||||
* returned even if the operation has completed successfully. For example,
|
||||
* a successful response from a server could have been delayed long enough
|
||||
* for the deadline to expire.
|
||||
*
|
||||
* - `not-found`: Some requested document was not found.
|
||||
*
|
||||
* - `already-exists`: Some document that we attempted to create already
|
||||
* exists.
|
||||
*
|
||||
* - `permission-denied`: The caller does not have permission to execute the
|
||||
* specified operation.
|
||||
*
|
||||
* - `resource-exhausted`: Some resource has been exhausted, perhaps a
|
||||
* per-user quota, or perhaps the entire file system is out of space.
|
||||
*
|
||||
* - `failed-precondition`: Operation was rejected because the system is not
|
||||
* in a state required for the operation's execution.
|
||||
*
|
||||
* - `aborted`: The operation was aborted, typically due to a concurrency
|
||||
* issue like transaction aborts, etc.
|
||||
*
|
||||
* - `out-of-range`: Operation was attempted past the valid range.
|
||||
*
|
||||
* - `unimplemented`: Operation is not implemented or not supported/enabled.
|
||||
*
|
||||
* - `internal`: Internal errors. Means some invariants expected by
|
||||
* underlying system has been broken. If you see one of these errors,
|
||||
* something is very broken.
|
||||
*
|
||||
* - `unavailable`: The service is currently unavailable. This is most likely
|
||||
* a transient condition and may be corrected by retrying with a backoff.
|
||||
*
|
||||
* - `data-loss`: Unrecoverable data loss or corruption.
|
||||
*
|
||||
* - `unauthenticated`: The request does not have valid authentication
|
||||
* credentials for the operation.
|
||||
*/
|
||||
export type FunctionsErrorCode = "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";
|
||||
/** @hidden */
|
||||
export type CanonicalErrorCodeName = "OK" | "CANCELLED" | "UNKNOWN" | "INVALID_ARGUMENT" | "DEADLINE_EXCEEDED" | "NOT_FOUND" | "ALREADY_EXISTS" | "PERMISSION_DENIED" | "UNAUTHENTICATED" | "RESOURCE_EXHAUSTED" | "FAILED_PRECONDITION" | "ABORTED" | "OUT_OF_RANGE" | "UNIMPLEMENTED" | "INTERNAL" | "UNAVAILABLE" | "DATA_LOSS";
|
||||
/** @hidden */
|
||||
interface HttpErrorCode {
|
||||
canonicalName: CanonicalErrorCodeName;
|
||||
status: number;
|
||||
}
|
||||
/** @hidden */
|
||||
interface HttpErrorWireFormat {
|
||||
details?: unknown;
|
||||
message: string;
|
||||
status: CanonicalErrorCodeName;
|
||||
}
|
||||
/**
|
||||
* An explicit error that can be thrown from a handler to send an error to the
|
||||
* client that called the function.
|
||||
*/
|
||||
export declare class HttpsError extends Error {
|
||||
/**
|
||||
* A standard error code that will be returned to the client. This also
|
||||
* determines the HTTP status code of the response, as defined in code.proto.
|
||||
*/
|
||||
readonly code: FunctionsErrorCode;
|
||||
/**
|
||||
* Extra data to be converted to JSON and included in the error response.
|
||||
*/
|
||||
readonly details: unknown;
|
||||
/**
|
||||
* A wire format representation of a provided error code.
|
||||
*
|
||||
* @hidden
|
||||
*/
|
||||
readonly httpErrorCode: HttpErrorCode;
|
||||
constructor(code: FunctionsErrorCode, message: string, details?: unknown);
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON(): HttpErrorWireFormat;
|
||||
}
|
||||
/** @hidden */
|
||||
interface HttpRequest extends Request {
|
||||
body: {
|
||||
data: any;
|
||||
};
|
||||
}
|
||||
/** @hidden */
|
||||
export declare function isValidRequest(req: Request): req is HttpRequest;
|
||||
/**
|
||||
* Encodes arbitrary data in our special format for JSON.
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @hidden */
|
||||
export declare function encode(data: any): any;
|
||||
/**
|
||||
* Decodes our special format for JSON into native types.
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @hidden */
|
||||
export declare function decode(data: any): any;
|
||||
/**
|
||||
* Be careful when changing token status values.
|
||||
*
|
||||
* Users are encouraged to setup log-based metric based on these values, and
|
||||
* changing their values may cause their metrics to break.
|
||||
*
|
||||
*/
|
||||
/** @hidden */
|
||||
type TokenStatus = "MISSING" | "VALID" | "INVALID";
|
||||
/** @interanl */
|
||||
export declare function checkAuthToken(req: Request, ctx: CallableContext | TaskContext): Promise<TokenStatus>;
|
||||
export {};
|
||||
590
node_modules/firebase-functions/lib/common/providers/https.js
generated
vendored
Normal file
590
node_modules/firebase-functions/lib/common/providers/https.js
generated
vendored
Normal file
@@ -0,0 +1,590 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.onCallHandler = exports.checkAuthToken = exports.unsafeDecodeAppCheckToken = exports.unsafeDecodeIdToken = exports.unsafeDecodeToken = exports.decode = exports.encode = exports.isValidRequest = exports.HttpsError = exports.DEFAULT_HEARTBEAT_SECONDS = exports.ORIGINAL_AUTH_HEADER = exports.CALLABLE_AUTH_HEADER = void 0;
|
||||
const cors = require("cors");
|
||||
const logger = require("../../logger");
|
||||
// TODO(inlined): Decide whether we want to un-version apps or whether we want a
|
||||
// different strategy
|
||||
const app_check_1 = require("firebase-admin/app-check");
|
||||
const auth_1 = require("firebase-admin/auth");
|
||||
const app_1 = require("../app");
|
||||
const debug_1 = require("../debug");
|
||||
const JWT_REGEX = /^[a-zA-Z0-9\-_=]+?\.[a-zA-Z0-9\-_=]+?\.([a-zA-Z0-9\-_=]+)?$/;
|
||||
/** @internal */
|
||||
exports.CALLABLE_AUTH_HEADER = "x-callable-context-auth";
|
||||
/** @internal */
|
||||
exports.ORIGINAL_AUTH_HEADER = "x-original-auth";
|
||||
/** @internal */
|
||||
exports.DEFAULT_HEARTBEAT_SECONDS = 30;
|
||||
/**
|
||||
* Standard error codes and HTTP statuses for different ways a request can fail,
|
||||
* as defined by:
|
||||
* https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
|
||||
*
|
||||
* This map is used primarily to convert from a client error code string to
|
||||
* to the HTTP format error code string and status, and make sure it's in the
|
||||
* supported set.
|
||||
*/
|
||||
const errorCodeMap = {
|
||||
ok: { canonicalName: "OK", status: 200 },
|
||||
cancelled: { canonicalName: "CANCELLED", status: 499 },
|
||||
unknown: { canonicalName: "UNKNOWN", status: 500 },
|
||||
"invalid-argument": { canonicalName: "INVALID_ARGUMENT", status: 400 },
|
||||
"deadline-exceeded": { canonicalName: "DEADLINE_EXCEEDED", status: 504 },
|
||||
"not-found": { canonicalName: "NOT_FOUND", status: 404 },
|
||||
"already-exists": { canonicalName: "ALREADY_EXISTS", status: 409 },
|
||||
"permission-denied": { canonicalName: "PERMISSION_DENIED", status: 403 },
|
||||
unauthenticated: { canonicalName: "UNAUTHENTICATED", status: 401 },
|
||||
"resource-exhausted": { canonicalName: "RESOURCE_EXHAUSTED", status: 429 },
|
||||
"failed-precondition": { canonicalName: "FAILED_PRECONDITION", status: 400 },
|
||||
aborted: { canonicalName: "ABORTED", status: 409 },
|
||||
"out-of-range": { canonicalName: "OUT_OF_RANGE", status: 400 },
|
||||
unimplemented: { canonicalName: "UNIMPLEMENTED", status: 501 },
|
||||
internal: { canonicalName: "INTERNAL", status: 500 },
|
||||
unavailable: { canonicalName: "UNAVAILABLE", status: 503 },
|
||||
"data-loss": { canonicalName: "DATA_LOSS", status: 500 },
|
||||
};
|
||||
/**
|
||||
* An explicit error that can be thrown from a handler to send an error to the
|
||||
* client that called the function.
|
||||
*/
|
||||
class HttpsError extends Error {
|
||||
constructor(code, message, details) {
|
||||
super(message);
|
||||
// A sanity check for non-TypeScript consumers.
|
||||
if (code in errorCodeMap === false) {
|
||||
throw new Error(`Unknown error code: ${code}.`);
|
||||
}
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
this.httpErrorCode = errorCodeMap[code];
|
||||
}
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON() {
|
||||
const { details, httpErrorCode: { canonicalName: status }, message, } = this;
|
||||
return {
|
||||
...(details === undefined ? {} : { details }),
|
||||
message,
|
||||
status,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.HttpsError = HttpsError;
|
||||
/** @hidden */
|
||||
// Returns true if req is a properly formatted callable request.
|
||||
function isValidRequest(req) {
|
||||
// The body must not be empty.
|
||||
if (!req.body) {
|
||||
logger.warn("Request is missing body.");
|
||||
return false;
|
||||
}
|
||||
// Make sure it's a POST.
|
||||
if (req.method !== "POST") {
|
||||
logger.warn("Request has invalid method.", req.method);
|
||||
return false;
|
||||
}
|
||||
// Check that the Content-Type is JSON.
|
||||
let contentType = (req.header("Content-Type") || "").toLowerCase();
|
||||
// If it has a charset, just ignore it for now.
|
||||
const semiColon = contentType.indexOf(";");
|
||||
if (semiColon >= 0) {
|
||||
contentType = contentType.slice(0, semiColon).trim();
|
||||
}
|
||||
if (contentType !== "application/json") {
|
||||
logger.warn("Request has incorrect Content-Type.", contentType);
|
||||
return false;
|
||||
}
|
||||
// The body must have data.
|
||||
if (typeof req.body.data === "undefined") {
|
||||
logger.warn("Request body is missing data.", req.body);
|
||||
return false;
|
||||
}
|
||||
// TODO(klimt): Allow only specific http headers.
|
||||
// Verify that the body does not have any extra fields.
|
||||
const extraKeys = Object.keys(req.body).filter((field) => field !== "data");
|
||||
if (extraKeys.length !== 0) {
|
||||
logger.warn("Request body has extra fields: ", extraKeys.join(", "));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
exports.isValidRequest = isValidRequest;
|
||||
/** @hidden */
|
||||
const LONG_TYPE = "type.googleapis.com/google.protobuf.Int64Value";
|
||||
/** @hidden */
|
||||
const UNSIGNED_LONG_TYPE = "type.googleapis.com/google.protobuf.UInt64Value";
|
||||
/**
|
||||
* Encodes arbitrary data in our special format for JSON.
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @hidden */
|
||||
function encode(data) {
|
||||
if (data === null || typeof data === "undefined") {
|
||||
return null;
|
||||
}
|
||||
if (data instanceof Number) {
|
||||
data = data.valueOf();
|
||||
}
|
||||
if (Number.isFinite(data)) {
|
||||
// Any number in JS is safe to put directly in JSON and parse as a double
|
||||
// without any loss of precision.
|
||||
return data;
|
||||
}
|
||||
if (typeof data === "boolean") {
|
||||
return data;
|
||||
}
|
||||
if (typeof data === "string") {
|
||||
return data;
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
return data.map(encode);
|
||||
}
|
||||
if (typeof data === "object" || typeof data === "function") {
|
||||
// Sadly we don't have Object.fromEntries in Node 10, so we can't use a single
|
||||
// list comprehension
|
||||
const obj = {};
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
obj[k] = encode(v);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
// If we got this far, the data is not encodable.
|
||||
logger.error("Data cannot be encoded in JSON.", data);
|
||||
throw new Error(`Data cannot be encoded in JSON: ${data}`);
|
||||
}
|
||||
exports.encode = encode;
|
||||
/**
|
||||
* Decodes our special format for JSON into native types.
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @hidden */
|
||||
function decode(data) {
|
||||
if (data === null) {
|
||||
return data;
|
||||
}
|
||||
if (data["@type"]) {
|
||||
switch (data["@type"]) {
|
||||
case LONG_TYPE:
|
||||
// Fall through and handle this the same as unsigned.
|
||||
case UNSIGNED_LONG_TYPE: {
|
||||
// Technically, this could work return a valid number for malformed
|
||||
// data if there was a number followed by garbage. But it's just not
|
||||
// worth all the extra code to detect that case.
|
||||
const value = parseFloat(data.value);
|
||||
if (isNaN(value)) {
|
||||
logger.error("Data cannot be decoded from JSON.", data);
|
||||
throw new Error(`Data cannot be decoded from JSON: ${data}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
default: {
|
||||
logger.error("Data cannot be decoded from JSON.", data);
|
||||
throw new Error(`Data cannot be decoded from JSON: ${data}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
return data.map(decode);
|
||||
}
|
||||
if (typeof data === "object") {
|
||||
const obj = {};
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
obj[k] = decode(v);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
// Anything else is safe to return.
|
||||
return data;
|
||||
}
|
||||
exports.decode = decode;
|
||||
/** @internal */
|
||||
function unsafeDecodeToken(token) {
|
||||
if (!JWT_REGEX.test(token)) {
|
||||
return {};
|
||||
}
|
||||
const components = token.split(".").map((s) => Buffer.from(s, "base64").toString());
|
||||
let payload = components[1];
|
||||
if (typeof payload === "string") {
|
||||
try {
|
||||
const obj = JSON.parse(payload);
|
||||
if (typeof obj === "object") {
|
||||
payload = obj;
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// ignore error
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
exports.unsafeDecodeToken = unsafeDecodeToken;
|
||||
/**
|
||||
* Decode, but not verify, a Auth ID token.
|
||||
*
|
||||
* Do not use in production. Token should always be verified using the Admin SDK.
|
||||
*
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @internal */
|
||||
function unsafeDecodeIdToken(token) {
|
||||
const decoded = unsafeDecodeToken(token);
|
||||
decoded.uid = decoded.sub;
|
||||
return decoded;
|
||||
}
|
||||
exports.unsafeDecodeIdToken = unsafeDecodeIdToken;
|
||||
/**
|
||||
* Decode, but not verify, an App Check token.
|
||||
*
|
||||
* Do not use in production. Token should always be verified using the Admin SDK.
|
||||
*
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
/** @internal */
|
||||
function unsafeDecodeAppCheckToken(token) {
|
||||
const decoded = unsafeDecodeToken(token);
|
||||
decoded.app_id = decoded.sub;
|
||||
return decoded;
|
||||
}
|
||||
exports.unsafeDecodeAppCheckToken = unsafeDecodeAppCheckToken;
|
||||
/**
|
||||
* Check and verify tokens included in the requests. Once verified, tokens
|
||||
* are injected into the callable context.
|
||||
*
|
||||
* @param {Request} req - Request sent to the Callable function.
|
||||
* @param {CallableContext} ctx - Context to be sent to callable function handler.
|
||||
* @returns {CallableTokenStatus} Status of the token verifications.
|
||||
*/
|
||||
/** @internal */
|
||||
async function checkTokens(req, ctx, options) {
|
||||
const verifications = {
|
||||
app: "INVALID",
|
||||
auth: "INVALID",
|
||||
};
|
||||
[verifications.auth, verifications.app] = await Promise.all([
|
||||
checkAuthToken(req, ctx),
|
||||
checkAppCheckToken(req, ctx, options),
|
||||
]);
|
||||
const logPayload = {
|
||||
verifications,
|
||||
"logging.googleapis.com/labels": {
|
||||
"firebase-log-type": "callable-request-verification",
|
||||
},
|
||||
};
|
||||
const errs = [];
|
||||
if (verifications.app === "INVALID") {
|
||||
errs.push("AppCheck token was rejected.");
|
||||
}
|
||||
if (verifications.auth === "INVALID") {
|
||||
errs.push("Auth token was rejected.");
|
||||
}
|
||||
if (errs.length === 0) {
|
||||
logger.debug("Callable request verification passed", logPayload);
|
||||
}
|
||||
else {
|
||||
logger.warn(`Callable request verification failed: ${errs.join(" ")}`, logPayload);
|
||||
}
|
||||
return verifications;
|
||||
}
|
||||
/** @interanl */
|
||||
async function checkAuthToken(req, ctx) {
|
||||
const authorization = req.header("Authorization");
|
||||
if (!authorization) {
|
||||
return "MISSING";
|
||||
}
|
||||
const match = authorization.match(/^Bearer (.*)$/i);
|
||||
if (!match) {
|
||||
return "INVALID";
|
||||
}
|
||||
const idToken = match[1];
|
||||
try {
|
||||
let authToken;
|
||||
if ((0, debug_1.isDebugFeatureEnabled)("skipTokenVerification")) {
|
||||
authToken = unsafeDecodeIdToken(idToken);
|
||||
}
|
||||
else {
|
||||
authToken = await (0, auth_1.getAuth)((0, app_1.getApp)()).verifyIdToken(idToken);
|
||||
}
|
||||
ctx.auth = {
|
||||
uid: authToken.uid,
|
||||
token: authToken,
|
||||
};
|
||||
return "VALID";
|
||||
}
|
||||
catch (err) {
|
||||
logger.warn("Failed to validate auth token.", err);
|
||||
return "INVALID";
|
||||
}
|
||||
}
|
||||
exports.checkAuthToken = checkAuthToken;
|
||||
/** @internal */
|
||||
async function checkAppCheckToken(req, ctx, options) {
|
||||
var _a;
|
||||
const appCheckToken = req.header("X-Firebase-AppCheck");
|
||||
if (!appCheckToken) {
|
||||
return "MISSING";
|
||||
}
|
||||
try {
|
||||
let appCheckData;
|
||||
if ((0, debug_1.isDebugFeatureEnabled)("skipTokenVerification")) {
|
||||
const decodedToken = unsafeDecodeAppCheckToken(appCheckToken);
|
||||
appCheckData = { appId: decodedToken.app_id, token: decodedToken };
|
||||
if (options.consumeAppCheckToken) {
|
||||
appCheckData.alreadyConsumed = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const appCheck = (0, app_check_1.getAppCheck)((0, app_1.getApp)());
|
||||
if (options.consumeAppCheckToken) {
|
||||
if (((_a = appCheck.verifyToken) === null || _a === void 0 ? void 0 : _a.length) === 1) {
|
||||
const errorMsg = "Unsupported version of the Admin SDK." +
|
||||
" App Check token will not be consumed." +
|
||||
" Please upgrade the firebase-admin to the latest version.";
|
||||
logger.error(errorMsg);
|
||||
throw new HttpsError("internal", "Internal Error");
|
||||
}
|
||||
appCheckData = await (0, app_check_1.getAppCheck)((0, app_1.getApp)()).verifyToken(appCheckToken, { consume: true });
|
||||
}
|
||||
else {
|
||||
appCheckData = await (0, app_check_1.getAppCheck)((0, app_1.getApp)()).verifyToken(appCheckToken);
|
||||
}
|
||||
}
|
||||
ctx.app = appCheckData;
|
||||
return "VALID";
|
||||
}
|
||||
catch (err) {
|
||||
logger.warn("Failed to validate AppCheck token.", err);
|
||||
if (err instanceof HttpsError) {
|
||||
throw err;
|
||||
}
|
||||
return "INVALID";
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
function onCallHandler(options, handler, version) {
|
||||
const wrapped = wrapOnCallHandler(options, handler, version);
|
||||
return (req, res) => {
|
||||
return new Promise((resolve) => {
|
||||
res.on("finish", resolve);
|
||||
cors(options.cors)(req, res, () => {
|
||||
resolve(wrapped(req, res));
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
exports.onCallHandler = onCallHandler;
|
||||
function encodeSSE(data) {
|
||||
return `data: ${JSON.stringify(data)}\n\n`;
|
||||
}
|
||||
/** @internal */
|
||||
function wrapOnCallHandler(options, handler, version) {
|
||||
return async (req, res) => {
|
||||
var _a;
|
||||
const abortController = new AbortController();
|
||||
let heartbeatInterval = null;
|
||||
const heartbeatSeconds = options.heartbeatSeconds === undefined ? exports.DEFAULT_HEARTBEAT_SECONDS : options.heartbeatSeconds;
|
||||
const clearScheduledHeartbeat = () => {
|
||||
if (heartbeatInterval) {
|
||||
clearTimeout(heartbeatInterval);
|
||||
heartbeatInterval = null;
|
||||
}
|
||||
};
|
||||
const scheduleHeartbeat = () => {
|
||||
clearScheduledHeartbeat();
|
||||
if (!abortController.signal.aborted) {
|
||||
heartbeatInterval = setTimeout(() => {
|
||||
if (!abortController.signal.aborted) {
|
||||
res.write(": ping\n\n");
|
||||
scheduleHeartbeat();
|
||||
}
|
||||
}, heartbeatSeconds * 1000);
|
||||
}
|
||||
};
|
||||
res.on("close", () => {
|
||||
clearScheduledHeartbeat();
|
||||
abortController.abort();
|
||||
});
|
||||
try {
|
||||
if (!isValidRequest(req)) {
|
||||
logger.error("Invalid request, unable to process.");
|
||||
throw new HttpsError("invalid-argument", "Bad Request");
|
||||
}
|
||||
const context = { rawRequest: req };
|
||||
// TODO(colerogers): yank this when we release a breaking change of the CLI that removes
|
||||
// our monkey-patching code referenced below and increases the minimum supported SDK version.
|
||||
//
|
||||
// Note: This code is needed to fix v1 callable functions in the emulator with a monorepo setup.
|
||||
// The original monkey-patched code lived in the functionsEmulatorRuntime
|
||||
// (link: https://github.com/firebase/firebase-tools/blob/accea7abda3cc9fa6bb91368e4895faf95281c60/src/emulator/functionsEmulatorRuntime.ts#L480)
|
||||
// and was not compatible with how monorepos separate out packages (see https://github.com/firebase/firebase-tools/issues/5210).
|
||||
if ((0, debug_1.isDebugFeatureEnabled)("skipTokenVerification") && version === "gcfv1") {
|
||||
const authContext = context.rawRequest.header(exports.CALLABLE_AUTH_HEADER);
|
||||
if (authContext) {
|
||||
logger.debug("Callable functions auth override", {
|
||||
key: exports.CALLABLE_AUTH_HEADER,
|
||||
value: authContext,
|
||||
});
|
||||
context.auth = JSON.parse(decodeURIComponent(authContext));
|
||||
delete context.rawRequest.headers[exports.CALLABLE_AUTH_HEADER];
|
||||
}
|
||||
const originalAuth = context.rawRequest.header(exports.ORIGINAL_AUTH_HEADER);
|
||||
if (originalAuth) {
|
||||
context.rawRequest.headers["authorization"] = originalAuth;
|
||||
delete context.rawRequest.headers[exports.ORIGINAL_AUTH_HEADER];
|
||||
}
|
||||
}
|
||||
const tokenStatus = await checkTokens(req, context, options);
|
||||
if (tokenStatus.auth === "INVALID") {
|
||||
throw new HttpsError("unauthenticated", "Unauthenticated");
|
||||
}
|
||||
if (tokenStatus.app === "INVALID") {
|
||||
if (options.enforceAppCheck) {
|
||||
throw new HttpsError("unauthenticated", "Unauthenticated");
|
||||
}
|
||||
else {
|
||||
logger.warn("Allowing request with invalid AppCheck token because enforcement is disabled");
|
||||
}
|
||||
}
|
||||
if (tokenStatus.app === "MISSING" && options.enforceAppCheck) {
|
||||
throw new HttpsError("unauthenticated", "Unauthenticated");
|
||||
}
|
||||
const instanceId = req.header("Firebase-Instance-ID-Token");
|
||||
if (instanceId) {
|
||||
// Validating the token requires an http request, so we don't do it.
|
||||
// If the user wants to use it for something, it will be validated then.
|
||||
// Currently, the only real use case for this token is for sending
|
||||
// pushes with FCM. In that case, the FCM APIs will validate the token.
|
||||
context.instanceIdToken = req.header("Firebase-Instance-ID-Token");
|
||||
}
|
||||
const acceptsStreaming = req.header("accept") === "text/event-stream";
|
||||
if (acceptsStreaming && version === "gcfv1") {
|
||||
// streaming responses are not supported in v1 callable
|
||||
throw new HttpsError("invalid-argument", "Unsupported Accept header 'text/event-stream'");
|
||||
}
|
||||
const data = decode(req.body.data);
|
||||
if (options.authPolicy) {
|
||||
const authorized = await options.authPolicy((_a = context.auth) !== null && _a !== void 0 ? _a : null, data);
|
||||
if (!authorized) {
|
||||
throw new HttpsError("permission-denied", "Permission Denied");
|
||||
}
|
||||
}
|
||||
let result;
|
||||
if (version === "gcfv1") {
|
||||
result = await handler(data, context);
|
||||
}
|
||||
else {
|
||||
const arg = {
|
||||
...context,
|
||||
data,
|
||||
acceptsStreaming,
|
||||
};
|
||||
const responseProxy = {
|
||||
sendChunk(chunk) {
|
||||
// if client doesn't accept sse-protocol, response.write() is no-op.
|
||||
if (!acceptsStreaming) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
// if connection is already closed, response.write() is no-op.
|
||||
if (abortController.signal.aborted) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const formattedData = encodeSSE({ message: chunk });
|
||||
let resolve;
|
||||
let reject;
|
||||
const p = new Promise((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
const wrote = res.write(formattedData, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(wrote);
|
||||
});
|
||||
// Reset heartbeat timer after successful write
|
||||
if (wrote && heartbeatInterval !== null && heartbeatSeconds > 0) {
|
||||
scheduleHeartbeat();
|
||||
}
|
||||
return p;
|
||||
},
|
||||
signal: abortController.signal,
|
||||
};
|
||||
if (acceptsStreaming) {
|
||||
// SSE always responds with 200
|
||||
res.status(200);
|
||||
if (heartbeatSeconds !== null && heartbeatSeconds > 0) {
|
||||
scheduleHeartbeat();
|
||||
}
|
||||
}
|
||||
// For some reason the type system isn't picking up that the handler
|
||||
// is a one argument function.
|
||||
result = await handler(arg, responseProxy);
|
||||
clearScheduledHeartbeat();
|
||||
}
|
||||
if (!abortController.signal.aborted) {
|
||||
// Encode the result as JSON to preserve types like Dates.
|
||||
result = encode(result);
|
||||
// If there was some result, encode it in the body.
|
||||
const responseBody = { result };
|
||||
if (acceptsStreaming) {
|
||||
res.write(encodeSSE(responseBody));
|
||||
res.end();
|
||||
}
|
||||
else {
|
||||
res.status(200).send(responseBody);
|
||||
}
|
||||
}
|
||||
else {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (!abortController.signal.aborted) {
|
||||
let httpErr = err;
|
||||
if (!(err instanceof HttpsError)) {
|
||||
// This doesn't count as an 'explicit' error.
|
||||
logger.error("Unhandled error", err);
|
||||
httpErr = new HttpsError("internal", "INTERNAL");
|
||||
}
|
||||
const { status } = httpErr.httpErrorCode;
|
||||
const body = { error: httpErr.toJSON() };
|
||||
if (version === "gcfv2" && req.header("accept") === "text/event-stream") {
|
||||
res.write(encodeSSE(body));
|
||||
res.end();
|
||||
}
|
||||
else {
|
||||
res.status(status).send(body);
|
||||
}
|
||||
}
|
||||
else {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
finally {
|
||||
clearScheduledHeartbeat();
|
||||
}
|
||||
};
|
||||
}
|
||||
258
node_modules/firebase-functions/lib/common/providers/identity.d.ts
generated
vendored
Normal file
258
node_modules/firebase-functions/lib/common/providers/identity.d.ts
generated
vendored
Normal file
@@ -0,0 +1,258 @@
|
||||
import * as auth from "firebase-admin/auth";
|
||||
import { EventContext } from "../../v1/cloud-functions";
|
||||
import { HttpsError } from "./https";
|
||||
export { HttpsError };
|
||||
/**
|
||||
* Shorthand auth blocking events from GCIP.
|
||||
* @hidden
|
||||
* @alpha
|
||||
*/
|
||||
export type AuthBlockingEventType = "beforeCreate" | "beforeSignIn" | "beforeSendEmail" | "beforeSendSms";
|
||||
/**
|
||||
* The `UserRecord` passed to Cloud Functions is the same
|
||||
* {@link https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.userrecord | UserRecord}
|
||||
* that is returned by the Firebase Admin SDK.
|
||||
*/
|
||||
export type UserRecord = auth.UserRecord;
|
||||
/**
|
||||
* `UserInfo` that is part of the `UserRecord`.
|
||||
*/
|
||||
export type UserInfo = auth.UserInfo;
|
||||
/**
|
||||
* Helper class to create the user metadata in a `UserRecord` object.
|
||||
*/
|
||||
export declare class UserRecordMetadata implements auth.UserMetadata {
|
||||
creationTime: string;
|
||||
lastSignInTime: string;
|
||||
constructor(creationTime: string, lastSignInTime: string);
|
||||
/** Returns a plain JavaScript object with the properties of UserRecordMetadata. */
|
||||
toJSON(): AuthUserMetadata;
|
||||
}
|
||||
/**
|
||||
* Helper function that creates a `UserRecord` class from data sent over the wire.
|
||||
* @param wireData data sent over the wire
|
||||
* @returns an instance of `UserRecord` with correct toJSON functions
|
||||
*/
|
||||
export declare function userRecordConstructor(wireData: Record<string, unknown>): UserRecord;
|
||||
/**
|
||||
* User info that is part of the `AuthUserRecord`.
|
||||
*/
|
||||
export interface AuthUserInfo {
|
||||
/**
|
||||
* The user identifier for the linked provider.
|
||||
*/
|
||||
uid: string;
|
||||
/**
|
||||
* The display name for the linked provider.
|
||||
*/
|
||||
displayName: string;
|
||||
/**
|
||||
* The email for the linked provider.
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* The photo URL for the linked provider.
|
||||
*/
|
||||
photoURL: string;
|
||||
/**
|
||||
* The linked provider ID (for example, "google.com" for the Google provider).
|
||||
*/
|
||||
providerId: string;
|
||||
/**
|
||||
* The phone number for the linked provider.
|
||||
*/
|
||||
phoneNumber: string;
|
||||
}
|
||||
/**
|
||||
* Additional metadata about the user.
|
||||
*/
|
||||
export interface AuthUserMetadata {
|
||||
/**
|
||||
* The date the user was created, formatted as a UTC string.
|
||||
*/
|
||||
creationTime: string;
|
||||
/**
|
||||
* The date the user last signed in, formatted as a UTC string.
|
||||
*/
|
||||
lastSignInTime: string;
|
||||
}
|
||||
/**
|
||||
* Interface representing the common properties of a user-enrolled second factor.
|
||||
*/
|
||||
export interface AuthMultiFactorInfo {
|
||||
/**
|
||||
* The ID of the enrolled second factor. This ID is unique to the user.
|
||||
*/
|
||||
uid: string;
|
||||
/**
|
||||
* The optional display name of the enrolled second factor.
|
||||
*/
|
||||
displayName?: string;
|
||||
/**
|
||||
* The type identifier of the second factor. For SMS second factors, this is `phone`.
|
||||
*/
|
||||
factorId: string;
|
||||
/**
|
||||
* The optional date the second factor was enrolled, formatted as a UTC string.
|
||||
*/
|
||||
enrollmentTime?: string;
|
||||
/**
|
||||
* The phone number associated with a phone second factor.
|
||||
*/
|
||||
phoneNumber?: string;
|
||||
}
|
||||
/**
|
||||
* The multi-factor related properties for the current user, if available.
|
||||
*/
|
||||
export interface AuthMultiFactorSettings {
|
||||
/**
|
||||
* List of second factors enrolled with the current user.
|
||||
*/
|
||||
enrolledFactors: AuthMultiFactorInfo[];
|
||||
}
|
||||
/**
|
||||
* The `UserRecord` passed to auth blocking functions from the identity platform.
|
||||
*/
|
||||
export interface AuthUserRecord {
|
||||
/**
|
||||
* The user's `uid`.
|
||||
*/
|
||||
uid: string;
|
||||
/**
|
||||
* The user's primary email, if set.
|
||||
*/
|
||||
email?: string;
|
||||
/**
|
||||
* Whether or not the user's primary email is verified.
|
||||
*/
|
||||
emailVerified: boolean;
|
||||
/**
|
||||
* The user's display name.
|
||||
*/
|
||||
displayName?: string;
|
||||
/**
|
||||
* The user's photo URL.
|
||||
*/
|
||||
photoURL?: string;
|
||||
/**
|
||||
* The user's primary phone number, if set.
|
||||
*/
|
||||
phoneNumber?: string;
|
||||
/**
|
||||
* Whether or not the user is disabled: `true` for disabled; `false` for
|
||||
* enabled.
|
||||
*/
|
||||
disabled: boolean;
|
||||
/**
|
||||
* Additional metadata about the user.
|
||||
*/
|
||||
metadata: AuthUserMetadata;
|
||||
/**
|
||||
* An array of providers (for example, Google, Facebook) linked to the user.
|
||||
*/
|
||||
providerData: AuthUserInfo[];
|
||||
/**
|
||||
* The user's hashed password (base64-encoded).
|
||||
*/
|
||||
passwordHash?: string;
|
||||
/**
|
||||
* The user's password salt (base64-encoded).
|
||||
*/
|
||||
passwordSalt?: string;
|
||||
/**
|
||||
* The user's custom claims object if available, typically used to define
|
||||
* user roles and propagated to an authenticated user's ID token.
|
||||
*/
|
||||
customClaims?: Record<string, any>;
|
||||
/**
|
||||
* The ID of the tenant the user belongs to, if available.
|
||||
*/
|
||||
tenantId?: string | null;
|
||||
/**
|
||||
* The date the user's tokens are valid after, formatted as a UTC string.
|
||||
*/
|
||||
tokensValidAfterTime?: string;
|
||||
/**
|
||||
* The multi-factor related properties for the current user, if available.
|
||||
*/
|
||||
multiFactor?: AuthMultiFactorSettings;
|
||||
}
|
||||
/** The additional user info component of the auth event context */
|
||||
export interface AdditionalUserInfo {
|
||||
providerId?: string;
|
||||
profile?: any;
|
||||
username?: string;
|
||||
isNewUser: boolean;
|
||||
recaptchaScore?: number;
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
}
|
||||
/** The credential component of the auth event context */
|
||||
export interface Credential {
|
||||
claims?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
idToken?: string;
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
expirationTime?: string;
|
||||
secret?: string;
|
||||
providerId: string;
|
||||
signInMethod: string;
|
||||
}
|
||||
/**
|
||||
* Possible types of emails as described by the GCIP backend, which can be:
|
||||
* - A sign-in email
|
||||
* - A password reset email
|
||||
*/
|
||||
export type EmailType = "EMAIL_SIGN_IN" | "PASSWORD_RESET";
|
||||
/**
|
||||
* The type of SMS message, which can be:
|
||||
* - A sign-in or sign up SMS message
|
||||
* - A multi-factor sign-in SMS message
|
||||
* - A multi-factor enrollment SMS message
|
||||
*/
|
||||
export type SmsType = "SIGN_IN_OR_SIGN_UP" | "MULTI_FACTOR_SIGN_IN" | "MULTI_FACTOR_ENROLLMENT";
|
||||
/** Defines the auth event context for blocking events */
|
||||
export interface AuthEventContext extends EventContext {
|
||||
locale?: string;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
additionalUserInfo?: AdditionalUserInfo;
|
||||
credential?: Credential;
|
||||
emailType?: EmailType;
|
||||
smsType?: SmsType;
|
||||
}
|
||||
/** Defines the auth event for 2nd gen blocking events */
|
||||
export interface AuthBlockingEvent extends AuthEventContext {
|
||||
data?: AuthUserRecord;
|
||||
}
|
||||
/** The reCAPTCHA action options. */
|
||||
export type RecaptchaActionOptions = "ALLOW" | "BLOCK";
|
||||
/** The handler response type for `beforeEmailSent` blocking events */
|
||||
export interface BeforeEmailResponse {
|
||||
recaptchaActionOverride?: RecaptchaActionOptions;
|
||||
}
|
||||
/** The handler response type for `beforeSmsSent` blocking events */
|
||||
export interface BeforeSmsResponse {
|
||||
recaptchaActionOverride?: RecaptchaActionOptions;
|
||||
}
|
||||
/** The handler response type for `beforeCreate` blocking events */
|
||||
export interface BeforeCreateResponse {
|
||||
displayName?: string;
|
||||
disabled?: boolean;
|
||||
emailVerified?: boolean;
|
||||
photoURL?: string;
|
||||
customClaims?: object;
|
||||
recaptchaActionOverride?: RecaptchaActionOptions;
|
||||
}
|
||||
/** The handler response type for `beforeSignIn` blocking events */
|
||||
export interface BeforeSignInResponse extends BeforeCreateResponse {
|
||||
sessionClaims?: object;
|
||||
}
|
||||
export type MaybeAsync<T> = T | Promise<T>;
|
||||
export type HandlerV1 = (userOrContext: AuthUserRecord | AuthEventContext, context?: AuthEventContext) => MaybeAsync<BeforeCreateResponse | BeforeSignInResponse | BeforeEmailResponse | BeforeSmsResponse | void>;
|
||||
export type HandlerV2 = (event: AuthBlockingEvent) => MaybeAsync<BeforeCreateResponse | BeforeSignInResponse | BeforeEmailResponse | BeforeSmsResponse | void>;
|
||||
export type AuthBlockingEventHandler = (HandlerV1 | HandlerV2) & {
|
||||
platform: "gcfv1" | "gcfv2";
|
||||
};
|
||||
494
node_modules/firebase-functions/lib/common/providers/identity.js
generated
vendored
Normal file
494
node_modules/firebase-functions/lib/common/providers/identity.js
generated
vendored
Normal file
@@ -0,0 +1,494 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.wrapHandler = exports.getUpdateMask = exports.validateAuthResponse = exports.parseAuthEventContext = exports.generateResponsePayload = exports.parseAuthUserRecord = exports.parseMultiFactor = exports.parseDate = exports.parseProviderData = exports.parseMetadata = exports.isValidRequest = exports.userRecordConstructor = exports.UserRecordMetadata = exports.HttpsError = void 0;
|
||||
const auth = require("firebase-admin/auth");
|
||||
const logger = require("../../logger");
|
||||
const app_1 = require("../app");
|
||||
const debug_1 = require("../debug");
|
||||
const https_1 = require("./https");
|
||||
Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function () { return https_1.HttpsError; } });
|
||||
const DISALLOWED_CUSTOM_CLAIMS = [
|
||||
"acr",
|
||||
"amr",
|
||||
"at_hash",
|
||||
"aud",
|
||||
"auth_time",
|
||||
"azp",
|
||||
"cnf",
|
||||
"c_hash",
|
||||
"exp",
|
||||
"iat",
|
||||
"iss",
|
||||
"jti",
|
||||
"nbf",
|
||||
"nonce",
|
||||
"firebase",
|
||||
];
|
||||
const CLAIMS_MAX_PAYLOAD_SIZE = 1000;
|
||||
const EVENT_MAPPING = {
|
||||
beforeCreate: "providers/cloud.auth/eventTypes/user.beforeCreate",
|
||||
beforeSignIn: "providers/cloud.auth/eventTypes/user.beforeSignIn",
|
||||
beforeSendEmail: "providers/cloud.auth/eventTypes/user.beforeSendEmail",
|
||||
beforeSendSms: "providers/cloud.auth/eventTypes/user.beforeSendSms",
|
||||
};
|
||||
/**
|
||||
* Helper class to create the user metadata in a `UserRecord` object.
|
||||
*/
|
||||
class UserRecordMetadata {
|
||||
constructor(creationTime, lastSignInTime) {
|
||||
this.creationTime = creationTime;
|
||||
this.lastSignInTime = lastSignInTime;
|
||||
}
|
||||
/** Returns a plain JavaScript object with the properties of UserRecordMetadata. */
|
||||
toJSON() {
|
||||
return {
|
||||
creationTime: this.creationTime,
|
||||
lastSignInTime: this.lastSignInTime,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.UserRecordMetadata = UserRecordMetadata;
|
||||
/**
|
||||
* Helper function that creates a `UserRecord` class from data sent over the wire.
|
||||
* @param wireData data sent over the wire
|
||||
* @returns an instance of `UserRecord` with correct toJSON functions
|
||||
*/
|
||||
function userRecordConstructor(wireData) {
|
||||
// Falsey values from the wire format proto get lost when converted to JSON, this adds them back.
|
||||
const falseyValues = {
|
||||
email: null,
|
||||
emailVerified: false,
|
||||
displayName: null,
|
||||
photoURL: null,
|
||||
phoneNumber: null,
|
||||
disabled: false,
|
||||
providerData: [],
|
||||
customClaims: {},
|
||||
passwordSalt: null,
|
||||
passwordHash: null,
|
||||
tokensValidAfterTime: null,
|
||||
};
|
||||
const record = { ...falseyValues, ...wireData };
|
||||
const meta = record.metadata;
|
||||
if (meta) {
|
||||
record.metadata = new UserRecordMetadata(meta.createdAt || meta.creationTime, meta.lastSignedInAt || meta.lastSignInTime);
|
||||
}
|
||||
else {
|
||||
record.metadata = new UserRecordMetadata(null, null);
|
||||
}
|
||||
record.toJSON = () => {
|
||||
const { uid, email, emailVerified, displayName, photoURL, phoneNumber, disabled, passwordHash, passwordSalt, tokensValidAfterTime, } = record;
|
||||
const json = {
|
||||
uid,
|
||||
email,
|
||||
emailVerified,
|
||||
displayName,
|
||||
photoURL,
|
||||
phoneNumber,
|
||||
disabled,
|
||||
passwordHash,
|
||||
passwordSalt,
|
||||
tokensValidAfterTime,
|
||||
};
|
||||
json.metadata = record.metadata.toJSON();
|
||||
json.customClaims = JSON.parse(JSON.stringify(record.customClaims));
|
||||
json.providerData = record.providerData.map((entry) => {
|
||||
const newEntry = { ...entry };
|
||||
newEntry.toJSON = () => entry;
|
||||
return newEntry;
|
||||
});
|
||||
return json;
|
||||
};
|
||||
return record;
|
||||
}
|
||||
exports.userRecordConstructor = userRecordConstructor;
|
||||
/**
|
||||
* Checks for a valid identity platform web request, otherwise throws an HttpsError.
|
||||
* @internal
|
||||
*/
|
||||
function isValidRequest(req) {
|
||||
var _a, _b;
|
||||
if (req.method !== "POST") {
|
||||
logger.warn(`Request has invalid method "${req.method}".`);
|
||||
return false;
|
||||
}
|
||||
const contentType = (req.header("Content-Type") || "").toLowerCase();
|
||||
if (!contentType.includes("application/json")) {
|
||||
logger.warn("Request has invalid header Content-Type.");
|
||||
return false;
|
||||
}
|
||||
if (!((_b = (_a = req.body) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.jwt)) {
|
||||
logger.warn("Request has an invalid body.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
exports.isValidRequest = isValidRequest;
|
||||
/**
|
||||
* Decode, but not verify, an Auth Blocking token.
|
||||
*
|
||||
* Do not use in production. Token should always be verified using the Admin SDK.
|
||||
*
|
||||
* This is exposed only for testing.
|
||||
*/
|
||||
function unsafeDecodeAuthBlockingToken(token) {
|
||||
const decoded = (0, https_1.unsafeDecodeToken)(token);
|
||||
decoded.uid = decoded.sub;
|
||||
return decoded;
|
||||
}
|
||||
/**
|
||||
* Helper function to parse the decoded metadata object into a `UserMetaData` object
|
||||
* @internal
|
||||
*/
|
||||
function parseMetadata(metadata) {
|
||||
const creationTime = (metadata === null || metadata === void 0 ? void 0 : metadata.creation_time)
|
||||
? new Date(metadata.creation_time).toUTCString()
|
||||
: null;
|
||||
const lastSignInTime = (metadata === null || metadata === void 0 ? void 0 : metadata.last_sign_in_time)
|
||||
? new Date(metadata.last_sign_in_time).toUTCString()
|
||||
: null;
|
||||
return {
|
||||
creationTime,
|
||||
lastSignInTime,
|
||||
};
|
||||
}
|
||||
exports.parseMetadata = parseMetadata;
|
||||
/**
|
||||
* Helper function to parse the decoded user info array into an `AuthUserInfo` array.
|
||||
* @internal
|
||||
*/
|
||||
function parseProviderData(providerData) {
|
||||
const providers = [];
|
||||
for (const provider of providerData) {
|
||||
providers.push({
|
||||
uid: provider.uid,
|
||||
displayName: provider.display_name,
|
||||
email: provider.email,
|
||||
photoURL: provider.photo_url,
|
||||
providerId: provider.provider_id,
|
||||
phoneNumber: provider.phone_number,
|
||||
});
|
||||
}
|
||||
return providers;
|
||||
}
|
||||
exports.parseProviderData = parseProviderData;
|
||||
/**
|
||||
* Helper function to parse the date into a UTC string.
|
||||
* @internal
|
||||
*/
|
||||
function parseDate(tokensValidAfterTime) {
|
||||
if (!tokensValidAfterTime) {
|
||||
return null;
|
||||
}
|
||||
tokensValidAfterTime = tokensValidAfterTime * 1000;
|
||||
try {
|
||||
const date = new Date(tokensValidAfterTime);
|
||||
if (!isNaN(date.getTime())) {
|
||||
return date.toUTCString();
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// ignore error
|
||||
}
|
||||
return null;
|
||||
}
|
||||
exports.parseDate = parseDate;
|
||||
/**
|
||||
* Helper function to parse the decoded enrolled factors into a valid MultiFactorSettings
|
||||
* @internal
|
||||
*/
|
||||
function parseMultiFactor(multiFactor) {
|
||||
if (!multiFactor) {
|
||||
return null;
|
||||
}
|
||||
const parsedEnrolledFactors = [];
|
||||
for (const factor of multiFactor.enrolled_factors || []) {
|
||||
if (!factor.uid) {
|
||||
throw new https_1.HttpsError("internal", "INTERNAL ASSERT FAILED: Invalid multi-factor info response");
|
||||
}
|
||||
const enrollmentTime = factor.enrollment_time
|
||||
? new Date(factor.enrollment_time).toUTCString()
|
||||
: null;
|
||||
parsedEnrolledFactors.push({
|
||||
uid: factor.uid,
|
||||
factorId: factor.phone_number ? factor.factor_id || "phone" : factor.factor_id,
|
||||
displayName: factor.display_name,
|
||||
enrollmentTime,
|
||||
phoneNumber: factor.phone_number,
|
||||
});
|
||||
}
|
||||
if (parsedEnrolledFactors.length > 0) {
|
||||
return {
|
||||
enrolledFactors: parsedEnrolledFactors,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
exports.parseMultiFactor = parseMultiFactor;
|
||||
/**
|
||||
* Parses the decoded user record into a valid UserRecord for use in the handler
|
||||
* @internal
|
||||
*/
|
||||
function parseAuthUserRecord(decodedJWTUserRecord) {
|
||||
if (!decodedJWTUserRecord.uid) {
|
||||
throw new https_1.HttpsError("internal", "INTERNAL ASSERT FAILED: Invalid user response");
|
||||
}
|
||||
const disabled = decodedJWTUserRecord.disabled || false;
|
||||
const metadata = parseMetadata(decodedJWTUserRecord.metadata);
|
||||
const providerData = parseProviderData(decodedJWTUserRecord.provider_data);
|
||||
const tokensValidAfterTime = parseDate(decodedJWTUserRecord.tokens_valid_after_time);
|
||||
const multiFactor = parseMultiFactor(decodedJWTUserRecord.multi_factor);
|
||||
return {
|
||||
uid: decodedJWTUserRecord.uid,
|
||||
email: decodedJWTUserRecord.email,
|
||||
emailVerified: decodedJWTUserRecord.email_verified,
|
||||
displayName: decodedJWTUserRecord.display_name,
|
||||
photoURL: decodedJWTUserRecord.photo_url,
|
||||
phoneNumber: decodedJWTUserRecord.phone_number,
|
||||
disabled,
|
||||
metadata,
|
||||
providerData,
|
||||
passwordHash: decodedJWTUserRecord.password_hash,
|
||||
passwordSalt: decodedJWTUserRecord.password_salt,
|
||||
customClaims: decodedJWTUserRecord.custom_claims,
|
||||
tenantId: decodedJWTUserRecord.tenant_id,
|
||||
tokensValidAfterTime,
|
||||
multiFactor,
|
||||
};
|
||||
}
|
||||
exports.parseAuthUserRecord = parseAuthUserRecord;
|
||||
/** Helper to get the `AdditionalUserInfo` from the decoded JWT */
|
||||
function parseAdditionalUserInfo(decodedJWT) {
|
||||
let profile;
|
||||
let username;
|
||||
if (decodedJWT.raw_user_info) {
|
||||
try {
|
||||
profile = JSON.parse(decodedJWT.raw_user_info);
|
||||
}
|
||||
catch (err) {
|
||||
logger.debug(`Parse Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
if (profile) {
|
||||
if (decodedJWT.sign_in_method === "github.com") {
|
||||
username = profile.login;
|
||||
}
|
||||
if (decodedJWT.sign_in_method === "twitter.com") {
|
||||
username = profile.screen_name;
|
||||
}
|
||||
}
|
||||
return {
|
||||
providerId: decodedJWT.sign_in_method === "emailLink" ? "password" : decodedJWT.sign_in_method,
|
||||
profile,
|
||||
username,
|
||||
isNewUser: decodedJWT.event_type === "beforeCreate" ? true : false,
|
||||
recaptchaScore: decodedJWT.recaptcha_score,
|
||||
email: decodedJWT.email,
|
||||
phoneNumber: decodedJWT.phone_number,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Helper to generate a response from the blocking function to the Firebase Auth backend.
|
||||
* @internal
|
||||
*/
|
||||
function generateResponsePayload(authResponse) {
|
||||
if (!authResponse) {
|
||||
return {};
|
||||
}
|
||||
const { recaptchaActionOverride, ...formattedAuthResponse } = authResponse;
|
||||
const result = {};
|
||||
const updateMask = getUpdateMask(formattedAuthResponse);
|
||||
if (updateMask.length !== 0) {
|
||||
result.userRecord = {
|
||||
...formattedAuthResponse,
|
||||
updateMask,
|
||||
};
|
||||
}
|
||||
if (recaptchaActionOverride !== undefined) {
|
||||
result.recaptchaActionOverride = recaptchaActionOverride;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
exports.generateResponsePayload = generateResponsePayload;
|
||||
/** Helper to get the Credential from the decoded JWT */
|
||||
function parseAuthCredential(decodedJWT, time) {
|
||||
if (!decodedJWT.sign_in_attributes &&
|
||||
!decodedJWT.oauth_id_token &&
|
||||
!decodedJWT.oauth_access_token &&
|
||||
!decodedJWT.oauth_refresh_token) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
claims: decodedJWT.sign_in_attributes,
|
||||
idToken: decodedJWT.oauth_id_token,
|
||||
accessToken: decodedJWT.oauth_access_token,
|
||||
refreshToken: decodedJWT.oauth_refresh_token,
|
||||
expirationTime: decodedJWT.oauth_expires_in
|
||||
? new Date(time + decodedJWT.oauth_expires_in * 1000).toUTCString()
|
||||
: undefined,
|
||||
secret: decodedJWT.oauth_token_secret,
|
||||
providerId: decodedJWT.sign_in_method === "emailLink" ? "password" : decodedJWT.sign_in_method,
|
||||
signInMethod: decodedJWT.sign_in_method,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Parses the decoded jwt into a valid AuthEventContext for use in the handler
|
||||
* @internal
|
||||
*/
|
||||
function parseAuthEventContext(decodedJWT, projectId, time = new Date().getTime()) {
|
||||
const eventType = (EVENT_MAPPING[decodedJWT.event_type] || decodedJWT.event_type) +
|
||||
(decodedJWT.sign_in_method ? `:${decodedJWT.sign_in_method}` : "");
|
||||
return {
|
||||
locale: decodedJWT.locale,
|
||||
ipAddress: decodedJWT.ip_address,
|
||||
userAgent: decodedJWT.user_agent,
|
||||
eventId: decodedJWT.event_id,
|
||||
eventType,
|
||||
authType: decodedJWT.user_record ? "USER" : "UNAUTHENTICATED",
|
||||
resource: {
|
||||
// TODO(colerogers): figure out the correct service
|
||||
service: "identitytoolkit.googleapis.com",
|
||||
name: decodedJWT.tenant_id
|
||||
? `projects/${projectId}/tenants/${decodedJWT.tenant_id}`
|
||||
: `projects/${projectId}`,
|
||||
},
|
||||
timestamp: new Date(decodedJWT.iat * 1000).toUTCString(),
|
||||
additionalUserInfo: parseAdditionalUserInfo(decodedJWT),
|
||||
credential: parseAuthCredential(decodedJWT, time),
|
||||
emailType: decodedJWT.email_type,
|
||||
smsType: decodedJWT.sms_type,
|
||||
params: {},
|
||||
};
|
||||
}
|
||||
exports.parseAuthEventContext = parseAuthEventContext;
|
||||
/**
|
||||
* Checks the handler response for invalid customClaims & sessionClaims objects
|
||||
* @internal
|
||||
*/
|
||||
function validateAuthResponse(eventType, authRequest) {
|
||||
if (!authRequest) {
|
||||
authRequest = {};
|
||||
}
|
||||
if (authRequest.customClaims) {
|
||||
const invalidClaims = DISALLOWED_CUSTOM_CLAIMS.filter((claim) => authRequest.customClaims.hasOwnProperty(claim));
|
||||
if (invalidClaims.length > 0) {
|
||||
throw new https_1.HttpsError("invalid-argument", `The customClaims claims "${invalidClaims.join(",")}" are reserved and cannot be specified.`);
|
||||
}
|
||||
if (JSON.stringify(authRequest.customClaims).length > CLAIMS_MAX_PAYLOAD_SIZE) {
|
||||
throw new https_1.HttpsError("invalid-argument", `The customClaims payload should not exceed ${CLAIMS_MAX_PAYLOAD_SIZE} characters.`);
|
||||
}
|
||||
}
|
||||
if (eventType === "beforeSignIn" && authRequest.sessionClaims) {
|
||||
const invalidClaims = DISALLOWED_CUSTOM_CLAIMS.filter((claim) => authRequest.sessionClaims.hasOwnProperty(claim));
|
||||
if (invalidClaims.length > 0) {
|
||||
throw new https_1.HttpsError("invalid-argument", `The sessionClaims claims "${invalidClaims.join(",")}" are reserved and cannot be specified.`);
|
||||
}
|
||||
if (JSON.stringify(authRequest.sessionClaims).length >
|
||||
CLAIMS_MAX_PAYLOAD_SIZE) {
|
||||
throw new https_1.HttpsError("invalid-argument", `The sessionClaims payload should not exceed ${CLAIMS_MAX_PAYLOAD_SIZE} characters.`);
|
||||
}
|
||||
const combinedClaims = {
|
||||
...authRequest.customClaims,
|
||||
...authRequest.sessionClaims,
|
||||
};
|
||||
if (JSON.stringify(combinedClaims).length > CLAIMS_MAX_PAYLOAD_SIZE) {
|
||||
throw new https_1.HttpsError("invalid-argument", `The customClaims and sessionClaims payloads should not exceed ${CLAIMS_MAX_PAYLOAD_SIZE} characters combined.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.validateAuthResponse = validateAuthResponse;
|
||||
/**
|
||||
* Helper function to generate the update mask for the identity platform changed values
|
||||
* @internal
|
||||
*/
|
||||
function getUpdateMask(authResponse) {
|
||||
if (!authResponse) {
|
||||
return "";
|
||||
}
|
||||
const updateMask = [];
|
||||
for (const key in authResponse) {
|
||||
if (authResponse.hasOwnProperty(key) && typeof authResponse[key] !== "undefined") {
|
||||
updateMask.push(key);
|
||||
}
|
||||
}
|
||||
return updateMask.join(",");
|
||||
}
|
||||
exports.getUpdateMask = getUpdateMask;
|
||||
/** @internal */
|
||||
function wrapHandler(eventType, handler) {
|
||||
return async (req, res) => {
|
||||
try {
|
||||
const projectId = process.env.GCLOUD_PROJECT;
|
||||
if (!isValidRequest(req)) {
|
||||
logger.error("Invalid request, unable to process");
|
||||
throw new https_1.HttpsError("invalid-argument", "Bad Request");
|
||||
}
|
||||
if (!auth.getAuth((0, app_1.getApp)())._verifyAuthBlockingToken) {
|
||||
throw new Error("Cannot validate Auth Blocking token. Please update Firebase Admin SDK to >= v10.1.0");
|
||||
}
|
||||
const decodedPayload = (0, debug_1.isDebugFeatureEnabled)("skipTokenVerification")
|
||||
? unsafeDecodeAuthBlockingToken(req.body.data.jwt)
|
||||
: handler.platform === "gcfv1"
|
||||
? await auth.getAuth((0, app_1.getApp)())._verifyAuthBlockingToken(req.body.data.jwt)
|
||||
: await auth.getAuth((0, app_1.getApp)())._verifyAuthBlockingToken(req.body.data.jwt, "run.app");
|
||||
let authUserRecord;
|
||||
if (decodedPayload.event_type === "beforeCreate" ||
|
||||
decodedPayload.event_type === "beforeSignIn") {
|
||||
authUserRecord = parseAuthUserRecord(decodedPayload.user_record);
|
||||
}
|
||||
const authEventContext = parseAuthEventContext(decodedPayload, projectId);
|
||||
let authResponse;
|
||||
if (handler.platform === "gcfv1") {
|
||||
authResponse = authUserRecord
|
||||
? (await handler(authUserRecord, authEventContext)) || undefined
|
||||
: (await handler(authEventContext)) || undefined;
|
||||
}
|
||||
else {
|
||||
authResponse =
|
||||
(await handler({
|
||||
...authEventContext,
|
||||
data: authUserRecord,
|
||||
})) || undefined;
|
||||
}
|
||||
validateAuthResponse(eventType, authResponse);
|
||||
const result = generateResponsePayload(authResponse);
|
||||
res.status(200);
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.send(JSON.stringify(result));
|
||||
}
|
||||
catch (err) {
|
||||
let httpErr = err;
|
||||
if (!(httpErr instanceof https_1.HttpsError)) {
|
||||
// This doesn't count as an 'explicit' error.
|
||||
logger.error("Unhandled error", err);
|
||||
httpErr = new https_1.HttpsError("internal", "An unexpected error occurred.");
|
||||
}
|
||||
const { status } = httpErr.httpErrorCode;
|
||||
const body = { error: httpErr.toJSON() };
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.status(status).send(body);
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.wrapHandler = wrapHandler;
|
||||
112
node_modules/firebase-functions/lib/common/providers/tasks.d.ts
generated
vendored
Normal file
112
node_modules/firebase-functions/lib/common/providers/tasks.d.ts
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
import { DecodedIdToken } from "firebase-admin/auth";
|
||||
import { Expression } from "../../params";
|
||||
import { ResetValue } from "../options";
|
||||
/** How a task should be retried in the event of a non-2xx return. */
|
||||
export interface RetryConfig {
|
||||
/**
|
||||
* Maximum number of times a request should be attempted.
|
||||
* If left unspecified, will default to 3.
|
||||
*/
|
||||
maxAttempts?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Maximum amount of time for retrying failed task.
|
||||
* If left unspecified will retry indefinitely.
|
||||
*/
|
||||
maxRetrySeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* The maximum amount of time to wait between attempts.
|
||||
* If left unspecified will default to 1hr.
|
||||
*/
|
||||
maxBackoffSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* The maximum number of times to double the backoff between
|
||||
* retries. If left unspecified will default to 16.
|
||||
*/
|
||||
maxDoublings?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* The minimum time to wait between attempts. If left unspecified
|
||||
* will default to 100ms.
|
||||
*/
|
||||
minBackoffSeconds?: number | Expression<number> | ResetValue;
|
||||
}
|
||||
/** How congestion control should be applied to the function. */
|
||||
export interface RateLimits {
|
||||
/**
|
||||
* The maximum number of requests that can be processed at a time.
|
||||
* If left unspecified, will default to 1000.
|
||||
*/
|
||||
maxConcurrentDispatches?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* The maximum number of requests that can be invoked per second.
|
||||
* If left unspecified, will default to 500.
|
||||
*/
|
||||
maxDispatchesPerSecond?: number | Expression<number> | ResetValue;
|
||||
}
|
||||
/** Metadata about the authorization used to invoke a function. */
|
||||
export interface AuthData {
|
||||
uid: string;
|
||||
token: DecodedIdToken;
|
||||
}
|
||||
/** Metadata about a call to a Task Queue function. */
|
||||
export interface TaskContext {
|
||||
/**
|
||||
* The result of decoding and verifying an ODIC token.
|
||||
*/
|
||||
auth?: AuthData;
|
||||
/**
|
||||
* The name of the queue.
|
||||
* Populated via the `X-CloudTasks-QueueName` header.
|
||||
*/
|
||||
queueName: string;
|
||||
/**
|
||||
* The "short" name of the task, or, if no name was specified at creation, a unique
|
||||
* system-generated id.
|
||||
* This is the "my-task-id" value in the complete task name, such as "task_name =
|
||||
* projects/my-project-id/locations/my-location/queues/my-queue-id/tasks/my-task-id."
|
||||
* Populated via the `X-CloudTasks-TaskName` header.
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* The number of times this task has been retried.
|
||||
* For the first attempt, this value is 0. This number includes attempts where the task failed
|
||||
* due to 5XX error codes and never reached the execution phase.
|
||||
* Populated via the `X-CloudTasks-TaskRetryCount` header.
|
||||
*/
|
||||
retryCount: number;
|
||||
/**
|
||||
* The total number of times that the task has received a response from the handler.
|
||||
* Since Cloud Tasks deletes the task once a successful response has been received, all
|
||||
* previous handler responses were failures. This number does not include failures due to 5XX
|
||||
* error codes.
|
||||
* Populated via the `X-CloudTasks-TaskExecutionCount` header.
|
||||
*/
|
||||
executionCount: number;
|
||||
/**
|
||||
* The schedule time of the task, as an RFC 3339 string in UTC time zone.
|
||||
* Populated via the `X-CloudTasks-TaskETA` header, which uses seconds since January 1 1970.
|
||||
*/
|
||||
scheduledTime: string;
|
||||
/**
|
||||
* The HTTP response code from the previous retry.
|
||||
* Populated via the `X-CloudTasks-TaskPreviousResponse` header
|
||||
*/
|
||||
previousResponse?: number;
|
||||
/**
|
||||
* The reason for retrying the task.
|
||||
* Populated via the `X-CloudTasks-TaskRetryReason` header.
|
||||
*/
|
||||
retryReason?: string;
|
||||
/**
|
||||
* Raw request headers.
|
||||
*/
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
/**
|
||||
* The request used to call a task queue function.
|
||||
*/
|
||||
export type Request<T = any> = TaskContext & {
|
||||
/**
|
||||
* The parameters used by a client when calling this function.
|
||||
*/
|
||||
data: T;
|
||||
};
|
||||
100
node_modules/firebase-functions/lib/common/providers/tasks.js
generated
vendored
Normal file
100
node_modules/firebase-functions/lib/common/providers/tasks.js
generated
vendored
Normal file
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.onDispatchHandler = void 0;
|
||||
const logger = require("../../logger");
|
||||
const https = require("./https");
|
||||
/** @internal */
|
||||
function onDispatchHandler(handler) {
|
||||
return async (req, res) => {
|
||||
var _a;
|
||||
try {
|
||||
if (!https.isValidRequest(req)) {
|
||||
logger.error("Invalid request, unable to process.");
|
||||
throw new https.HttpsError("invalid-argument", "Bad Request");
|
||||
}
|
||||
const headers = {};
|
||||
for (const [key, value] of Object.entries(req.headers)) {
|
||||
if (!Array.isArray(value)) {
|
||||
headers[key] = value;
|
||||
}
|
||||
}
|
||||
const context = {
|
||||
queueName: req.header("X-CloudTasks-QueueName"),
|
||||
id: req.header("X-CloudTasks-TaskName"),
|
||||
retryCount: req.header("X-CloudTasks-TaskRetryCount")
|
||||
? Number(req.header("X-CloudTasks-TaskRetryCount"))
|
||||
: undefined,
|
||||
executionCount: req.header("X-CloudTasks-TaskExecutionCount")
|
||||
? Number(req.header("X-CloudTasks-TaskExecutionCount"))
|
||||
: undefined,
|
||||
scheduledTime: req.header("X-CloudTasks-TaskETA"),
|
||||
previousResponse: req.header("X-CloudTasks-TaskPreviousResponse")
|
||||
? Number(req.header("X-CloudTasks-TaskPreviousResponse"))
|
||||
: undefined,
|
||||
retryReason: req.header("X-CloudTasks-TaskRetryReason"),
|
||||
headers,
|
||||
};
|
||||
if (!process.env.FUNCTIONS_EMULATOR) {
|
||||
const authHeader = req.header("Authorization") || "";
|
||||
const token = (_a = authHeader.match(/^Bearer (.*)$/)) === null || _a === void 0 ? void 0 : _a[1];
|
||||
// Note: this should never happen since task queue functions are guarded by IAM.
|
||||
if (!token) {
|
||||
throw new https.HttpsError("unauthenticated", "Unauthenticated");
|
||||
}
|
||||
// We skip authenticating the token since tq functions are guarded by IAM.
|
||||
const authToken = https.unsafeDecodeIdToken(token);
|
||||
context.auth = {
|
||||
uid: authToken.uid,
|
||||
token: authToken,
|
||||
};
|
||||
}
|
||||
const data = https.decode(req.body.data);
|
||||
if (handler.length === 2) {
|
||||
await handler(data, context);
|
||||
}
|
||||
else {
|
||||
const arg = {
|
||||
...context,
|
||||
data,
|
||||
};
|
||||
// For some reason the type system isn't picking up that the handler
|
||||
// is a one argument function.
|
||||
await handler(arg);
|
||||
}
|
||||
res.status(204).end();
|
||||
}
|
||||
catch (err) {
|
||||
let httpErr = err;
|
||||
if (!(err instanceof https.HttpsError)) {
|
||||
// This doesn't count as an 'explicit' error.
|
||||
logger.error("Unhandled error", err);
|
||||
httpErr = new https.HttpsError("internal", "INTERNAL");
|
||||
}
|
||||
const { status } = httpErr.httpErrorCode;
|
||||
const body = { error: httpErr.toJSON() };
|
||||
res.status(status).send(body);
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.onDispatchHandler = onDispatchHandler;
|
||||
2
node_modules/firebase-functions/lib/common/timezone.d.ts
generated
vendored
Normal file
2
node_modules/firebase-functions/lib/common/timezone.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export declare const tzDatabase: Record<string, string>;
|
||||
export type timezone = keyof typeof tzDatabase;
|
||||
543
node_modules/firebase-functions/lib/common/timezone.js
generated
vendored
Normal file
543
node_modules/firebase-functions/lib/common/timezone.js
generated
vendored
Normal file
@@ -0,0 +1,543 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.tzDatabase = void 0;
|
||||
exports.tzDatabase = {
|
||||
"Africa/Abidjan": "+00:00",
|
||||
"Africa/Accra": "+00:00",
|
||||
"Africa/Addis_Ababa": "+03:00",
|
||||
"Africa/Algiers": "+01:00",
|
||||
"Africa/Asmara": "+03:00",
|
||||
"Africa/Asmera": "+03:00",
|
||||
"Africa/Bamako": "+00:00",
|
||||
"Africa/Bangui": "+01:00",
|
||||
"Africa/Banjul": "+00:00",
|
||||
"Africa/Blantyre": "+02:00",
|
||||
"Africa/Brazzaville": "+01:00",
|
||||
"Africa/Bujumbura": "+02:00",
|
||||
"Africa/Cairo": "+02:00",
|
||||
"Africa/Casablanca": "+00:00",
|
||||
"Africa/Ceuta": "+01:00",
|
||||
"Africa/Conakry": "+00:00",
|
||||
"Africa/Dakar": "+00:00",
|
||||
"Africa/Dar_es_Salaam": "+03:00",
|
||||
"Africa/Djibouti": "+03:00",
|
||||
"Africa/Douala": "+01:00",
|
||||
"Africa/El_Aaiun": "+00:00",
|
||||
"Africa/Freetown": "+00:00",
|
||||
"Africa/Gaborone": "+02:00",
|
||||
"Africa/Harare": "+02:00",
|
||||
"Africa/Johannesburg": "+02:00",
|
||||
"Africa/Juba": "+03:00",
|
||||
"Africa/Kampala": "+03:00",
|
||||
"Africa/Khartoum": "+03:00",
|
||||
"Africa/Kigali": "+02:00",
|
||||
"Africa/Kinshasa": "+01:00",
|
||||
"Africa/Lagos": "+01:00",
|
||||
"Africa/Libreville": "+01:00",
|
||||
"Africa/Lome": "+00:00",
|
||||
"Africa/Luanda": "+01:00",
|
||||
"Africa/Lubumbashi": "+02:00",
|
||||
"Africa/Lusaka": "+02:00",
|
||||
"Africa/Malabo": "+01:00",
|
||||
"Africa/Maputo": "+02:00",
|
||||
"Africa/Maseru": "+02:00",
|
||||
"Africa/Mbabane": "+02:00",
|
||||
"Africa/Mogadishu": "+03:00",
|
||||
"Africa/Monrovia": "+00:00",
|
||||
"Africa/Nairobi": "+03:00",
|
||||
"Africa/Ndjamena": "+01:00",
|
||||
"Africa/Niamey": "+01:00",
|
||||
"Africa/Nouakchott": "+00:00",
|
||||
"Africa/Ouagadougou": "+00:00",
|
||||
"Africa/Porto-Novo": "+01:00",
|
||||
"Africa/Sao_Tome": "+00:00",
|
||||
"Africa/Timbuktu": "+00:00",
|
||||
"Africa/Tripoli": "+02:00",
|
||||
"Africa/Tunis": "+01:00",
|
||||
"Africa/Windhoek": "+01:00",
|
||||
"America/Adak": "-10:00",
|
||||
"America/Anchorage": "-09:00",
|
||||
"America/Anguilla": "-04:00",
|
||||
"America/Antigua": "-04:00",
|
||||
"America/Araguaina": "-03:00",
|
||||
"America/Argentina/Buenos_Aires": "-03:00",
|
||||
"America/Argentina/Catamarca": "-03:00",
|
||||
"America/Argentina/ComodRivadavia": "-03:00",
|
||||
"America/Argentina/Cordoba": "-03:00",
|
||||
"America/Argentina/Jujuy": "-03:00",
|
||||
"America/Argentina/La_Rioja": "-03:00",
|
||||
"America/Argentina/Mendoza": "-03:00",
|
||||
"America/Argentina/Rio_Gallegos": "-03:00",
|
||||
"America/Argentina/Salta": "-03:00",
|
||||
"America/Argentina/San_Juan": "-03:00",
|
||||
"America/Argentina/San_Luis": "-03:00",
|
||||
"America/Argentina/Tucuman": "-03:00",
|
||||
"America/Argentina/Ushuaia": "-03:00",
|
||||
"America/Aruba": "-04:00",
|
||||
"America/Asuncion": "-04:00",
|
||||
"America/Atikokan": "-05:00",
|
||||
"America/Atka": "-10:00",
|
||||
"America/Bahia": "-03:00",
|
||||
"America/Bahia_Banderas": "-06:00",
|
||||
"America/Barbados": "-04:00",
|
||||
"America/Belem": "-03:00",
|
||||
"America/Belize": "-06:00",
|
||||
"America/Blanc-Sablon": "-04:00",
|
||||
"America/Boa_Vista": "-04:00",
|
||||
"America/Bogota": "-05:00",
|
||||
"America/Boise": "-07:00",
|
||||
"America/Buenos_Aires": "-03:00",
|
||||
"America/Cambridge_Bay": "-07:00",
|
||||
"America/Campo_Grande": "-04:00",
|
||||
"America/Cancun": "-06:00",
|
||||
"America/Caracas": "-04:30",
|
||||
"America/Catamarca": "-03:00",
|
||||
"America/Cayenne": "-03:00",
|
||||
"America/Cayman": "-05:00",
|
||||
"America/Chicago": "-06:00",
|
||||
"America/Chihuahua": "-07:00",
|
||||
"America/Coral_Harbour": "-05:00",
|
||||
"America/Cordoba": "-03:00",
|
||||
"America/Costa_Rica": "-06:00",
|
||||
"America/Creston": "-07:00",
|
||||
"America/Cuiaba": "-04:00",
|
||||
"America/Curacao": "-04:00",
|
||||
"America/Danmarkshavn": "+00:00",
|
||||
"America/Dawson": "-08:00",
|
||||
"America/Dawson_Creek": "-07:00",
|
||||
"America/Denver": "-07:00",
|
||||
"America/Detroit": "-05:00",
|
||||
"America/Dominica": "-04:00",
|
||||
"America/Edmonton": "-07:00",
|
||||
"America/Eirunepe": "-05:00",
|
||||
"America/El_Salvador": "-06:00",
|
||||
"America/Ensenada": "-08:00",
|
||||
"America/Fort_Wayne": "-05:00",
|
||||
"America/Fortaleza": "-03:00",
|
||||
"America/Glace_Bay": "-04:00",
|
||||
"America/Godthab": "-03:00",
|
||||
"America/Goose_Bay": "-04:00",
|
||||
"America/Grand_Turk": "-05:00",
|
||||
"America/Grenada": "-04:00",
|
||||
"America/Guadeloupe": "-04:00",
|
||||
"America/Guatemala": "-06:00",
|
||||
"America/Guayaquil": "-05:00",
|
||||
"America/Guyana": "-04:00",
|
||||
"America/Halifax": "-04:00",
|
||||
"America/Havana": "-05:00",
|
||||
"America/Hermosillo": "-07:00",
|
||||
"America/Indiana/Indianapolis": "-05:00",
|
||||
"America/Indiana/Knox": "-06:00",
|
||||
"America/Indiana/Marengo": "-05:00",
|
||||
"America/Indiana/Petersburg": "-05:00",
|
||||
"America/Indiana/Tell_City": "-06:00",
|
||||
"America/Indiana/Valparaiso": "-06:00",
|
||||
"America/Indiana/Vevay": "-05:00",
|
||||
"America/Indiana/Vincennes": "-05:00",
|
||||
"America/Indiana/Winamac": "-05:00",
|
||||
"America/Indianapolis": "-05:00",
|
||||
"America/Inuvik": "-07:00",
|
||||
"America/Iqaluit": "-05:00",
|
||||
"America/Jamaica": "-05:00",
|
||||
"America/Jujuy": "-03:00",
|
||||
"America/Juneau": "-09:00",
|
||||
"America/Kentucky/Louisville": "-05:00",
|
||||
"America/Kentucky/Monticello": "-05:00",
|
||||
"America/Knox_IN": "-06:00",
|
||||
"America/Kralendijk": "-04:00",
|
||||
"America/La_Paz": "-04:00",
|
||||
"America/Lima": "-05:00",
|
||||
"America/Los_Angeles": "-08:00",
|
||||
"America/Louisville": "-05:00",
|
||||
"America/Lower_Princes": "-04:00",
|
||||
"America/Maceio": "-03:00",
|
||||
"America/Managua": "-06:00",
|
||||
"America/Manaus": "-04:00",
|
||||
"America/Marigot": "-04:00",
|
||||
"America/Martinique": "-04:00",
|
||||
"America/Matamoros": "-06:00",
|
||||
"America/Mazatlan": "-07:00",
|
||||
"America/Mendoza": "-03:00",
|
||||
"America/Menominee": "-06:00",
|
||||
"America/Merida": "-06:00",
|
||||
"America/Metlakatla": "-08:00",
|
||||
"America/Mexico_City": "-06:00",
|
||||
"America/Miquelon": "-03:00",
|
||||
"America/Moncton": "-04:00",
|
||||
"America/Monterrey": "-06:00",
|
||||
"America/Montevideo": "-03:00",
|
||||
"America/Montreal": "-05:00",
|
||||
"America/Montserrat": "-04:00",
|
||||
"America/Nassau": "-05:00",
|
||||
"America/New_York": "-05:00",
|
||||
"America/Nipigon": "-05:00",
|
||||
"America/Nome": "-09:00",
|
||||
"America/Noronha": "-02:00",
|
||||
"America/North_Dakota/Beulah": "-06:00",
|
||||
"America/North_Dakota/Center": "-06:00",
|
||||
"America/North_Dakota/New_Salem": "-06:00",
|
||||
"America/Ojinaga": "-07:00",
|
||||
"America/Panama": "-05:00",
|
||||
"America/Pangnirtung": "-05:00",
|
||||
"America/Paramaribo": "-03:00",
|
||||
"America/Phoenix": "-07:00",
|
||||
"America/Port_of_Spain": "-04:00",
|
||||
"America/Port-au-Prince": "-05:00",
|
||||
"America/Porto_Acre": "-05:00",
|
||||
"America/Porto_Velho": "-04:00",
|
||||
"America/Puerto_Rico": "-04:00",
|
||||
"America/Rainy_River": "-06:00",
|
||||
"America/Rankin_Inlet": "-06:00",
|
||||
"America/Recife": "-03:00",
|
||||
"America/Regina": "-06:00",
|
||||
"America/Resolute": "-06:00",
|
||||
"America/Rio_Branco": "-05:00",
|
||||
"America/Rosario": "-03:00",
|
||||
"America/Santa_Isabel": "-08:00",
|
||||
"America/Santarem": "-03:00",
|
||||
"America/Santiago": "-03:00",
|
||||
"America/Santo_Domingo": "-04:00",
|
||||
"America/Sao_Paulo": "-03:00",
|
||||
"America/Scoresbysund": "-01:00",
|
||||
"America/Shiprock": "-07:00",
|
||||
"America/Sitka": "-09:00",
|
||||
"America/St_Barthelemy": "-04:00",
|
||||
"America/St_Johns": "-03:30",
|
||||
"America/St_Kitts": "-04:00",
|
||||
"America/St_Lucia": "-04:00",
|
||||
"America/St_Thomas": "-04:00",
|
||||
"America/St_Vincent": "-04:00",
|
||||
"America/Swift_Current": "-06:00",
|
||||
"America/Tegucigalpa": "-06:00",
|
||||
"America/Thule": "-04:00",
|
||||
"America/Thunder_Bay": "-05:00",
|
||||
"America/Tijuana": "-08:00",
|
||||
"America/Toronto": "-05:00",
|
||||
"America/Tortola": "-04:00",
|
||||
"America/Vancouver": "-08:00",
|
||||
"America/Virgin": "-04:00",
|
||||
"America/Whitehorse": "-08:00",
|
||||
"America/Winnipeg": "-06:00",
|
||||
"America/Yakutat": "-09:00",
|
||||
"America/Yellowknife": "-07:00",
|
||||
"Antarctica/Casey": "+11:00",
|
||||
"Antarctica/Davis": "+05:00",
|
||||
"Antarctica/DumontDUrville": "+10:00",
|
||||
"Antarctica/Macquarie": "+11:00",
|
||||
"Antarctica/Mawson": "+05:00",
|
||||
"Antarctica/McMurdo": "+12:00",
|
||||
"Antarctica/Palmer": "-04:00",
|
||||
"Antarctica/Rothera": "-03:00",
|
||||
"Antarctica/South_Pole": "+12:00",
|
||||
"Antarctica/Syowa": "+03:00",
|
||||
"Antarctica/Troll": "+00:00",
|
||||
"Antarctica/Vostok": "+06:00",
|
||||
"Arctic/Longyearbyen": "+01:00",
|
||||
"Asia/Aden": "+03:00",
|
||||
"Asia/Almaty": "+06:00",
|
||||
"Asia/Amman": "+02:00",
|
||||
"Asia/Anadyr": "+12:00",
|
||||
"Asia/Aqtau": "+05:00",
|
||||
"Asia/Aqtobe": "+05:00",
|
||||
"Asia/Ashgabat": "+05:00",
|
||||
"Asia/Ashkhabad": "+05:00",
|
||||
"Asia/Baghdad": "+03:00",
|
||||
"Asia/Bahrain": "+03:00",
|
||||
"Asia/Baku": "+04:00",
|
||||
"Asia/Bangkok": "+07:00",
|
||||
"Asia/Beirut": "+02:00",
|
||||
"Asia/Bishkek": "+06:00",
|
||||
"Asia/Brunei": "+08:00",
|
||||
"Asia/Calcutta": "+05:30",
|
||||
"Asia/Choibalsan": "+08:00",
|
||||
"Asia/Chongqing": "+08:00",
|
||||
"Asia/Chungking": "+08:00",
|
||||
"Asia/Colombo": "+05:30",
|
||||
"Asia/Dacca": "+06:00",
|
||||
"Asia/Damascus": "+02:00",
|
||||
"Asia/Dhaka": "+06:00",
|
||||
"Asia/Dili": "+09:00",
|
||||
"Asia/Dubai": "+04:00",
|
||||
"Asia/Dushanbe": "+05:00",
|
||||
"Asia/Gaza": "+02:00",
|
||||
"Asia/Harbin": "+08:00",
|
||||
"Asia/Hebron": "+02:00",
|
||||
"Asia/Ho_Chi_Minh": "+07:00",
|
||||
"Asia/Hong_Kong": "+08:00",
|
||||
"Asia/Hovd": "+07:00",
|
||||
"Asia/Irkutsk": "+08:00",
|
||||
"Asia/Istanbul": "+02:00",
|
||||
"Asia/Jakarta": "+07:00",
|
||||
"Asia/Jayapura": "+09:00",
|
||||
"Asia/Jerusalem": "+02:00",
|
||||
"Asia/Kabul": "+04:30",
|
||||
"Asia/Kamchatka": "+12:00",
|
||||
"Asia/Karachi": "+05:00",
|
||||
"Asia/Kashgar": "+08:00",
|
||||
"Asia/Kathmandu": "+05:45",
|
||||
"Asia/Katmandu": "+05:45",
|
||||
"Asia/Khandyga": "+09:00",
|
||||
"Asia/Kolkata": "+05:30",
|
||||
"Asia/Krasnoyarsk": "+07:00",
|
||||
"Asia/Kuala_Lumpur": "+08:00",
|
||||
"Asia/Kuching": "+08:00",
|
||||
"Asia/Kuwait": "+03:00",
|
||||
"Asia/Macao": "+08:00",
|
||||
"Asia/Macau": "+08:00",
|
||||
"Asia/Magadan": "+10:00",
|
||||
"Asia/Makassar": "+08:00",
|
||||
"Asia/Manila": "+08:00",
|
||||
"Asia/Muscat": "+04:00",
|
||||
"Asia/Nicosia": "+02:00",
|
||||
"Asia/Novokuznetsk": "+07:00",
|
||||
"Asia/Novosibirsk": "+06:00",
|
||||
"Asia/Omsk": "+06:00",
|
||||
"Asia/Oral": "+05:00",
|
||||
"Asia/Phnom_Penh": "+07:00",
|
||||
"Asia/Pontianak": "+07:00",
|
||||
"Asia/Pyongyang": "+09:00",
|
||||
"Asia/Qatar": "+03:00",
|
||||
"Asia/Qyzylorda": "+06:00",
|
||||
"Asia/Rangoon": "+06:30",
|
||||
"Asia/Riyadh": "+03:00",
|
||||
"Asia/Saigon": "+07:00",
|
||||
"Asia/Sakhalin": "+11:00",
|
||||
"Asia/Samarkand": "+05:00",
|
||||
"Asia/Seoul": "+09:00",
|
||||
"Asia/Shanghai": "+08:00",
|
||||
"Asia/Singapore": "+08:00",
|
||||
"Asia/Taipei": "+08:00",
|
||||
"Asia/Tashkent": "+05:00",
|
||||
"Asia/Tbilisi": "+04:00",
|
||||
"Asia/Tehran": "+03:30",
|
||||
"Asia/Tel_Aviv": "+02:00",
|
||||
"Asia/Thimbu": "+06:00",
|
||||
"Asia/Thimphu": "+06:00",
|
||||
"Asia/Tokyo": "+09:00",
|
||||
"Asia/Ujung_Pandang": "+08:00",
|
||||
"Asia/Ulaanbaatar": "+08:00",
|
||||
"Asia/Ulan_Bator": "+08:00",
|
||||
"Asia/Urumqi": "+08:00",
|
||||
"Asia/Ust-Nera": "+10:00",
|
||||
"Asia/Vientiane": "+07:00",
|
||||
"Asia/Vladivostok": "+10:00",
|
||||
"Asia/Yakutsk": "+09:00",
|
||||
"Asia/Yekaterinburg": "+05:00",
|
||||
"Asia/Yerevan": "+04:00",
|
||||
"Atlantic/Azores": "-01:00",
|
||||
"Atlantic/Bermuda": "-04:00",
|
||||
"Atlantic/Canary": "+00:00",
|
||||
"Atlantic/Cape_Verde": "-01:00",
|
||||
"Atlantic/Faeroe": "+00:00",
|
||||
"Atlantic/Faroe": "+00:00",
|
||||
"Atlantic/Jan_Mayen": "+01:00",
|
||||
"Atlantic/Madeira": "+00:00",
|
||||
"Atlantic/Reykjavik": "+00:00",
|
||||
"Atlantic/South_Georgia": "-02:00",
|
||||
"Atlantic/St_Helena": "+00:00",
|
||||
"Atlantic/Stanley": "-03:00",
|
||||
"Australia/ACT": "+10:00",
|
||||
"Australia/Adelaide": "+09:30",
|
||||
"Australia/Brisbane": "+10:00",
|
||||
"Australia/Broken_Hill": "+09:30",
|
||||
"Australia/Canberra": "+10:00",
|
||||
"Australia/Currie": "+10:00",
|
||||
"Australia/Darwin": "+09:30",
|
||||
"Australia/Eucla": "+08:45",
|
||||
"Australia/Hobart": "+10:00",
|
||||
"Australia/LHI": "+10:30",
|
||||
"Australia/Lindeman": "+10:00",
|
||||
"Australia/Lord_Howe": "+10:30",
|
||||
"Australia/Melbourne": "+10:00",
|
||||
"Australia/North": "+09:30",
|
||||
"Australia/NSW": "+10:00",
|
||||
"Australia/Perth": "+08:00",
|
||||
"Australia/Queensland": "+10:00",
|
||||
"Australia/South": "+09:30",
|
||||
"Australia/Sydney": "+10:00",
|
||||
"Australia/Tasmania": "+10:00",
|
||||
"Australia/Victoria": "+10:00",
|
||||
"Australia/West": "+08:00",
|
||||
"Australia/Yancowinna": "+09:30",
|
||||
"Brazil/Acre": "-05:00",
|
||||
"Brazil/DeNoronha": "-02:00",
|
||||
"Brazil/East": "-03:00",
|
||||
"Brazil/West": "-04:00",
|
||||
"Canada/Atlantic": "-04:00",
|
||||
"Canada/Central": "-06:00",
|
||||
"Canada/Eastern": "-05:00",
|
||||
"Canada/East-Saskatchewan": "-06:00",
|
||||
"Canada/Mountain": "-07:00",
|
||||
"Canada/Newfoundland": "-03:30",
|
||||
"Canada/Pacific": "-08:00",
|
||||
"Canada/Saskatchewan": "-06:00",
|
||||
"Canada/Yukon": "-08:00",
|
||||
"Chile/Continental": "-03:00",
|
||||
"Chile/EasterIsland": "-05:00",
|
||||
Cuba: "-05:00",
|
||||
Egypt: "+02:00",
|
||||
Eire: "+00:00",
|
||||
"Etc/GMT": "+00:00",
|
||||
"Etc/GMT+0": "+00:00",
|
||||
"Etc/UCT": "+00:00",
|
||||
"Etc/Universal": "+00:00",
|
||||
"Etc/UTC": "+00:00",
|
||||
"Etc/Zulu": "+00:00",
|
||||
"Europe/Amsterdam": "+01:00",
|
||||
"Europe/Andorra": "+01:00",
|
||||
"Europe/Athens": "+02:00",
|
||||
"Europe/Belfast": "+00:00",
|
||||
"Europe/Belgrade": "+01:00",
|
||||
"Europe/Berlin": "+01:00",
|
||||
"Europe/Bratislava": "+01:00",
|
||||
"Europe/Brussels": "+01:00",
|
||||
"Europe/Bucharest": "+02:00",
|
||||
"Europe/Budapest": "+01:00",
|
||||
"Europe/Busingen": "+01:00",
|
||||
"Europe/Chisinau": "+02:00",
|
||||
"Europe/Copenhagen": "+01:00",
|
||||
"Europe/Dublin": "+00:00",
|
||||
"Europe/Gibraltar": "+01:00",
|
||||
"Europe/Guernsey": "+00:00",
|
||||
"Europe/Helsinki": "+02:00",
|
||||
"Europe/Isle_of_Man": "+00:00",
|
||||
"Europe/Istanbul": "+02:00",
|
||||
"Europe/Jersey": "+00:00",
|
||||
"Europe/Kaliningrad": "+02:00",
|
||||
"Europe/Kiev": "+02:00",
|
||||
"Europe/Lisbon": "+00:00",
|
||||
"Europe/Ljubljana": "+01:00",
|
||||
"Europe/London": "+00:00",
|
||||
"Europe/Luxembourg": "+01:00",
|
||||
"Europe/Madrid": "+01:00",
|
||||
"Europe/Malta": "+01:00",
|
||||
"Europe/Mariehamn": "+02:00",
|
||||
"Europe/Minsk": "+03:00",
|
||||
"Europe/Monaco": "+01:00",
|
||||
"Europe/Moscow": "+03:00",
|
||||
"Europe/Nicosia": "+02:00",
|
||||
"Europe/Oslo": "+01:00",
|
||||
"Europe/Paris": "+01:00",
|
||||
"Europe/Podgorica": "+01:00",
|
||||
"Europe/Prague": "+01:00",
|
||||
"Europe/Riga": "+02:00",
|
||||
"Europe/Rome": "+01:00",
|
||||
"Europe/Samara": "+04:00",
|
||||
"Europe/San_Marino": "+01:00",
|
||||
"Europe/Sarajevo": "+01:00",
|
||||
"Europe/Simferopol": "+03:00",
|
||||
"Europe/Skopje": "+01:00",
|
||||
"Europe/Sofia": "+02:00",
|
||||
"Europe/Stockholm": "+01:00",
|
||||
"Europe/Tallinn": "+02:00",
|
||||
"Europe/Tirane": "+01:00",
|
||||
"Europe/Tiraspol": "+02:00",
|
||||
"Europe/Uzhgorod": "+02:00",
|
||||
"Europe/Vaduz": "+01:00",
|
||||
"Europe/Vatican": "+01:00",
|
||||
"Europe/Vienna": "+01:00",
|
||||
"Europe/Vilnius": "+02:00",
|
||||
"Europe/Volgograd": "+03:00",
|
||||
"Europe/Warsaw": "+01:00",
|
||||
"Europe/Zagreb": "+01:00",
|
||||
"Europe/Zaporozhye": "+02:00",
|
||||
"Europe/Zurich": "+01:00",
|
||||
GB: "+00:00",
|
||||
"GB-Eire": "+00:00",
|
||||
GMT: "+00:00",
|
||||
"GMT+0": "+00:00",
|
||||
GMT0: "+00:00",
|
||||
"GMT-0": "+00:00",
|
||||
Greenwich: "+00:00",
|
||||
Hongkong: "+08:00",
|
||||
Iceland: "+00:00",
|
||||
"Indian/Antananarivo": "+03:00",
|
||||
"Indian/Chagos": "+06:00",
|
||||
"Indian/Christmas": "+07:00",
|
||||
"Indian/Cocos": "+06:30",
|
||||
"Indian/Comoro": "+03:00",
|
||||
"Indian/Kerguelen": "+05:00",
|
||||
"Indian/Mahe": "+04:00",
|
||||
"Indian/Maldives": "+05:00",
|
||||
"Indian/Mauritius": "+04:00",
|
||||
"Indian/Mayotte": "+03:00",
|
||||
"Indian/Reunion": "+04:00",
|
||||
Iran: "+03:30",
|
||||
Israel: "+02:00",
|
||||
Jamaica: "-05:00",
|
||||
Japan: "+09:00",
|
||||
Kwajalein: "+12:00",
|
||||
Libya: "+02:00",
|
||||
"Mexico/BajaNorte": "-08:00",
|
||||
"Mexico/BajaSur": "-07:00",
|
||||
"Mexico/General": "-06:00",
|
||||
Navajo: "-07:00",
|
||||
NZ: "+12:00",
|
||||
"NZ-CHAT": "+12:45",
|
||||
"Pacific/Apia": "+13:00",
|
||||
"Pacific/Auckland": "+12:00",
|
||||
"Pacific/Chatham": "+12:45",
|
||||
"Pacific/Chuuk": "+10:00",
|
||||
"Pacific/Easter": "-06:00",
|
||||
"Pacific/Efate": "+11:00",
|
||||
"Pacific/Enderbury": "+13:00",
|
||||
"Pacific/Fakaofo": "+13:00",
|
||||
"Pacific/Fiji": "+12:00",
|
||||
"Pacific/Funafuti": "+12:00",
|
||||
"Pacific/Galapagos": "-06:00",
|
||||
"Pacific/Gambier": "-09:00",
|
||||
"Pacific/Guadalcanal": "+11:00",
|
||||
"Pacific/Guam": "+10:00",
|
||||
"Pacific/Honolulu": "-10:00",
|
||||
"Pacific/Johnston": "-10:00",
|
||||
"Pacific/Kiritimati": "+14:00",
|
||||
"Pacific/Kosrae": "+11:00",
|
||||
"Pacific/Kwajalein": "+12:00",
|
||||
"Pacific/Majuro": "+12:00",
|
||||
"Pacific/Marquesas": "-09:30",
|
||||
"Pacific/Midway": "-11:00",
|
||||
"Pacific/Nauru": "+12:00",
|
||||
"Pacific/Niue": "-11:00",
|
||||
"Pacific/Norfolk": "+11:30",
|
||||
"Pacific/Noumea": "+11:00",
|
||||
"Pacific/Pago_Pago": "-11:00",
|
||||
"Pacific/Palau": "+09:00",
|
||||
"Pacific/Pitcairn": "-08:00",
|
||||
"Pacific/Pohnpei": "+11:00",
|
||||
"Pacific/Ponape": "+11:00",
|
||||
"Pacific/Port_Moresby": "+10:00",
|
||||
"Pacific/Rarotonga": "-10:00",
|
||||
"Pacific/Saipan": "+10:00",
|
||||
"Pacific/Samoa": "-11:00",
|
||||
"Pacific/Tahiti": "-10:00",
|
||||
"Pacific/Tarawa": "+12:00",
|
||||
"Pacific/Tongatapu": "+13:00",
|
||||
"Pacific/Truk": "+10:00",
|
||||
"Pacific/Wake": "+12:00",
|
||||
"Pacific/Wallis": "+12:00",
|
||||
"Pacific/Yap": "+10:00",
|
||||
Poland: "+01:00",
|
||||
Portugal: "+00:00",
|
||||
PRC: "+08:00",
|
||||
ROC: "+08:00",
|
||||
ROK: "+09:00",
|
||||
Singapore: "+08:00",
|
||||
Turkey: "+02:00",
|
||||
UCT: "+00:00",
|
||||
Universal: "+00:00",
|
||||
"US/Alaska": "-09:00",
|
||||
"US/Aleutian": "-10:00",
|
||||
"US/Arizona": "-07:00",
|
||||
"US/Central": "-06:00",
|
||||
"US/Eastern": "-05:00",
|
||||
"US/East-Indiana": "-05:00",
|
||||
"US/Hawaii": "-10:00",
|
||||
"US/Indiana-Starke": "-06:00",
|
||||
"US/Michigan": "-05:00",
|
||||
"US/Mountain": "-07:00",
|
||||
"US/Pacific": "-08:00",
|
||||
"US/Samoa": "-11:00",
|
||||
UTC: "+00:00",
|
||||
"W-SU": "+03:00",
|
||||
Zulu: "+00:00",
|
||||
};
|
||||
14
node_modules/firebase-functions/lib/common/trace.d.ts
generated
vendored
Normal file
14
node_modules/firebase-functions/lib/common/trace.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
export interface TraceContext {
|
||||
version: string;
|
||||
traceId: string;
|
||||
parentId: string;
|
||||
sample: boolean;
|
||||
}
|
||||
/**
|
||||
* Extracts trace context from given carrier object, if any.
|
||||
*
|
||||
* Supports Cloud Trace and traceparent format.
|
||||
*
|
||||
* @param carrier
|
||||
*/
|
||||
export declare function extractTraceContext(carrier: unknown): TraceContext | undefined;
|
||||
69
node_modules/firebase-functions/lib/common/trace.js
generated
vendored
Normal file
69
node_modules/firebase-functions/lib/common/trace.js
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.extractTraceContext = exports.traceContext = void 0;
|
||||
const async_hooks_1 = require("async_hooks");
|
||||
/* @internal */
|
||||
exports.traceContext = new async_hooks_1.AsyncLocalStorage();
|
||||
/**
|
||||
* A regex to match the Cloud Trace header.
|
||||
* - ([A-Fa-f0-9]{32}): The trace id, a 32 character hex value. (e.g. 4bf92f3577b34da6a3ce929d0e0e4736)
|
||||
* - ([0-9]+): The parent span id, a 64 bit integer. (e.g. 00f067aa0ba902b7)
|
||||
* - (?:;o=([0-3])): The trace mask, 1-3 denote it should be traced.
|
||||
*/
|
||||
const CLOUD_TRACE_REGEX = new RegExp("^(?<traceId>[A-Fa-f0-9]{32})/" + "(?<parentIdInt>[0-9]+)" + "(?:;o=(?<traceMask>[0-3]))?$");
|
||||
const CLOUD_TRACE_HEADER = "X-Cloud-Trace-Context";
|
||||
function matchCloudTraceHeader(carrier) {
|
||||
let header = carrier === null || carrier === void 0 ? void 0 : carrier[CLOUD_TRACE_HEADER];
|
||||
if (!header) {
|
||||
// try lowercase header
|
||||
header = carrier === null || carrier === void 0 ? void 0 : carrier[CLOUD_TRACE_HEADER.toLowerCase()];
|
||||
}
|
||||
if (header && typeof header === "string") {
|
||||
const matches = CLOUD_TRACE_REGEX.exec(header);
|
||||
if (matches && matches.groups) {
|
||||
const { traceId, parentIdInt, traceMask } = matches.groups;
|
||||
// Convert parentId from unsigned int to hex
|
||||
const parentId = parseInt(parentIdInt);
|
||||
if (isNaN(parentId)) {
|
||||
// Ignore traces with invalid parentIds
|
||||
return;
|
||||
}
|
||||
const sample = !!traceMask && traceMask !== "0";
|
||||
return { traceId, parentId: parentId.toString(16), sample, version: "00" };
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A regex to match the traceparent header.
|
||||
* - ^([a-f0-9]{2}): The specification version (e.g. 00)
|
||||
* - ([a-f0-9]{32}): The trace id, a 16-byte array. (e.g. 4bf92f3577b34da6a3ce929d0e0e4736)
|
||||
* - ([a-f0-9]{16}): The parent span id, an 8-byte array. (e.g. 00f067aa0ba902b7)
|
||||
* - ([a-f0-9]{2}: The sampled flag. (e.g. 00)
|
||||
*/
|
||||
const TRACEPARENT_REGEX = new RegExp("^(?<version>[a-f0-9]{2})-" +
|
||||
"(?<traceId>[a-f0-9]{32})-" +
|
||||
"(?<parentId>[a-f0-9]{16})-" +
|
||||
"(?<flag>[a-f0-9]{2})$");
|
||||
const TRACEPARENT_HEADER = "traceparent";
|
||||
function matchTraceparentHeader(carrier) {
|
||||
const header = carrier === null || carrier === void 0 ? void 0 : carrier[TRACEPARENT_HEADER];
|
||||
if (header && typeof header === "string") {
|
||||
const matches = TRACEPARENT_REGEX.exec(header);
|
||||
if (matches && matches.groups) {
|
||||
const { version, traceId, parentId, flag } = matches.groups;
|
||||
const sample = flag === "01";
|
||||
return { traceId, parentId, sample, version };
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Extracts trace context from given carrier object, if any.
|
||||
*
|
||||
* Supports Cloud Trace and traceparent format.
|
||||
*
|
||||
* @param carrier
|
||||
*/
|
||||
function extractTraceContext(carrier) {
|
||||
return matchCloudTraceHeader(carrier) || matchTraceparentHeader(carrier);
|
||||
}
|
||||
exports.extractTraceContext = extractTraceContext;
|
||||
4
node_modules/firebase-functions/lib/common/utilities/encoder.d.ts
generated
vendored
Normal file
4
node_modules/firebase-functions/lib/common/utilities/encoder.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
export declare function dateToTimestampProto(timeString?: string): {
|
||||
seconds: number;
|
||||
nanos: number;
|
||||
};
|
||||
39
node_modules/firebase-functions/lib/common/utilities/encoder.js
generated
vendored
Normal file
39
node_modules/firebase-functions/lib/common/utilities/encoder.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.dateToTimestampProto = void 0;
|
||||
function dateToTimestampProto(timeString) {
|
||||
if (typeof timeString === "undefined") {
|
||||
return;
|
||||
}
|
||||
const date = new Date(timeString);
|
||||
const seconds = Math.floor(date.getTime() / 1000);
|
||||
let nanos = 0;
|
||||
if (timeString.length > 20) {
|
||||
const nanoString = timeString.substring(20, timeString.length - 1);
|
||||
const trailingZeroes = 9 - nanoString.length;
|
||||
nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes);
|
||||
}
|
||||
return { seconds, nanos };
|
||||
}
|
||||
exports.dateToTimestampProto = dateToTimestampProto;
|
||||
1
node_modules/firebase-functions/lib/common/utilities/path-pattern.d.ts
generated
vendored
Normal file
1
node_modules/firebase-functions/lib/common/utilities/path-pattern.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
143
node_modules/firebase-functions/lib/common/utilities/path-pattern.js
generated
vendored
Normal file
143
node_modules/firebase-functions/lib/common/utilities/path-pattern.js
generated
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PathPattern = exports.trimParam = void 0;
|
||||
const path_1 = require("./path");
|
||||
/** https://cloud.google.com/eventarc/docs/path-patterns */
|
||||
/** @hidden */
|
||||
const WILDCARD_CAPTURE_REGEX = new RegExp("{[^/{}]+}", "g");
|
||||
/** @internal */
|
||||
function trimParam(param) {
|
||||
const paramNoBraces = param.slice(1, -1);
|
||||
if (paramNoBraces.includes("=")) {
|
||||
return paramNoBraces.slice(0, paramNoBraces.indexOf("="));
|
||||
}
|
||||
return paramNoBraces;
|
||||
}
|
||||
exports.trimParam = trimParam;
|
||||
/** @hidden */
|
||||
class Segment {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
this.name = "segment";
|
||||
this.trimmed = value;
|
||||
}
|
||||
isSingleSegmentWildcard() {
|
||||
return this.value.includes("*") && !this.isMultiSegmentWildcard();
|
||||
}
|
||||
isMultiSegmentWildcard() {
|
||||
return this.value.includes("**");
|
||||
}
|
||||
}
|
||||
/** @hidden */
|
||||
class SingleCaptureSegment {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
this.name = "single-capture";
|
||||
this.trimmed = trimParam(value);
|
||||
}
|
||||
isSingleSegmentWildcard() {
|
||||
return true;
|
||||
}
|
||||
isMultiSegmentWildcard() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** @hidden */
|
||||
class MultiCaptureSegment {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
this.name = "multi-capture";
|
||||
this.trimmed = trimParam(value);
|
||||
}
|
||||
isSingleSegmentWildcard() {
|
||||
return false;
|
||||
}
|
||||
isMultiSegmentWildcard() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Implements Eventarc's path pattern from the spec https://cloud.google.com/eventarc/docs/path-patterns
|
||||
* @internal
|
||||
*/
|
||||
class PathPattern {
|
||||
/** @throws on validation error */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
static compile(rawPath) {
|
||||
return undefined;
|
||||
}
|
||||
constructor(raw) {
|
||||
this.raw = raw;
|
||||
this.segments = [];
|
||||
this.initPathSegments(raw);
|
||||
}
|
||||
getValue() {
|
||||
return this.raw;
|
||||
}
|
||||
// If false, we don't need to use pathPattern as our eventarc match type.
|
||||
hasWildcards() {
|
||||
return this.segments.some((segment) => segment.isSingleSegmentWildcard() || segment.isMultiSegmentWildcard());
|
||||
}
|
||||
hasCaptures() {
|
||||
return this.segments.some((segment) => segment.name === "single-capture" || segment.name === "multi-capture");
|
||||
}
|
||||
extractMatches(path) {
|
||||
const matches = {};
|
||||
if (!this.hasCaptures()) {
|
||||
return matches;
|
||||
}
|
||||
const pathSegments = (0, path_1.pathParts)(path);
|
||||
let pathNdx = 0;
|
||||
for (let segmentNdx = 0; segmentNdx < this.segments.length && pathNdx < pathSegments.length; segmentNdx++) {
|
||||
const segment = this.segments[segmentNdx];
|
||||
const remainingSegments = this.segments.length - 1 - segmentNdx;
|
||||
const nextPathNdx = pathSegments.length - remainingSegments;
|
||||
if (segment.name === "single-capture") {
|
||||
matches[segment.trimmed] = pathSegments[pathNdx];
|
||||
}
|
||||
else if (segment.name === "multi-capture") {
|
||||
matches[segment.trimmed] = pathSegments.slice(pathNdx, nextPathNdx).join("/");
|
||||
}
|
||||
pathNdx = segment.isMultiSegmentWildcard() ? nextPathNdx : pathNdx + 1;
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
initPathSegments(raw) {
|
||||
const parts = (0, path_1.pathParts)(raw);
|
||||
for (const part of parts) {
|
||||
let segment;
|
||||
const capture = part.match(WILDCARD_CAPTURE_REGEX);
|
||||
if (capture && capture.length === 1) {
|
||||
segment = part.includes("**")
|
||||
? new MultiCaptureSegment(part)
|
||||
: new SingleCaptureSegment(part);
|
||||
}
|
||||
else {
|
||||
segment = new Segment(part);
|
||||
}
|
||||
this.segments.push(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.PathPattern = PathPattern;
|
||||
19
node_modules/firebase-functions/lib/common/utilities/path.d.ts
generated
vendored
Normal file
19
node_modules/firebase-functions/lib/common/utilities/path.d.ts
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
/** @hidden
|
||||
* Removes leading and trailing slashes from a path.
|
||||
*
|
||||
* @param path A path to normalize, in POSIX format.
|
||||
*/
|
||||
export declare function normalizePath(path: string): string;
|
||||
/**
|
||||
* Normalizes a given path and splits it into an array of segments.
|
||||
*
|
||||
* @param path A path to split, in POSIX format.
|
||||
*/
|
||||
export declare function pathParts(path: string): string[];
|
||||
/**
|
||||
* Normalizes given paths and joins these together using a POSIX separator.
|
||||
*
|
||||
* @param base A first path segment, in POSIX format.
|
||||
* @param child A second path segment, in POSIX format.
|
||||
*/
|
||||
export declare function joinPath(base: string, child: string): string;
|
||||
37
node_modules/firebase-functions/lib/common/utilities/path.js
generated
vendored
Normal file
37
node_modules/firebase-functions/lib/common/utilities/path.js
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.joinPath = exports.pathParts = exports.normalizePath = void 0;
|
||||
/** @hidden
|
||||
* Removes leading and trailing slashes from a path.
|
||||
*
|
||||
* @param path A path to normalize, in POSIX format.
|
||||
*/
|
||||
function normalizePath(path) {
|
||||
if (!path) {
|
||||
return "";
|
||||
}
|
||||
return path.replace(/^\//, "").replace(/\/$/, "");
|
||||
}
|
||||
exports.normalizePath = normalizePath;
|
||||
/**
|
||||
* Normalizes a given path and splits it into an array of segments.
|
||||
*
|
||||
* @param path A path to split, in POSIX format.
|
||||
*/
|
||||
function pathParts(path) {
|
||||
if (!path || path === "" || path === "/") {
|
||||
return [];
|
||||
}
|
||||
return normalizePath(path).split("/");
|
||||
}
|
||||
exports.pathParts = pathParts;
|
||||
/**
|
||||
* Normalizes given paths and joins these together using a POSIX separator.
|
||||
*
|
||||
* @param base A first path segment, in POSIX format.
|
||||
* @param child A second path segment, in POSIX format.
|
||||
*/
|
||||
function joinPath(base, child) {
|
||||
return pathParts(base).concat(pathParts(child)).join("/");
|
||||
}
|
||||
exports.joinPath = joinPath;
|
||||
2
node_modules/firebase-functions/lib/common/utilities/utils.d.ts
generated
vendored
Normal file
2
node_modules/firebase-functions/lib/common/utilities/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/** @hidden */
|
||||
export declare function applyChange(src: any, dest: any): any;
|
||||
52
node_modules/firebase-functions/lib/common/utilities/utils.js
generated
vendored
Normal file
52
node_modules/firebase-functions/lib/common/utilities/utils.js
generated
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.applyChange = void 0;
|
||||
function isObject(obj) {
|
||||
return typeof obj === "object" && !!obj;
|
||||
}
|
||||
/** @hidden */
|
||||
function applyChange(src, dest) {
|
||||
// if not mergeable, don't merge
|
||||
if (!isObject(dest) || !isObject(src)) {
|
||||
return dest;
|
||||
}
|
||||
return merge(src, dest);
|
||||
}
|
||||
exports.applyChange = applyChange;
|
||||
function merge(src, dest) {
|
||||
const res = {};
|
||||
const keys = new Set([...Object.keys(src), ...Object.keys(dest)]);
|
||||
for (const key of keys.values()) {
|
||||
if (key in dest) {
|
||||
if (dest[key] === null) {
|
||||
continue;
|
||||
}
|
||||
res[key] = applyChange(src[key], dest[key]);
|
||||
}
|
||||
else if (src[key] !== null) {
|
||||
res[key] = src[key];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
12
node_modules/firebase-functions/lib/logger/common.d.ts
generated
vendored
Normal file
12
node_modules/firebase-functions/lib/logger/common.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
/** @hidden */
|
||||
export declare const CONSOLE_SEVERITY: {
|
||||
[severity: string]: "debug" | "info" | "warn" | "error";
|
||||
};
|
||||
/** @hidden */
|
||||
export declare const UNPATCHED_CONSOLE: {
|
||||
debug: (message?: any, ...optionalParams: any[]) => void;
|
||||
info: (message?: any, ...optionalParams: any[]) => void;
|
||||
log: (message?: any, ...optionalParams: any[]) => void;
|
||||
warn: (message?: any, ...optionalParams: any[]) => void;
|
||||
error: (message?: any, ...optionalParams: any[]) => void;
|
||||
};
|
||||
45
node_modules/firebase-functions/lib/logger/common.js
generated
vendored
Normal file
45
node_modules/firebase-functions/lib/logger/common.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UNPATCHED_CONSOLE = exports.CONSOLE_SEVERITY = void 0;
|
||||
// Map LogSeverity types to their equivalent `console.*` method.
|
||||
/** @hidden */
|
||||
exports.CONSOLE_SEVERITY = {
|
||||
DEBUG: "debug",
|
||||
INFO: "info",
|
||||
NOTICE: "info",
|
||||
WARNING: "warn",
|
||||
ERROR: "error",
|
||||
CRITICAL: "error",
|
||||
ALERT: "error",
|
||||
EMERGENCY: "error",
|
||||
};
|
||||
// safely preserve unpatched console.* methods in case of compat require
|
||||
/** @hidden */
|
||||
exports.UNPATCHED_CONSOLE = {
|
||||
debug: console.debug,
|
||||
info: console.info,
|
||||
log: console.log,
|
||||
warn: console.warn,
|
||||
error: console.error,
|
||||
};
|
||||
1
node_modules/firebase-functions/lib/logger/compat.d.ts
generated
vendored
Normal file
1
node_modules/firebase-functions/lib/logger/compat.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
41
node_modules/firebase-functions/lib/logger/compat.js
generated
vendored
Normal file
41
node_modules/firebase-functions/lib/logger/compat.js
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const util_1 = require("util");
|
||||
const common_1 = require("./common");
|
||||
/** @hidden */
|
||||
function patchedConsole(severity) {
|
||||
return function (data, ...args) {
|
||||
let message = (0, util_1.format)(data, ...args);
|
||||
if (severity === "ERROR") {
|
||||
message = new Error(message).stack || message;
|
||||
}
|
||||
common_1.UNPATCHED_CONSOLE[common_1.CONSOLE_SEVERITY[severity]](JSON.stringify({ severity, message }));
|
||||
};
|
||||
}
|
||||
// IMPORTANT -- "../logger" must be imported before monkeypatching!
|
||||
console.debug = patchedConsole("DEBUG");
|
||||
console.info = patchedConsole("INFO");
|
||||
console.log = patchedConsole("INFO");
|
||||
console.warn = patchedConsole("WARNING");
|
||||
console.error = patchedConsole("ERROR");
|
||||
57
node_modules/firebase-functions/lib/logger/index.d.ts
generated
vendored
Normal file
57
node_modules/firebase-functions/lib/logger/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* `LogSeverity` indicates the detailed severity of the log entry. See [LogSeverity](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity).
|
||||
* @public
|
||||
*/
|
||||
export type LogSeverity = "DEBUG" | "INFO" | "NOTICE" | "WARNING" | "ERROR" | "CRITICAL" | "ALERT" | "EMERGENCY";
|
||||
/**
|
||||
* `LogEntry` represents a [structured Cloud Logging](https://cloud.google.com/logging/docs/structured-logging)
|
||||
* entry. All keys aside from `severity` and `message` are
|
||||
* included in the `jsonPayload` of the logged entry.
|
||||
* @public
|
||||
*/
|
||||
export interface LogEntry {
|
||||
severity: LogSeverity;
|
||||
message?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
/**
|
||||
* Writes a `LogEntry` to `stdout`/`stderr` (depending on severity).
|
||||
* @param entry - The `LogEntry` including severity, message, and any additional structured metadata.
|
||||
* @public
|
||||
*/
|
||||
export declare function write(entry: LogEntry): void;
|
||||
/**
|
||||
* Writes a `DEBUG` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
export declare function debug(...args: any[]): void;
|
||||
/**
|
||||
* Writes an `INFO` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
export declare function log(...args: any[]): void;
|
||||
/**
|
||||
* Writes an `INFO` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
export declare function info(...args: any[]): void;
|
||||
/**
|
||||
* Writes a `WARNING` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
export declare function warn(...args: any[]): void;
|
||||
/**
|
||||
* Writes an `ERROR` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
export declare function error(...args: any[]): void;
|
||||
143
node_modules/firebase-functions/lib/logger/index.js
generated
vendored
Normal file
143
node_modules/firebase-functions/lib/logger/index.js
generated
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.error = exports.warn = exports.info = exports.log = exports.debug = exports.write = void 0;
|
||||
const util_1 = require("util");
|
||||
const trace_1 = require("../common/trace");
|
||||
const common_1 = require("./common");
|
||||
/** @internal */
|
||||
function removeCircular(obj, refs = []) {
|
||||
if (typeof obj !== "object" || !obj) {
|
||||
return obj;
|
||||
}
|
||||
// If the object defines its own toJSON, prefer that.
|
||||
if (obj.toJSON) {
|
||||
return obj.toJSON();
|
||||
}
|
||||
if (refs.includes(obj)) {
|
||||
return "[Circular]";
|
||||
}
|
||||
else {
|
||||
refs.push(obj);
|
||||
}
|
||||
let returnObj;
|
||||
if (Array.isArray(obj)) {
|
||||
returnObj = new Array(obj.length);
|
||||
}
|
||||
else {
|
||||
returnObj = {};
|
||||
}
|
||||
for (const k in obj) {
|
||||
if (refs.includes(obj[k])) {
|
||||
returnObj[k] = "[Circular]";
|
||||
}
|
||||
else {
|
||||
returnObj[k] = removeCircular(obj[k], refs);
|
||||
}
|
||||
}
|
||||
return returnObj;
|
||||
}
|
||||
/**
|
||||
* Writes a `LogEntry` to `stdout`/`stderr` (depending on severity).
|
||||
* @param entry - The `LogEntry` including severity, message, and any additional structured metadata.
|
||||
* @public
|
||||
*/
|
||||
function write(entry) {
|
||||
const ctx = trace_1.traceContext.getStore();
|
||||
if (ctx === null || ctx === void 0 ? void 0 : ctx.traceId) {
|
||||
entry["logging.googleapis.com/trace"] = `projects/${process.env.GCLOUD_PROJECT}/traces/${ctx.traceId}`;
|
||||
}
|
||||
common_1.UNPATCHED_CONSOLE[common_1.CONSOLE_SEVERITY[entry.severity]](JSON.stringify(removeCircular(entry)));
|
||||
}
|
||||
exports.write = write;
|
||||
/**
|
||||
* Writes a `DEBUG` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
function debug(...args) {
|
||||
write(entryFromArgs("DEBUG", args));
|
||||
}
|
||||
exports.debug = debug;
|
||||
/**
|
||||
* Writes an `INFO` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
function log(...args) {
|
||||
write(entryFromArgs("INFO", args));
|
||||
}
|
||||
exports.log = log;
|
||||
/**
|
||||
* Writes an `INFO` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
function info(...args) {
|
||||
write(entryFromArgs("INFO", args));
|
||||
}
|
||||
exports.info = info;
|
||||
/**
|
||||
* Writes a `WARNING` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
function warn(...args) {
|
||||
write(entryFromArgs("WARNING", args));
|
||||
}
|
||||
exports.warn = warn;
|
||||
/**
|
||||
* Writes an `ERROR` severity log. If the last argument provided is a plain object,
|
||||
* it is added to the `jsonPayload` in the Cloud Logging entry.
|
||||
* @param args - Arguments, concatenated into the log message with space separators.
|
||||
* @public
|
||||
*/
|
||||
function error(...args) {
|
||||
write(entryFromArgs("ERROR", args));
|
||||
}
|
||||
exports.error = error;
|
||||
/** @hidden */
|
||||
function entryFromArgs(severity, args) {
|
||||
let entry = {};
|
||||
const lastArg = args[args.length - 1];
|
||||
if (lastArg && typeof lastArg === "object" && lastArg.constructor === Object) {
|
||||
entry = args.pop();
|
||||
}
|
||||
// mimic `console.*` behavior, see https://nodejs.org/api/console.html#console_console_log_data_args
|
||||
let message = (0, util_1.format)(...args);
|
||||
if (severity === "ERROR" && !args.find((arg) => arg instanceof Error)) {
|
||||
message = new Error(message).stack || message;
|
||||
}
|
||||
const out = {
|
||||
...entry,
|
||||
severity,
|
||||
};
|
||||
if (message) {
|
||||
out.message = message;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
71
node_modules/firebase-functions/lib/params/index.d.ts
generated
vendored
Normal file
71
node_modules/firebase-functions/lib/params/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* @hidden
|
||||
* @alpha
|
||||
*/
|
||||
import { BooleanParam, Expression, IntParam, Param, ParamOptions, SecretParam, StringParam, ListParam } from "./types";
|
||||
export { BUCKET_PICKER, TextInput, SelectInput, SelectOptions, MultiSelectInput, select, multiSelect, } from "./types";
|
||||
export { ParamOptions, Expression };
|
||||
type SecretOrExpr = Param<any> | SecretParam;
|
||||
export declare const declaredParams: SecretOrExpr[];
|
||||
/**
|
||||
* A built-in parameter that resolves to the default RTDB database URL associated
|
||||
* with the project, without prompting the deployer. Empty string if none exists.
|
||||
*/
|
||||
export declare const databaseURL: Param<string>;
|
||||
/**
|
||||
* A built-in parameter that resolves to the Cloud project ID associated with
|
||||
* the project, without prompting the deployer.
|
||||
*/
|
||||
export declare const projectID: Param<string>;
|
||||
/**
|
||||
* A built-in parameter that resolves to the Cloud project ID, without prompting
|
||||
* the deployer.
|
||||
*/
|
||||
export declare const gcloudProject: Param<string>;
|
||||
/**
|
||||
* A builtin parameter that resolves to the Cloud storage bucket associated
|
||||
* with the function, without prompting the deployer. Empty string if not
|
||||
* defined.
|
||||
*/
|
||||
export declare const storageBucket: Param<string>;
|
||||
/**
|
||||
* Declares a secret param, that will persist values only in Cloud Secret Manager.
|
||||
* Secrets are stored internally as bytestrings. Use `ParamOptions.as` to provide type
|
||||
* hinting during parameter resolution.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @returns A parameter with a `string` return type for `.value`.
|
||||
*/
|
||||
export declare function defineSecret(name: string): SecretParam;
|
||||
/**
|
||||
* Declare a string parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `string` return type for `.value`.
|
||||
*/
|
||||
export declare function defineString(name: string, options?: ParamOptions<string>): StringParam;
|
||||
/**
|
||||
* Declare a boolean parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `boolean` return type for `.value`.
|
||||
*/
|
||||
export declare function defineBoolean(name: string, options?: ParamOptions<boolean>): BooleanParam;
|
||||
/**
|
||||
* Declare an integer parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `number` return type for `.value`.
|
||||
*/
|
||||
export declare function defineInt(name: string, options?: ParamOptions<number>): IntParam;
|
||||
/**
|
||||
* Declare a list parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `string[]` return type for `.value`.
|
||||
*/
|
||||
export declare function defineList(name: string, options?: ParamOptions<string[]>): ListParam;
|
||||
158
node_modules/firebase-functions/lib/params/index.js
generated
vendored
Normal file
158
node_modules/firebase-functions/lib/params/index.js
generated
vendored
Normal file
@@ -0,0 +1,158 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.defineList = exports.defineFloat = exports.defineInt = exports.defineBoolean = exports.defineString = exports.defineSecret = exports.storageBucket = exports.gcloudProject = exports.projectID = exports.databaseURL = exports.clearParams = exports.declaredParams = exports.Expression = exports.multiSelect = exports.select = exports.BUCKET_PICKER = void 0;
|
||||
/**
|
||||
* @hidden
|
||||
* @alpha
|
||||
*/
|
||||
const types_1 = require("./types");
|
||||
Object.defineProperty(exports, "Expression", { enumerable: true, get: function () { return types_1.Expression; } });
|
||||
var types_2 = require("./types");
|
||||
Object.defineProperty(exports, "BUCKET_PICKER", { enumerable: true, get: function () { return types_2.BUCKET_PICKER; } });
|
||||
Object.defineProperty(exports, "select", { enumerable: true, get: function () { return types_2.select; } });
|
||||
Object.defineProperty(exports, "multiSelect", { enumerable: true, get: function () { return types_2.multiSelect; } });
|
||||
exports.declaredParams = [];
|
||||
/**
|
||||
* Use a helper to manage the list such that parameters are uniquely
|
||||
* registered once only but order is preserved.
|
||||
* @internal
|
||||
*/
|
||||
function registerParam(param) {
|
||||
for (let i = 0; i < exports.declaredParams.length; i++) {
|
||||
if (exports.declaredParams[i].name === param.name) {
|
||||
exports.declaredParams.splice(i, 1);
|
||||
}
|
||||
}
|
||||
exports.declaredParams.push(param);
|
||||
}
|
||||
/**
|
||||
* For testing.
|
||||
* @internal
|
||||
*/
|
||||
function clearParams() {
|
||||
exports.declaredParams.splice(0, exports.declaredParams.length);
|
||||
}
|
||||
exports.clearParams = clearParams;
|
||||
/**
|
||||
* A built-in parameter that resolves to the default RTDB database URL associated
|
||||
* with the project, without prompting the deployer. Empty string if none exists.
|
||||
*/
|
||||
exports.databaseURL = new types_1.InternalExpression("DATABASE_URL", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.databaseURL) || ""; });
|
||||
/**
|
||||
* A built-in parameter that resolves to the Cloud project ID associated with
|
||||
* the project, without prompting the deployer.
|
||||
*/
|
||||
exports.projectID = new types_1.InternalExpression("PROJECT_ID", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.projectId) || ""; });
|
||||
/**
|
||||
* A built-in parameter that resolves to the Cloud project ID, without prompting
|
||||
* the deployer.
|
||||
*/
|
||||
exports.gcloudProject = new types_1.InternalExpression("GCLOUD_PROJECT", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.projectId) || ""; });
|
||||
/**
|
||||
* A builtin parameter that resolves to the Cloud storage bucket associated
|
||||
* with the function, without prompting the deployer. Empty string if not
|
||||
* defined.
|
||||
*/
|
||||
exports.storageBucket = new types_1.InternalExpression("STORAGE_BUCKET", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.storageBucket) || ""; });
|
||||
/**
|
||||
* Declares a secret param, that will persist values only in Cloud Secret Manager.
|
||||
* Secrets are stored internally as bytestrings. Use `ParamOptions.as` to provide type
|
||||
* hinting during parameter resolution.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @returns A parameter with a `string` return type for `.value`.
|
||||
*/
|
||||
function defineSecret(name) {
|
||||
const param = new types_1.SecretParam(name);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineSecret = defineSecret;
|
||||
/**
|
||||
* Declare a string parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `string` return type for `.value`.
|
||||
*/
|
||||
function defineString(name, options = {}) {
|
||||
const param = new types_1.StringParam(name, options);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineString = defineString;
|
||||
/**
|
||||
* Declare a boolean parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `boolean` return type for `.value`.
|
||||
*/
|
||||
function defineBoolean(name, options = {}) {
|
||||
const param = new types_1.BooleanParam(name, options);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineBoolean = defineBoolean;
|
||||
/**
|
||||
* Declare an integer parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `number` return type for `.value`.
|
||||
*/
|
||||
function defineInt(name, options = {}) {
|
||||
const param = new types_1.IntParam(name, options);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineInt = defineInt;
|
||||
/**
|
||||
* Declare a float parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `number` return type for `.value`.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
function defineFloat(name, options = {}) {
|
||||
const param = new types_1.FloatParam(name, options);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineFloat = defineFloat;
|
||||
/**
|
||||
* Declare a list parameter.
|
||||
*
|
||||
* @param name The name of the environment variable to use to load the parameter.
|
||||
* @param options Configuration options for the parameter.
|
||||
* @returns A parameter with a `string[]` return type for `.value`.
|
||||
*/
|
||||
function defineList(name, options = {}) {
|
||||
const param = new types_1.ListParam(name, options);
|
||||
registerParam(param);
|
||||
return param;
|
||||
}
|
||||
exports.defineList = defineList;
|
||||
225
node_modules/firebase-functions/lib/params/types.d.ts
generated
vendored
Normal file
225
node_modules/firebase-functions/lib/params/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
export declare abstract class Expression<T extends string | number | boolean | string[]> {
|
||||
/** Returns the expression's runtime value, based on the CLI's resolution of parameters. */
|
||||
value(): T;
|
||||
/** Returns the expression's representation as a braced CEL expression. */
|
||||
toCEL(): string;
|
||||
/** Returns the expression's representation as JSON. */
|
||||
toJSON(): string;
|
||||
}
|
||||
/**
|
||||
* A CEL expression corresponding to a ternary operator, e.g {{ cond ? ifTrue : ifFalse }}
|
||||
*/
|
||||
export declare class TernaryExpression<T extends string | number | boolean | string[]> extends Expression<T> {
|
||||
private readonly test;
|
||||
private readonly ifTrue;
|
||||
private readonly ifFalse;
|
||||
constructor(test: Expression<boolean>, ifTrue: T | Expression<T>, ifFalse: T | Expression<T>);
|
||||
toString(): string;
|
||||
}
|
||||
/**
|
||||
* A CEL expression that evaluates to boolean true or false based on a comparison
|
||||
* between the value of another expression and a literal of that same type.
|
||||
*/
|
||||
export declare class CompareExpression<T extends string | number | boolean | string[]> extends Expression<boolean> {
|
||||
cmp: "==" | "!=" | ">" | ">=" | "<" | "<=";
|
||||
lhs: Expression<T>;
|
||||
rhs: T | Expression<T>;
|
||||
constructor(cmp: "==" | "!=" | ">" | ">=" | "<" | "<=", lhs: Expression<T>, rhs: T | Expression<T>);
|
||||
toString(): string;
|
||||
/** Returns a `TernaryExpression` which can resolve to one of two values, based on the resolution of this comparison. */
|
||||
thenElse<retT extends string | number | boolean | string[]>(ifTrue: retT | Expression<retT>, ifFalse: retT | Expression<retT>): TernaryExpression<retT>;
|
||||
}
|
||||
/** @hidden */
|
||||
type ParamValueType = "string" | "list" | "boolean" | "int" | "float" | "secret";
|
||||
/** Create a select input from a series of values. */
|
||||
export declare function select<T>(options: T[]): SelectInput<T>;
|
||||
/** Create a select input from a map of labels to values. */
|
||||
export declare function select<T>(optionsWithLabels: Record<string, T>): SelectInput<T>;
|
||||
/** Create a multi-select input from a series of values. */
|
||||
export declare function multiSelect(options: string[]): MultiSelectInput;
|
||||
/** Create a multi-select input from map of labels to values. */
|
||||
export declare function multiSelect(options: Record<string, string>): MultiSelectInput;
|
||||
type ParamInput<T> = TextInput<T> | SelectInput<T> | (T extends string[] ? MultiSelectInput : never) | (T extends string ? ResourceInput : never);
|
||||
/**
|
||||
* Specifies that a parameter's value should be determined by prompting the user
|
||||
* to type it in interactively at deploy time. Input that does not match the
|
||||
* provided validationRegex, if present, will be retried.
|
||||
*/
|
||||
export interface TextInput<T = unknown> {
|
||||
text: {
|
||||
example?: string;
|
||||
/**
|
||||
* A regular expression (or an escaped string to compile into a regular
|
||||
* expression) which the prompted text must satisfy; the prompt will retry
|
||||
* until input matching the regex is provided.
|
||||
*/
|
||||
validationRegex?: string | RegExp;
|
||||
/**
|
||||
* A custom error message to display when retrying the prompt based on input
|
||||
* failing to conform to the validationRegex,
|
||||
*/
|
||||
validationErrorMessage?: string;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Specifies that a parameter's value should be determined by having the user
|
||||
* select from a list containing all the project's resources of a certain
|
||||
* type. Currently, only type:"storage.googleapis.com/Bucket" is supported.
|
||||
*/
|
||||
export interface ResourceInput {
|
||||
resource: {
|
||||
type: "storage.googleapis.com/Bucket";
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Autogenerate a list of buckets in a project that a user can select from.
|
||||
*/
|
||||
export declare const BUCKET_PICKER: ResourceInput;
|
||||
/**
|
||||
* Specifies that a parameter's value should be determined by having the user select
|
||||
* from a list of pre-canned options interactively at deploy time.
|
||||
*/
|
||||
export interface SelectInput<T = unknown> {
|
||||
select: {
|
||||
options: Array<SelectOptions<T>>;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Specifies that a parameter's value should be determined by having the user select
|
||||
* a subset from a list of pre-canned options interactively at deploy time.
|
||||
* Will result in errors if used on parameters of type other than `string[]`.
|
||||
*/
|
||||
export interface MultiSelectInput {
|
||||
multiSelect: {
|
||||
options: Array<SelectOptions<string>>;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* One of the options provided to a `SelectInput`, containing a value and
|
||||
* optionally a human-readable label to display in the selection interface.
|
||||
*/
|
||||
export interface SelectOptions<T = unknown> {
|
||||
label?: string;
|
||||
value: T;
|
||||
}
|
||||
/** The wire representation of a parameter when it's sent to the CLI. A superset of `ParamOptions`. */
|
||||
export type ParamSpec<T extends string | number | boolean | string[]> = {
|
||||
/** The name of the parameter which will be stored in .env files. Use UPPERCASE. */
|
||||
name: string;
|
||||
/** An optional default value to be used while prompting for input. Can be a literal or another parametrized expression. */
|
||||
default?: T | Expression<T>;
|
||||
/** An optional human-readable string to be used as a replacement for the parameter's name when prompting. */
|
||||
label?: string;
|
||||
/** An optional long-form description of the parameter to be displayed while prompting. */
|
||||
description?: string;
|
||||
/** The way in which the Firebase CLI will prompt for the value of this parameter. Defaults to a TextInput. */
|
||||
input?: ParamInput<T>;
|
||||
};
|
||||
/**
|
||||
* Representation of parameters for the stack over the wire.
|
||||
*
|
||||
* @remarks
|
||||
* N.B: a WireParamSpec is just a ParamSpec with default expressions converted into a CEL literal
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export type WireParamSpec<T extends string | number | boolean | string[]> = {
|
||||
name: string;
|
||||
default?: T | string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
type: ParamValueType;
|
||||
input?: ParamInput<T>;
|
||||
};
|
||||
/** Configuration options which can be used to customize the prompting behavior of a parameter. */
|
||||
export type ParamOptions<T extends string | number | boolean | string[]> = Omit<ParamSpec<T>, "name" | "type">;
|
||||
/**
|
||||
* Represents a parametrized value that will be read from .env files if present,
|
||||
* or prompted for by the CLI if missing. Instantiate these with the defineX
|
||||
* methods exported by the firebase-functions/params namespace.
|
||||
*/
|
||||
export declare abstract class Param<T extends string | number | boolean | string[]> extends Expression<T> {
|
||||
readonly name: string;
|
||||
readonly options: ParamOptions<T>;
|
||||
static type: ParamValueType;
|
||||
constructor(name: string, options?: ParamOptions<T>);
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
cmp(cmp: "==" | "!=" | ">" | ">=" | "<" | "<=", rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
equals(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
notEquals(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
greaterThan(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
greaterThanOrEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
lessThan(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
lessThanOrEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
/**
|
||||
* Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression.
|
||||
* @deprecated A typo. Use lessThanOrEqualTo instead.
|
||||
*/
|
||||
lessThanorEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
|
||||
toString(): string;
|
||||
}
|
||||
/**
|
||||
* A parametrized string whose value is stored in Cloud Secret Manager
|
||||
* instead of the local filesystem. Supply instances of SecretParams to
|
||||
* the secrets array while defining a Function to make their values accessible
|
||||
* during execution of that Function.
|
||||
*/
|
||||
export declare class SecretParam {
|
||||
static type: ParamValueType;
|
||||
name: string;
|
||||
constructor(name: string);
|
||||
/** Returns the secret's value at runtime. Throws an error if accessed during deployment. */
|
||||
value(): string;
|
||||
}
|
||||
/**
|
||||
* A parametrized value of String type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
export declare class StringParam extends Param<string> {
|
||||
}
|
||||
/**
|
||||
* A parametrized value of Integer type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
export declare class IntParam extends Param<number> {
|
||||
static type: ParamValueType;
|
||||
}
|
||||
/**
|
||||
* A parametrized value of Float type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
export declare class FloatParam extends Param<number> {
|
||||
static type: ParamValueType;
|
||||
}
|
||||
/**
|
||||
* A parametrized value of Boolean type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
export declare class BooleanParam extends Param<boolean> {
|
||||
static type: ParamValueType;
|
||||
/** @deprecated */
|
||||
then<T extends string | number | boolean>(ifTrue: T | Expression<T>, ifFalse: T | Expression<T>): TernaryExpression<T>;
|
||||
thenElse<T extends string | number | boolean>(ifTrue: T | Expression<T>, ifFalse: T | Expression<T>): TernaryExpression<T>;
|
||||
}
|
||||
/**
|
||||
* A parametrized value of String[] type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
export declare class ListParam extends Param<string[]> {
|
||||
static type: ParamValueType;
|
||||
/** @hidden */
|
||||
greaterThan(rhs: string[] | Expression<string[]>): CompareExpression<string[]>;
|
||||
/** @hidden */
|
||||
greaterThanOrEqualTo(rhs: string[] | Expression<string[]>): CompareExpression<string[]>;
|
||||
/** @hidden */
|
||||
lessThan(rhs: string[] | Expression<string[]>): CompareExpression<string[]>;
|
||||
/** @hidden */
|
||||
lessThanorEqualTo(rhs: string[] | Expression<string[]>): CompareExpression<string[]>;
|
||||
}
|
||||
export {};
|
||||
406
node_modules/firebase-functions/lib/params/types.js
generated
vendored
Normal file
406
node_modules/firebase-functions/lib/params/types.js
generated
vendored
Normal file
@@ -0,0 +1,406 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ListParam = exports.BooleanParam = exports.FloatParam = exports.IntParam = exports.InternalExpression = exports.StringParam = exports.SecretParam = exports.Param = exports.BUCKET_PICKER = exports.multiSelect = exports.select = exports.CompareExpression = exports.TernaryExpression = exports.Expression = void 0;
|
||||
const logger = require("../logger");
|
||||
/*
|
||||
* A CEL expression which can be evaluated during function deployment, and
|
||||
* resolved to a value of the generic type parameter: i.e, you can pass
|
||||
* an Expression<number> as the value of an option that normally accepts numbers.
|
||||
*/
|
||||
class Expression {
|
||||
/** Returns the expression's runtime value, based on the CLI's resolution of parameters. */
|
||||
value() {
|
||||
if (process.env.FUNCTIONS_CONTROL_API === "true") {
|
||||
logger.warn(`${this.toString()}.value() invoked during function deployment, instead of during runtime.`);
|
||||
logger.warn(`This is usually a mistake. In configs, use Params directly without calling .value().`);
|
||||
logger.warn(`example: { memory: memoryParam } not { memory: memoryParam.value() }`);
|
||||
}
|
||||
return this.runtimeValue();
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
/** Returns the expression's representation as a braced CEL expression. */
|
||||
toCEL() {
|
||||
return `{{ ${this.toString()} }}`;
|
||||
}
|
||||
/** Returns the expression's representation as JSON. */
|
||||
toJSON() {
|
||||
return this.toString();
|
||||
}
|
||||
}
|
||||
exports.Expression = Expression;
|
||||
function valueOf(arg) {
|
||||
return arg instanceof Expression ? arg.runtimeValue() : arg;
|
||||
}
|
||||
/**
|
||||
* Returns how an entity (either an `Expression` or a literal value) should be represented in CEL.
|
||||
* - Expressions delegate to the `.toString()` method, which is used by the WireManifest
|
||||
* - Strings have to be quoted explicitly
|
||||
* - Arrays are represented as []-delimited, parsable JSON
|
||||
* - Numbers and booleans are not quoted explicitly
|
||||
*/
|
||||
function refOf(arg) {
|
||||
if (arg instanceof Expression) {
|
||||
return arg.toString();
|
||||
}
|
||||
else if (typeof arg === "string") {
|
||||
return `"${arg}"`;
|
||||
}
|
||||
else if (Array.isArray(arg)) {
|
||||
return JSON.stringify(arg);
|
||||
}
|
||||
else {
|
||||
return arg.toString();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A CEL expression corresponding to a ternary operator, e.g {{ cond ? ifTrue : ifFalse }}
|
||||
*/
|
||||
class TernaryExpression extends Expression {
|
||||
constructor(test, ifTrue, ifFalse) {
|
||||
super();
|
||||
this.test = test;
|
||||
this.ifTrue = ifTrue;
|
||||
this.ifFalse = ifFalse;
|
||||
this.ifTrue = ifTrue;
|
||||
this.ifFalse = ifFalse;
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return this.test.runtimeValue() ? valueOf(this.ifTrue) : valueOf(this.ifFalse);
|
||||
}
|
||||
toString() {
|
||||
return `${this.test} ? ${refOf(this.ifTrue)} : ${refOf(this.ifFalse)}`;
|
||||
}
|
||||
}
|
||||
exports.TernaryExpression = TernaryExpression;
|
||||
/**
|
||||
* A CEL expression that evaluates to boolean true or false based on a comparison
|
||||
* between the value of another expression and a literal of that same type.
|
||||
*/
|
||||
class CompareExpression extends Expression {
|
||||
constructor(cmp, lhs, rhs) {
|
||||
super();
|
||||
this.cmp = cmp;
|
||||
this.lhs = lhs;
|
||||
this.rhs = rhs;
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
const left = this.lhs.runtimeValue();
|
||||
const right = valueOf(this.rhs);
|
||||
switch (this.cmp) {
|
||||
case "==":
|
||||
return Array.isArray(left) ? this.arrayEquals(left, right) : left === right;
|
||||
case "!=":
|
||||
return Array.isArray(left) ? !this.arrayEquals(left, right) : left !== right;
|
||||
case ">":
|
||||
return left > right;
|
||||
case ">=":
|
||||
return left >= right;
|
||||
case "<":
|
||||
return left < right;
|
||||
case "<=":
|
||||
return left <= right;
|
||||
default:
|
||||
throw new Error(`Unknown comparator ${this.cmp}`);
|
||||
}
|
||||
}
|
||||
/** @internal */
|
||||
arrayEquals(a, b) {
|
||||
return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));
|
||||
}
|
||||
toString() {
|
||||
const rhsStr = refOf(this.rhs);
|
||||
return `${this.lhs} ${this.cmp} ${rhsStr}`;
|
||||
}
|
||||
/** Returns a `TernaryExpression` which can resolve to one of two values, based on the resolution of this comparison. */
|
||||
thenElse(ifTrue, ifFalse) {
|
||||
return new TernaryExpression(this, ifTrue, ifFalse);
|
||||
}
|
||||
}
|
||||
exports.CompareExpression = CompareExpression;
|
||||
/** Create a select input from a series of values or a map of labels to values */
|
||||
function select(options) {
|
||||
let wireOpts;
|
||||
if (Array.isArray(options)) {
|
||||
wireOpts = options.map((opt) => ({ value: opt }));
|
||||
}
|
||||
else {
|
||||
wireOpts = Object.entries(options).map(([label, value]) => ({ label, value }));
|
||||
}
|
||||
return {
|
||||
select: {
|
||||
options: wireOpts,
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.select = select;
|
||||
/** Create a multi-select input from a series of values or map of labels to values. */
|
||||
function multiSelect(options) {
|
||||
let wireOpts;
|
||||
if (Array.isArray(options)) {
|
||||
wireOpts = options.map((opt) => ({ value: opt }));
|
||||
}
|
||||
else {
|
||||
wireOpts = Object.entries(options).map(([label, value]) => ({ label, value }));
|
||||
}
|
||||
return {
|
||||
multiSelect: {
|
||||
options: wireOpts,
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.multiSelect = multiSelect;
|
||||
/**
|
||||
* Autogenerate a list of buckets in a project that a user can select from.
|
||||
*/
|
||||
exports.BUCKET_PICKER = {
|
||||
resource: {
|
||||
type: "storage.googleapis.com/Bucket",
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Represents a parametrized value that will be read from .env files if present,
|
||||
* or prompted for by the CLI if missing. Instantiate these with the defineX
|
||||
* methods exported by the firebase-functions/params namespace.
|
||||
*/
|
||||
class Param extends Expression {
|
||||
constructor(name, options = {}) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.options = options;
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
cmp(cmp, rhs) {
|
||||
return new CompareExpression(cmp, this, rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
equals(rhs) {
|
||||
return this.cmp("==", rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
notEquals(rhs) {
|
||||
return this.cmp("!=", rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
greaterThan(rhs) {
|
||||
return this.cmp(">", rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
greaterThanOrEqualTo(rhs) {
|
||||
return this.cmp(">=", rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
lessThan(rhs) {
|
||||
return this.cmp("<", rhs);
|
||||
}
|
||||
/** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
|
||||
lessThanOrEqualTo(rhs) {
|
||||
return this.cmp("<=", rhs);
|
||||
}
|
||||
/**
|
||||
* Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression.
|
||||
* @deprecated A typo. Use lessThanOrEqualTo instead.
|
||||
*/
|
||||
lessThanorEqualTo(rhs) {
|
||||
return this.lessThanOrEqualTo(rhs);
|
||||
}
|
||||
toString() {
|
||||
return `params.${this.name}`;
|
||||
}
|
||||
/** @internal */
|
||||
toSpec() {
|
||||
const { default: paramDefault, ...otherOptions } = this.options;
|
||||
const out = {
|
||||
name: this.name,
|
||||
...otherOptions,
|
||||
type: this.constructor.type,
|
||||
};
|
||||
if (paramDefault instanceof Expression) {
|
||||
out.default = paramDefault.toCEL();
|
||||
}
|
||||
else if (paramDefault !== undefined) {
|
||||
out.default = paramDefault;
|
||||
}
|
||||
if (out.input && "text" in out.input && out.input.text.validationRegex instanceof RegExp) {
|
||||
out.input.text.validationRegex = out.input.text.validationRegex.source;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
exports.Param = Param;
|
||||
Param.type = "string";
|
||||
/**
|
||||
* A parametrized string whose value is stored in Cloud Secret Manager
|
||||
* instead of the local filesystem. Supply instances of SecretParams to
|
||||
* the secrets array while defining a Function to make their values accessible
|
||||
* during execution of that Function.
|
||||
*/
|
||||
class SecretParam {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
const val = process.env[this.name];
|
||||
if (val === undefined) {
|
||||
logger.warn(`No value found for secret parameter "${this.name}". A function can only access a secret if you include the secret in the function's dependency array.`);
|
||||
}
|
||||
return val || "";
|
||||
}
|
||||
/** @internal */
|
||||
toSpec() {
|
||||
return {
|
||||
type: "secret",
|
||||
name: this.name,
|
||||
};
|
||||
}
|
||||
/** Returns the secret's value at runtime. Throws an error if accessed during deployment. */
|
||||
value() {
|
||||
if (process.env.FUNCTIONS_CONTROL_API === "true") {
|
||||
throw new Error(`Cannot access the value of secret "${this.name}" during function deployment. Secret values are only available at runtime.`);
|
||||
}
|
||||
return this.runtimeValue();
|
||||
}
|
||||
}
|
||||
exports.SecretParam = SecretParam;
|
||||
SecretParam.type = "secret";
|
||||
/**
|
||||
* A parametrized value of String type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
class StringParam extends Param {
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return process.env[this.name] || "";
|
||||
}
|
||||
}
|
||||
exports.StringParam = StringParam;
|
||||
/**
|
||||
* A CEL expression which represents an internal Firebase variable. This class
|
||||
* cannot be instantiated by developers, but we provide several canned instances
|
||||
* of it to make available parameters that will never have to be defined at
|
||||
* deployment time, and can always be read from process.env.
|
||||
* @internal
|
||||
*/
|
||||
class InternalExpression extends Param {
|
||||
constructor(name, getter) {
|
||||
super(name);
|
||||
this.getter = getter;
|
||||
}
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return this.getter(process.env) || "";
|
||||
}
|
||||
toSpec() {
|
||||
throw new Error("An InternalExpression should never be marshalled for wire transmission.");
|
||||
}
|
||||
}
|
||||
exports.InternalExpression = InternalExpression;
|
||||
/**
|
||||
* A parametrized value of Integer type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
class IntParam extends Param {
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return parseInt(process.env[this.name] || "0", 10) || 0;
|
||||
}
|
||||
}
|
||||
exports.IntParam = IntParam;
|
||||
IntParam.type = "int";
|
||||
/**
|
||||
* A parametrized value of Float type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
class FloatParam extends Param {
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return parseFloat(process.env[this.name] || "0") || 0;
|
||||
}
|
||||
}
|
||||
exports.FloatParam = FloatParam;
|
||||
FloatParam.type = "float";
|
||||
/**
|
||||
* A parametrized value of Boolean type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
class BooleanParam extends Param {
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
return !!process.env[this.name] && process.env[this.name] === "true";
|
||||
}
|
||||
/** @deprecated */
|
||||
then(ifTrue, ifFalse) {
|
||||
return this.thenElse(ifTrue, ifFalse);
|
||||
}
|
||||
thenElse(ifTrue, ifFalse) {
|
||||
return new TernaryExpression(this, ifTrue, ifFalse);
|
||||
}
|
||||
}
|
||||
exports.BooleanParam = BooleanParam;
|
||||
BooleanParam.type = "boolean";
|
||||
/**
|
||||
* A parametrized value of String[] type that will be read from .env files
|
||||
* if present, or prompted for by the CLI if missing.
|
||||
*/
|
||||
class ListParam extends Param {
|
||||
/** @internal */
|
||||
runtimeValue() {
|
||||
const val = JSON.parse(process.env[this.name]);
|
||||
if (!Array.isArray(val) || !val.every((v) => typeof v === "string")) {
|
||||
return [];
|
||||
}
|
||||
return val;
|
||||
}
|
||||
/** @hidden */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
greaterThan(rhs) {
|
||||
throw new Error(">/< comparison operators not supported on params of type List");
|
||||
}
|
||||
/** @hidden */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
greaterThanOrEqualTo(rhs) {
|
||||
throw new Error(">/< comparison operators not supported on params of type List");
|
||||
}
|
||||
/** @hidden */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
lessThan(rhs) {
|
||||
throw new Error(">/< comparison operators not supported on params of type List");
|
||||
}
|
||||
/** @hidden */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
lessThanorEqualTo(rhs) {
|
||||
throw new Error(">/< comparison operators not supported on params of type List");
|
||||
}
|
||||
}
|
||||
exports.ListParam = ListParam;
|
||||
ListParam.type = "list";
|
||||
1
node_modules/firebase-functions/lib/runtime/loader.d.ts
generated
vendored
Normal file
1
node_modules/firebase-functions/lib/runtime/loader.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
170
node_modules/firebase-functions/lib/runtime/loader.js
generated
vendored
Normal file
170
node_modules/firebase-functions/lib/runtime/loader.js
generated
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.loadStack = exports.mergeRequiredAPIs = exports.extractStack = void 0;
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
const path = require("path");
|
||||
const url = require("url");
|
||||
const params = require("../params");
|
||||
/**
|
||||
* Dynamically load import function to prevent TypeScript from
|
||||
* transpiling into a require.
|
||||
*
|
||||
* See https://github.com/microsoft/TypeScript/issues/43329.
|
||||
*
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
const dynamicImport = new Function("modulePath", "return import(modulePath)");
|
||||
async function loadModule(functionsDir) {
|
||||
const absolutePath = path.resolve(functionsDir);
|
||||
try {
|
||||
return require(path.resolve(absolutePath));
|
||||
}
|
||||
catch (e) {
|
||||
if (e.code === "ERR_REQUIRE_ESM" || e.code === "ERR_REQUIRE_ASYNC_MODULE") {
|
||||
// This is an ESM package, or one containing top-level awaits!
|
||||
const modulePath = require.resolve(absolutePath);
|
||||
// Resolve module path to file:// URL. Required for windows support.
|
||||
const moduleURL = url.pathToFileURL(modulePath).href;
|
||||
return await dynamicImport(moduleURL);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
/* @internal */
|
||||
function extractStack(module, endpoints, requiredAPIs, extensions, prefix = "") {
|
||||
for (const [name, valAsUnknown] of Object.entries(module)) {
|
||||
// We're introspecting untrusted code here. Any is appropraite
|
||||
const val = valAsUnknown;
|
||||
if (typeof val === "function" && val.__endpoint && typeof val.__endpoint === "object") {
|
||||
const funcName = prefix + name;
|
||||
endpoints[funcName] = {
|
||||
...val.__endpoint,
|
||||
entryPoint: funcName.replace(/-/g, "."),
|
||||
};
|
||||
if (val.__requiredAPIs && Array.isArray(val.__requiredAPIs)) {
|
||||
requiredAPIs.push(...val.__requiredAPIs);
|
||||
}
|
||||
}
|
||||
else if (isFirebaseRefExtension(val)) {
|
||||
extensions[val.instanceId] = {
|
||||
params: convertExtensionParams(val.params),
|
||||
ref: val.FIREBASE_EXTENSION_REFERENCE,
|
||||
events: val.events || [],
|
||||
};
|
||||
}
|
||||
else if (isFirebaseLocalExtension(val)) {
|
||||
extensions[val.instanceId] = {
|
||||
params: convertExtensionParams(val.params),
|
||||
localPath: val.FIREBASE_EXTENSION_LOCAL_PATH,
|
||||
events: val.events || [],
|
||||
};
|
||||
}
|
||||
else if (isObject(val)) {
|
||||
extractStack(val, endpoints, requiredAPIs, extensions, prefix + name + "-");
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.extractStack = extractStack;
|
||||
function toTitleCase(txt) {
|
||||
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
|
||||
}
|
||||
function snakeToCamelCase(txt) {
|
||||
let ret = txt.toLowerCase();
|
||||
ret = ret.replace(/_/g, " ");
|
||||
ret = ret.replace(/\w\S*/g, toTitleCase);
|
||||
ret = ret.charAt(0).toLowerCase() + ret.substring(1);
|
||||
return ret;
|
||||
}
|
||||
function convertExtensionParams(params) {
|
||||
const systemPrefixes = {
|
||||
FUNCTION: "firebaseextensions.v1beta.function",
|
||||
V2FUNCTION: "firebaseextensions.v1beta.v2function",
|
||||
};
|
||||
const converted = {};
|
||||
for (const [rawKey, paramVal] of Object.entries(params)) {
|
||||
let key = rawKey;
|
||||
if (rawKey.startsWith("_") && rawKey !== "_EVENT_ARC_REGION") {
|
||||
const prefix = rawKey.substring(1).split("_")[0];
|
||||
const suffix = rawKey.substring(2 + prefix.length); // 2 for underscores
|
||||
key = `${systemPrefixes[prefix]}/${snakeToCamelCase(suffix)}`;
|
||||
}
|
||||
if (Array.isArray(paramVal)) {
|
||||
converted[key] = paramVal.join(",");
|
||||
}
|
||||
else {
|
||||
converted[key] = paramVal;
|
||||
}
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
function isObject(value) {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
const isFirebaseLocalExtension = (val) => {
|
||||
return (isObject(val) &&
|
||||
typeof val.FIREBASE_EXTENSION_LOCAL_PATH === "string" &&
|
||||
typeof val.instanceId === "string" &&
|
||||
isObject(val.params) &&
|
||||
(!val.events || Array.isArray(val.events)));
|
||||
};
|
||||
const isFirebaseRefExtension = (val) => {
|
||||
return (isObject(val) &&
|
||||
typeof val.FIREBASE_EXTENSION_REFERENCE === "string" &&
|
||||
typeof val.instanceId === "string" &&
|
||||
isObject(val.params) &&
|
||||
(!val.events || Array.isArray(val.events)));
|
||||
};
|
||||
/* @internal */
|
||||
function mergeRequiredAPIs(requiredAPIs) {
|
||||
const apiToReasons = {};
|
||||
for (const { api, reason } of requiredAPIs) {
|
||||
const reasons = apiToReasons[api] || new Set();
|
||||
reasons.add(reason);
|
||||
apiToReasons[api] = reasons;
|
||||
}
|
||||
const merged = [];
|
||||
for (const [api, reasons] of Object.entries(apiToReasons)) {
|
||||
merged.push({ api, reason: Array.from(reasons).join(" ") });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
exports.mergeRequiredAPIs = mergeRequiredAPIs;
|
||||
/* @internal */
|
||||
async function loadStack(functionsDir) {
|
||||
const endpoints = {};
|
||||
const requiredAPIs = [];
|
||||
const extensions = {};
|
||||
const mod = await loadModule(functionsDir);
|
||||
extractStack(mod, endpoints, requiredAPIs, extensions);
|
||||
const stack = {
|
||||
endpoints,
|
||||
specVersion: "v1alpha1",
|
||||
requiredAPIs: mergeRequiredAPIs(requiredAPIs),
|
||||
extensions,
|
||||
};
|
||||
if (params.declaredParams.length > 0) {
|
||||
stack.params = params.declaredParams.map((p) => p.toSpec());
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
exports.loadStack = loadStack;
|
||||
116
node_modules/firebase-functions/lib/runtime/manifest.d.ts
generated
vendored
Normal file
116
node_modules/firebase-functions/lib/runtime/manifest.d.ts
generated
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
import { ResetValue } from "../common/options";
|
||||
import { Expression } from "../params";
|
||||
import { WireParamSpec, SecretParam } from "../params/types";
|
||||
/**
|
||||
* A definition of an extension as appears in the Manifest.
|
||||
* Exactly one of ref or localPath must be present.
|
||||
*/
|
||||
export interface ManifestExtension {
|
||||
params: Record<string, string | SecretParam>;
|
||||
ref?: string;
|
||||
localPath?: string;
|
||||
events: string[];
|
||||
}
|
||||
/**
|
||||
* A definition of a function as appears in the Manifest.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface ManifestEndpoint {
|
||||
entryPoint?: string;
|
||||
region?: string[];
|
||||
omit?: boolean | Expression<boolean>;
|
||||
platform?: string;
|
||||
availableMemoryMb?: number | Expression<number> | ResetValue;
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
concurrency?: number | Expression<number> | ResetValue;
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
vpc?: {
|
||||
connector: string | Expression<string>;
|
||||
egressSettings?: string | Expression<string> | ResetValue;
|
||||
} | ResetValue;
|
||||
serviceAccountEmail?: string | Expression<string> | ResetValue;
|
||||
cpu?: number | "gcf_gen1";
|
||||
labels?: Record<string, string>;
|
||||
ingressSettings?: string | Expression<string> | ResetValue;
|
||||
environmentVariables?: Record<string, string>;
|
||||
secretEnvironmentVariables?: Array<{
|
||||
key: string;
|
||||
secret?: string;
|
||||
}>;
|
||||
httpsTrigger?: {
|
||||
invoker?: string[];
|
||||
};
|
||||
callableTrigger?: {
|
||||
genkitAction?: string;
|
||||
};
|
||||
eventTrigger?: {
|
||||
eventFilters: Record<string, string | Expression<string>>;
|
||||
eventFilterPathPatterns?: Record<string, string | Expression<string>>;
|
||||
channel?: string;
|
||||
eventType: string;
|
||||
retry: boolean | Expression<boolean> | ResetValue;
|
||||
region?: string;
|
||||
serviceAccountEmail?: string | ResetValue;
|
||||
};
|
||||
taskQueueTrigger?: {
|
||||
retryConfig?: {
|
||||
maxAttempts?: number | Expression<number> | ResetValue;
|
||||
maxRetrySeconds?: number | Expression<number> | ResetValue;
|
||||
maxBackoffSeconds?: number | Expression<number> | ResetValue;
|
||||
maxDoublings?: number | Expression<number> | ResetValue;
|
||||
minBackoffSeconds?: number | Expression<number> | ResetValue;
|
||||
};
|
||||
rateLimits?: {
|
||||
maxConcurrentDispatches?: number | Expression<number> | ResetValue;
|
||||
maxDispatchesPerSecond?: number | Expression<number> | ResetValue;
|
||||
};
|
||||
};
|
||||
scheduleTrigger?: {
|
||||
schedule: string | Expression<string>;
|
||||
timeZone?: string | Expression<string> | ResetValue;
|
||||
retryConfig?: {
|
||||
retryCount?: number | Expression<number> | ResetValue;
|
||||
maxRetrySeconds?: string | Expression<string> | ResetValue;
|
||||
minBackoffSeconds?: string | Expression<string> | ResetValue;
|
||||
maxBackoffSeconds?: string | Expression<string> | ResetValue;
|
||||
maxDoublings?: number | Expression<number> | ResetValue;
|
||||
maxRetryDuration?: string | Expression<string> | ResetValue;
|
||||
minBackoffDuration?: string | Expression<string> | ResetValue;
|
||||
maxBackoffDuration?: string | Expression<string> | ResetValue;
|
||||
};
|
||||
};
|
||||
blockingTrigger?: {
|
||||
eventType: string;
|
||||
options?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Description of API required for this stack.
|
||||
* @alpha
|
||||
*/
|
||||
export interface ManifestRequiredAPI {
|
||||
api: string;
|
||||
reason: string;
|
||||
}
|
||||
/**
|
||||
* A definition of a function/extension deployment as appears in the Manifest.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface ManifestStack {
|
||||
specVersion: "v1alpha1";
|
||||
params?: WireParamSpec<any>[];
|
||||
requiredAPIs: ManifestRequiredAPI[];
|
||||
endpoints: Record<string, ManifestEndpoint>;
|
||||
extensions?: Record<string, ManifestExtension>;
|
||||
}
|
||||
/**
|
||||
* Returns the JSON representation of a ManifestStack, which has CEL
|
||||
* expressions in its options as object types, with its expressions
|
||||
* transformed into the actual CEL strings.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export declare function stackToWire(stack: ManifestStack): Record<string, unknown>;
|
||||
159
node_modules/firebase-functions/lib/runtime/manifest.js
generated
vendored
Normal file
159
node_modules/firebase-functions/lib/runtime/manifest.js
generated
vendored
Normal file
@@ -0,0 +1,159 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initV2ScheduleTrigger = exports.initV1ScheduleTrigger = exports.initTaskQueueTrigger = exports.initV2Endpoint = exports.initV1Endpoint = exports.stackToWire = void 0;
|
||||
const options_1 = require("../common/options");
|
||||
const params_1 = require("../params");
|
||||
/**
|
||||
* Returns the JSON representation of a ManifestStack, which has CEL
|
||||
* expressions in its options as object types, with its expressions
|
||||
* transformed into the actual CEL strings.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
function stackToWire(stack) {
|
||||
const wireStack = stack;
|
||||
const traverse = function traverse(obj) {
|
||||
for (const [key, val] of Object.entries(obj)) {
|
||||
if (val instanceof params_1.Expression) {
|
||||
obj[key] = val.toCEL();
|
||||
}
|
||||
else if (val instanceof options_1.ResetValue) {
|
||||
obj[key] = val.toJSON();
|
||||
}
|
||||
else if (typeof val === "object" && val !== null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
traverse(val);
|
||||
}
|
||||
}
|
||||
};
|
||||
traverse(wireStack.endpoints);
|
||||
return wireStack;
|
||||
}
|
||||
exports.stackToWire = stackToWire;
|
||||
const RESETTABLE_OPTIONS = {
|
||||
availableMemoryMb: null,
|
||||
timeoutSeconds: null,
|
||||
minInstances: null,
|
||||
maxInstances: null,
|
||||
ingressSettings: null,
|
||||
concurrency: null,
|
||||
serviceAccountEmail: null,
|
||||
vpc: null,
|
||||
};
|
||||
function initEndpoint(resetOptions, ...opts) {
|
||||
const endpoint = {};
|
||||
if (opts.every((opt) => !(opt === null || opt === void 0 ? void 0 : opt.preserveExternalChanges))) {
|
||||
for (const key of Object.keys(resetOptions)) {
|
||||
endpoint[key] = options_1.RESET_VALUE;
|
||||
}
|
||||
}
|
||||
return endpoint;
|
||||
}
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function initV1Endpoint(...opts) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { concurrency, ...resetOpts } = RESETTABLE_OPTIONS;
|
||||
return initEndpoint({ ...resetOpts }, ...opts);
|
||||
}
|
||||
exports.initV1Endpoint = initV1Endpoint;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function initV2Endpoint(...opts) {
|
||||
return initEndpoint(RESETTABLE_OPTIONS, ...opts);
|
||||
}
|
||||
exports.initV2Endpoint = initV2Endpoint;
|
||||
const RESETTABLE_RETRY_CONFIG_OPTIONS = {
|
||||
maxAttempts: null,
|
||||
maxDoublings: null,
|
||||
maxBackoffSeconds: null,
|
||||
maxRetrySeconds: null,
|
||||
minBackoffSeconds: null,
|
||||
};
|
||||
const RESETTABLE_RATE_LIMITS_OPTIONS = {
|
||||
maxConcurrentDispatches: null,
|
||||
maxDispatchesPerSecond: null,
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function initTaskQueueTrigger(...opts) {
|
||||
const taskQueueTrigger = {
|
||||
retryConfig: {},
|
||||
rateLimits: {},
|
||||
};
|
||||
if (opts.every((opt) => !(opt === null || opt === void 0 ? void 0 : opt.preserveExternalChanges))) {
|
||||
for (const key of Object.keys(RESETTABLE_RETRY_CONFIG_OPTIONS)) {
|
||||
taskQueueTrigger.retryConfig[key] = options_1.RESET_VALUE;
|
||||
}
|
||||
for (const key of Object.keys(RESETTABLE_RATE_LIMITS_OPTIONS)) {
|
||||
taskQueueTrigger.rateLimits[key] = options_1.RESET_VALUE;
|
||||
}
|
||||
}
|
||||
return taskQueueTrigger;
|
||||
}
|
||||
exports.initTaskQueueTrigger = initTaskQueueTrigger;
|
||||
const RESETTABLE_V1_SCHEDULE_OPTIONS = {
|
||||
retryCount: null,
|
||||
maxDoublings: null,
|
||||
maxRetryDuration: null,
|
||||
maxBackoffDuration: null,
|
||||
minBackoffDuration: null,
|
||||
};
|
||||
const RESETTABLE_V2_SCHEDULE_OPTIONS = {
|
||||
retryCount: null,
|
||||
maxDoublings: null,
|
||||
maxRetrySeconds: null,
|
||||
minBackoffSeconds: null,
|
||||
maxBackoffSeconds: null,
|
||||
};
|
||||
function initScheduleTrigger(resetOptions, schedule, ...opts) {
|
||||
let scheduleTrigger = {
|
||||
schedule,
|
||||
retryConfig: {},
|
||||
};
|
||||
if (opts.every((opt) => !(opt === null || opt === void 0 ? void 0 : opt.preserveExternalChanges))) {
|
||||
for (const key of Object.keys(resetOptions)) {
|
||||
scheduleTrigger.retryConfig[key] = options_1.RESET_VALUE;
|
||||
}
|
||||
scheduleTrigger = { ...scheduleTrigger, timeZone: options_1.RESET_VALUE };
|
||||
}
|
||||
return scheduleTrigger;
|
||||
}
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function initV1ScheduleTrigger(schedule, ...opts) {
|
||||
return initScheduleTrigger(RESETTABLE_V1_SCHEDULE_OPTIONS, schedule, ...opts);
|
||||
}
|
||||
exports.initV1ScheduleTrigger = initV1ScheduleTrigger;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function initV2ScheduleTrigger(schedule, ...opts) {
|
||||
return initScheduleTrigger(RESETTABLE_V2_SCHEDULE_OPTIONS, schedule, ...opts);
|
||||
}
|
||||
exports.initV2ScheduleTrigger = initV2ScheduleTrigger;
|
||||
273
node_modules/firebase-functions/lib/v1/cloud-functions.d.ts
generated
vendored
Normal file
273
node_modules/firebase-functions/lib/v1/cloud-functions.d.ts
generated
vendored
Normal file
@@ -0,0 +1,273 @@
|
||||
import { Request, Response } from "express";
|
||||
import { DeploymentOptions, FailurePolicy, Schedule } from "./function-configuration";
|
||||
export { Request, Response };
|
||||
import { ManifestEndpoint, ManifestRequiredAPI } from "../runtime/manifest";
|
||||
export { Change } from "../common/change";
|
||||
/**
|
||||
* Wire format for an event.
|
||||
*/
|
||||
export interface Event {
|
||||
/**
|
||||
* Wire format for an event context.
|
||||
*/
|
||||
context: {
|
||||
eventId: string;
|
||||
timestamp: string;
|
||||
eventType: string;
|
||||
resource: Resource;
|
||||
domain?: string;
|
||||
auth?: {
|
||||
variable?: {
|
||||
uid?: string;
|
||||
token?: string;
|
||||
};
|
||||
admin: boolean;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Event data over wire.
|
||||
*/
|
||||
data: any;
|
||||
}
|
||||
/**
|
||||
* The context in which an event occurred.
|
||||
*
|
||||
* @remarks
|
||||
* An EventContext describes:
|
||||
* - The time an event occurred.
|
||||
* - A unique identifier of the event.
|
||||
* - The resource on which the event occurred, if applicable.
|
||||
* - Authorization of the request that triggered the event, if applicable and
|
||||
* available.
|
||||
*/
|
||||
export interface EventContext<Params = Record<string, string>> {
|
||||
/**
|
||||
* Authentication information for the user that triggered the function.
|
||||
*
|
||||
* @remarks
|
||||
* This object contains `uid` and `token` properties for authenticated users.
|
||||
* For more detail including token keys, see the
|
||||
* {@link https://firebase.google.com/docs/reference/rules/rules#properties | security rules reference}.
|
||||
*
|
||||
* This field is only populated for Realtime Database triggers and Callable
|
||||
* functions. For an unauthenticated user, this field is null. For Firebase
|
||||
* admin users and event types that do not provide user information, this field
|
||||
* does not exist.
|
||||
*/
|
||||
auth?: {
|
||||
token: object;
|
||||
uid: string;
|
||||
};
|
||||
/**
|
||||
* The level of permissions for a user.
|
||||
*
|
||||
* @remarks
|
||||
* Valid values are:
|
||||
*
|
||||
* - `ADMIN`: Developer user or user authenticated via a service account.
|
||||
*
|
||||
* - `USER`: Known user.
|
||||
*
|
||||
* - `UNAUTHENTICATED`: Unauthenticated action
|
||||
*
|
||||
* - `null`: For event types that do not provide user information (all except
|
||||
* Realtime Database).
|
||||
*/
|
||||
authType?: "ADMIN" | "USER" | "UNAUTHENTICATED";
|
||||
/**
|
||||
* The event’s unique identifier.
|
||||
*/
|
||||
eventId: string;
|
||||
/**
|
||||
* Type of event.
|
||||
*
|
||||
* @remarks
|
||||
* Possible values are:
|
||||
*
|
||||
* - `google.analytics.event.log`
|
||||
*
|
||||
* - `google.firebase.auth.user.create`
|
||||
*
|
||||
* - `google.firebase.auth.user.delete`
|
||||
*
|
||||
* - `google.firebase.database.ref.write`
|
||||
*
|
||||
* - `google.firebase.database.ref.create`
|
||||
*
|
||||
* - `google.firebase.database.ref.update`
|
||||
*
|
||||
* - `google.firebase.database.ref.delete`
|
||||
*
|
||||
* - `google.firestore.document.write`
|
||||
*
|
||||
* - `google.firestore.document.create`
|
||||
*
|
||||
* - `google.firestore.document.update`
|
||||
*
|
||||
* - `google.firestore.document.delete`
|
||||
*
|
||||
* - `google.pubsub.topic.publish`
|
||||
*
|
||||
* - `google.firebase.remoteconfig.update`
|
||||
*
|
||||
* - `google.storage.object.finalize`
|
||||
*
|
||||
* - `google.storage.object.archive`
|
||||
*
|
||||
* - `google.storage.object.delete`
|
||||
*
|
||||
* - `google.storage.object.metadataUpdate`
|
||||
*
|
||||
* - `google.testing.testMatrix.complete`
|
||||
*/
|
||||
eventType: string;
|
||||
/**
|
||||
* An object containing the values of the wildcards in the `path` parameter
|
||||
* provided to the {@link fireabase-functions.v1.database#ref | `ref()`} method for a Realtime Database trigger.
|
||||
*/
|
||||
params: Params;
|
||||
/**
|
||||
* The resource that emitted the event.
|
||||
*
|
||||
* @remarks
|
||||
* Valid values are:
|
||||
*
|
||||
* Analytics: `projects/<projectId>/events/<analyticsEventType>`
|
||||
*
|
||||
* Realtime Database: `projects/_/instances/<databaseInstance>/refs/<databasePath>`
|
||||
*
|
||||
* Storage: `projects/_/buckets/<bucketName>/objects/<fileName>#<generation>`
|
||||
*
|
||||
* Authentication: `projects/<projectId>`
|
||||
*
|
||||
* Pub/Sub: `projects/<projectId>/topics/<topicName>`
|
||||
*
|
||||
* Because Realtime Database instances and Cloud Storage buckets are globally
|
||||
* unique and not tied to the project, their resources start with `projects/_`.
|
||||
* Underscore is not a valid project name.
|
||||
*/
|
||||
resource: Resource;
|
||||
/**
|
||||
* Timestamp for the event as an {@link https://www.ietf.org/rfc/rfc3339.txt | RFC 3339} string.
|
||||
*/
|
||||
timestamp: string;
|
||||
}
|
||||
/**
|
||||
* Resource is a standard format for defining a resource
|
||||
* (google.rpc.context.AttributeContext.Resource). In Cloud Functions, it is the
|
||||
* resource that triggered the function - such as a storage bucket.
|
||||
*/
|
||||
export interface Resource {
|
||||
/** The name of the service that this resource belongs to. */
|
||||
service: string;
|
||||
/**
|
||||
* The stable identifier (name) of a resource on the service.
|
||||
* A resource can be logically identified as "//{resource.service}/{resource.name}"
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The type of the resource. The syntax is platform-specific because different platforms define their resources differently.
|
||||
* For Google APIs, the type format must be "{service}/{kind}"
|
||||
*/
|
||||
type?: string;
|
||||
/** Map of Resource's labels. */
|
||||
labels?: {
|
||||
[tag: string]: string;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* TriggerAnnotion is used internally by the firebase CLI to understand what
|
||||
* type of Cloud Function to deploy.
|
||||
*/
|
||||
interface TriggerAnnotation {
|
||||
availableMemoryMb?: number;
|
||||
blockingTrigger?: {
|
||||
eventType: string;
|
||||
options?: Record<string, unknown>;
|
||||
};
|
||||
eventTrigger?: {
|
||||
eventType: string;
|
||||
resource: string;
|
||||
service: string;
|
||||
};
|
||||
failurePolicy?: FailurePolicy;
|
||||
httpsTrigger?: {
|
||||
invoker?: string[];
|
||||
};
|
||||
labels?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
regions?: string[];
|
||||
schedule?: Schedule;
|
||||
timeout?: string;
|
||||
vpcConnector?: string;
|
||||
vpcConnectorEgressSettings?: string;
|
||||
serviceAccountEmail?: string;
|
||||
ingressSettings?: string;
|
||||
secrets?: string[];
|
||||
}
|
||||
/**
|
||||
* A Runnable has a `run` method which directly invokes the user-defined
|
||||
* function - useful for unit testing.
|
||||
*/
|
||||
export interface Runnable<T> {
|
||||
/** Directly invoke the user defined function. */
|
||||
run: (data: T, context: any) => PromiseLike<any> | any;
|
||||
}
|
||||
/**
|
||||
* The function type for HTTPS triggers. This should be exported from your
|
||||
* JavaScript file to define a Cloud Function.
|
||||
*
|
||||
* @remarks
|
||||
* This type is a special JavaScript function which takes Express
|
||||
* {@link https://expressjs.com/en/api.html#req | `Request` } and
|
||||
* {@link https://expressjs.com/en/api.html#res | `Response` } objects as its only
|
||||
* arguments.
|
||||
*/
|
||||
export interface HttpsFunction {
|
||||
(req: Request, resp: Response): void | Promise<void>;
|
||||
/** @alpha */
|
||||
__trigger: TriggerAnnotation;
|
||||
/** @alpha */
|
||||
__endpoint: ManifestEndpoint;
|
||||
/** @alpha */
|
||||
__requiredAPIs?: ManifestRequiredAPI[];
|
||||
}
|
||||
/**
|
||||
* The function type for Auth Blocking triggers.
|
||||
*
|
||||
* @remarks
|
||||
* This type is a special JavaScript function for Auth Blocking triggers which takes Express
|
||||
* {@link https://expressjs.com/en/api.html#req | `Request` } and
|
||||
* {@link https://expressjs.com/en/api.html#res | `Response` } objects as its only
|
||||
* arguments.
|
||||
*/
|
||||
export interface BlockingFunction {
|
||||
/** @public */
|
||||
(req: Request, resp: Response): void | Promise<void>;
|
||||
/** @alpha */
|
||||
__trigger: TriggerAnnotation;
|
||||
/** @alpha */
|
||||
__endpoint: ManifestEndpoint;
|
||||
/** @alpha */
|
||||
__requiredAPIs?: ManifestRequiredAPI[];
|
||||
}
|
||||
/**
|
||||
* The function type for all non-HTTPS triggers. This should be exported
|
||||
* from your JavaScript file to define a Cloud Function.
|
||||
*
|
||||
* This type is a special JavaScript function which takes a templated
|
||||
* `Event` object as its only argument.
|
||||
*/
|
||||
export interface CloudFunction<T> extends Runnable<T> {
|
||||
(input: any, context?: any): PromiseLike<any> | any;
|
||||
/** @alpha */
|
||||
__trigger: TriggerAnnotation;
|
||||
/** @alpha */
|
||||
__endpoint: ManifestEndpoint;
|
||||
/** @alpha */
|
||||
__requiredAPIs?: ManifestRequiredAPI[];
|
||||
}
|
||||
/** @hidden */
|
||||
export declare function optionsToTrigger(options: DeploymentOptions): any;
|
||||
export declare function optionsToEndpoint(options: DeploymentOptions): ManifestEndpoint;
|
||||
257
node_modules/firebase-functions/lib/v1/cloud-functions.js
generated
vendored
Normal file
257
node_modules/firebase-functions/lib/v1/cloud-functions.js
generated
vendored
Normal file
@@ -0,0 +1,257 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.optionsToEndpoint = exports.optionsToTrigger = exports.makeCloudFunction = exports.Change = void 0;
|
||||
const logger_1 = require("../logger");
|
||||
const function_configuration_1 = require("./function-configuration");
|
||||
const encoding_1 = require("../common/encoding");
|
||||
const manifest_1 = require("../runtime/manifest");
|
||||
const options_1 = require("../common/options");
|
||||
const types_1 = require("../params/types");
|
||||
const onInit_1 = require("../common/onInit");
|
||||
var change_1 = require("../common/change");
|
||||
Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
|
||||
/** @internal */
|
||||
const WILDCARD_REGEX = new RegExp("{[^/{}]*}", "g");
|
||||
/** @internal */
|
||||
function makeCloudFunction({ contextOnlyHandler, dataConstructor = (raw) => raw.data, eventType, handler, labels = {}, legacyEventType, options = {}, provider, service, triggerResource, }) {
|
||||
handler = (0, onInit_1.withInit)(handler !== null && handler !== void 0 ? handler : contextOnlyHandler);
|
||||
const cloudFunction = (data, context) => {
|
||||
if (legacyEventType && context.eventType === legacyEventType) {
|
||||
/*
|
||||
* v1beta1 event flow has different format for context, transform them to
|
||||
* new format.
|
||||
*/
|
||||
context.eventType = provider + "." + eventType;
|
||||
context.resource = {
|
||||
service,
|
||||
name: context.resource,
|
||||
};
|
||||
}
|
||||
const event = {
|
||||
data,
|
||||
context,
|
||||
};
|
||||
if (provider === "google.firebase.database") {
|
||||
context.authType = _detectAuthType(event);
|
||||
if (context.authType !== "ADMIN") {
|
||||
context.auth = _makeAuth(event, context.authType);
|
||||
}
|
||||
else {
|
||||
delete context.auth;
|
||||
}
|
||||
}
|
||||
if (triggerResource() == null) {
|
||||
Object.defineProperty(context, "params", {
|
||||
get: () => {
|
||||
throw new Error("context.params is not available when using the handler namespace.");
|
||||
},
|
||||
});
|
||||
}
|
||||
else {
|
||||
context.params = context.params || _makeParams(context, triggerResource);
|
||||
}
|
||||
let promise;
|
||||
if (labels && labels["deployment-scheduled"]) {
|
||||
// Scheduled function do not have meaningful data, so exclude it
|
||||
promise = contextOnlyHandler(context);
|
||||
}
|
||||
else {
|
||||
const dataOrChange = dataConstructor(event);
|
||||
promise = handler(dataOrChange, context);
|
||||
}
|
||||
if (typeof promise === "undefined") {
|
||||
(0, logger_1.warn)("Function returned undefined, expected Promise or value");
|
||||
}
|
||||
return Promise.resolve(promise);
|
||||
};
|
||||
Object.defineProperty(cloudFunction, "__trigger", {
|
||||
get: () => {
|
||||
if (triggerResource() == null) {
|
||||
return {};
|
||||
}
|
||||
const trigger = {
|
||||
...optionsToTrigger(options),
|
||||
eventTrigger: {
|
||||
resource: triggerResource(),
|
||||
eventType: legacyEventType || provider + "." + eventType,
|
||||
service,
|
||||
},
|
||||
};
|
||||
if (!!labels && Object.keys(labels).length) {
|
||||
trigger.labels = { ...trigger.labels, ...labels };
|
||||
}
|
||||
return trigger;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(cloudFunction, "__endpoint", {
|
||||
get: () => {
|
||||
if (triggerResource() == null) {
|
||||
return undefined;
|
||||
}
|
||||
const endpoint = {
|
||||
platform: "gcfv1",
|
||||
...(0, manifest_1.initV1Endpoint)(options),
|
||||
...optionsToEndpoint(options),
|
||||
};
|
||||
if (options.schedule) {
|
||||
endpoint.scheduleTrigger = (0, manifest_1.initV1ScheduleTrigger)(options.schedule.schedule, options);
|
||||
(0, encoding_1.copyIfPresent)(endpoint.scheduleTrigger, options.schedule, "timeZone");
|
||||
(0, encoding_1.copyIfPresent)(endpoint.scheduleTrigger.retryConfig, options.schedule.retryConfig, "retryCount", "maxDoublings", "maxBackoffDuration", "maxRetryDuration", "minBackoffDuration");
|
||||
}
|
||||
else {
|
||||
endpoint.eventTrigger = {
|
||||
eventType: legacyEventType || provider + "." + eventType,
|
||||
eventFilters: {
|
||||
resource: triggerResource(),
|
||||
},
|
||||
retry: !!options.failurePolicy,
|
||||
};
|
||||
}
|
||||
// Note: We intentionally don't make use of labels args here.
|
||||
// labels is used to pass SDK-defined labels to the trigger, which isn't
|
||||
// something we will do in the container contract world.
|
||||
endpoint.labels = { ...endpoint.labels };
|
||||
return endpoint;
|
||||
},
|
||||
});
|
||||
if (options.schedule) {
|
||||
cloudFunction.__requiredAPIs = [
|
||||
{
|
||||
api: "cloudscheduler.googleapis.com",
|
||||
reason: "Needed for scheduled functions.",
|
||||
},
|
||||
];
|
||||
}
|
||||
cloudFunction.run = handler || contextOnlyHandler;
|
||||
return cloudFunction;
|
||||
}
|
||||
exports.makeCloudFunction = makeCloudFunction;
|
||||
function _makeParams(context, triggerResourceGetter) {
|
||||
var _a, _b, _c;
|
||||
if (context.params) {
|
||||
// In unit testing, user may directly provide `context.params`.
|
||||
return context.params;
|
||||
}
|
||||
if (!context.resource) {
|
||||
// In unit testing, `resource` may be unpopulated for a test event.
|
||||
return {};
|
||||
}
|
||||
const triggerResource = triggerResourceGetter();
|
||||
const wildcards = triggerResource.match(WILDCARD_REGEX);
|
||||
const params = {};
|
||||
// Note: some tests don't set context.resource.name
|
||||
const eventResourceParts = (_c = (_b = (_a = context === null || context === void 0 ? void 0 : context.resource) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.split) === null || _c === void 0 ? void 0 : _c.call(_b, "/");
|
||||
if (wildcards && eventResourceParts) {
|
||||
const triggerResourceParts = triggerResource.split("/");
|
||||
for (const wildcard of wildcards) {
|
||||
const wildcardNoBraces = wildcard.slice(1, -1);
|
||||
const position = triggerResourceParts.indexOf(wildcard);
|
||||
params[wildcardNoBraces] = eventResourceParts[position];
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
function _makeAuth(event, authType) {
|
||||
var _a, _b, _c, _d, _e, _f;
|
||||
if (authType === "UNAUTHENTICATED") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
uid: (_c = (_b = (_a = event.context) === null || _a === void 0 ? void 0 : _a.auth) === null || _b === void 0 ? void 0 : _b.variable) === null || _c === void 0 ? void 0 : _c.uid,
|
||||
token: (_f = (_e = (_d = event.context) === null || _d === void 0 ? void 0 : _d.auth) === null || _e === void 0 ? void 0 : _e.variable) === null || _f === void 0 ? void 0 : _f.token,
|
||||
};
|
||||
}
|
||||
function _detectAuthType(event) {
|
||||
var _a, _b, _c, _d;
|
||||
if ((_b = (_a = event.context) === null || _a === void 0 ? void 0 : _a.auth) === null || _b === void 0 ? void 0 : _b.admin) {
|
||||
return "ADMIN";
|
||||
}
|
||||
if ((_d = (_c = event.context) === null || _c === void 0 ? void 0 : _c.auth) === null || _d === void 0 ? void 0 : _d.variable) {
|
||||
return "USER";
|
||||
}
|
||||
return "UNAUTHENTICATED";
|
||||
}
|
||||
/** @hidden */
|
||||
function optionsToTrigger(options) {
|
||||
const trigger = {};
|
||||
(0, encoding_1.copyIfPresent)(trigger, options, "regions", "schedule", "minInstances", "maxInstances", "ingressSettings", "vpcConnectorEgressSettings", "vpcConnector", "labels", "secrets");
|
||||
(0, encoding_1.convertIfPresent)(trigger, options, "failurePolicy", "failurePolicy", (policy) => {
|
||||
if (policy === false) {
|
||||
return undefined;
|
||||
}
|
||||
else if (policy === true) {
|
||||
return function_configuration_1.DEFAULT_FAILURE_POLICY;
|
||||
}
|
||||
else {
|
||||
return policy;
|
||||
}
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(trigger, options, "timeout", "timeoutSeconds", encoding_1.durationFromSeconds);
|
||||
(0, encoding_1.convertIfPresent)(trigger, options, "availableMemoryMb", "memory", (mem) => {
|
||||
const memoryLookup = {
|
||||
"128MB": 128,
|
||||
"256MB": 256,
|
||||
"512MB": 512,
|
||||
"1GB": 1024,
|
||||
"2GB": 2048,
|
||||
"4GB": 4096,
|
||||
"8GB": 8192,
|
||||
};
|
||||
return memoryLookup[mem];
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(trigger, options, "serviceAccountEmail", "serviceAccount", encoding_1.serviceAccountFromShorthand);
|
||||
return trigger;
|
||||
}
|
||||
exports.optionsToTrigger = optionsToTrigger;
|
||||
function optionsToEndpoint(options) {
|
||||
const endpoint = {};
|
||||
(0, encoding_1.copyIfPresent)(endpoint, options, "omit", "minInstances", "maxInstances", "ingressSettings", "labels", "timeoutSeconds");
|
||||
(0, encoding_1.convertIfPresent)(endpoint, options, "region", "regions");
|
||||
(0, encoding_1.convertIfPresent)(endpoint, options, "serviceAccountEmail", "serviceAccount", (sa) => sa);
|
||||
(0, encoding_1.convertIfPresent)(endpoint, options, "secretEnvironmentVariables", "secrets", (secrets) => secrets.map((secret) => ({ key: secret instanceof types_1.SecretParam ? secret.name : secret })));
|
||||
if ((options === null || options === void 0 ? void 0 : options.vpcConnector) !== undefined) {
|
||||
if (options.vpcConnector === null || options.vpcConnector instanceof options_1.ResetValue) {
|
||||
endpoint.vpc = function_configuration_1.RESET_VALUE;
|
||||
}
|
||||
else {
|
||||
const vpc = { connector: options.vpcConnector };
|
||||
(0, encoding_1.convertIfPresent)(vpc, options, "egressSettings", "vpcConnectorEgressSettings");
|
||||
endpoint.vpc = vpc;
|
||||
}
|
||||
}
|
||||
(0, encoding_1.convertIfPresent)(endpoint, options, "availableMemoryMb", "memory", (mem) => {
|
||||
const memoryLookup = {
|
||||
"128MB": 128,
|
||||
"256MB": 256,
|
||||
"512MB": 512,
|
||||
"1GB": 1024,
|
||||
"2GB": 2048,
|
||||
"4GB": 4096,
|
||||
"8GB": 8192,
|
||||
};
|
||||
return typeof mem === "object" ? mem : memoryLookup[mem];
|
||||
});
|
||||
return endpoint;
|
||||
}
|
||||
exports.optionsToEndpoint = optionsToEndpoint;
|
||||
10
node_modules/firebase-functions/lib/v1/config.d.ts
generated
vendored
Normal file
10
node_modules/firebase-functions/lib/v1/config.d.ts
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
export { firebaseConfig } from "../common/config";
|
||||
/**
|
||||
* Store and retrieve project configuration data such as third-party API
|
||||
* keys or other settings. You can set configuration values using the
|
||||
* Firebase CLI as described in
|
||||
* https://firebase.google.com/docs/functions/config-env.
|
||||
*
|
||||
* @deprecated Using functions.config() is discouraged. See https://firebase.google.com/docs/functions/config-env.
|
||||
*/
|
||||
export declare function config(): Record<string, any>;
|
||||
77
node_modules/firebase-functions/lib/v1/config.js
generated
vendored
Normal file
77
node_modules/firebase-functions/lib/v1/config.js
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.config = exports.resetCache = exports.singleton = exports.firebaseConfig = void 0;
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
var config_1 = require("../common/config");
|
||||
Object.defineProperty(exports, "firebaseConfig", { enumerable: true, get: function () { return config_1.firebaseConfig; } });
|
||||
/** @internal */
|
||||
function resetCache() {
|
||||
exports.singleton = undefined;
|
||||
}
|
||||
exports.resetCache = resetCache;
|
||||
/**
|
||||
* Store and retrieve project configuration data such as third-party API
|
||||
* keys or other settings. You can set configuration values using the
|
||||
* Firebase CLI as described in
|
||||
* https://firebase.google.com/docs/functions/config-env.
|
||||
*
|
||||
* @deprecated Using functions.config() is discouraged. See https://firebase.google.com/docs/functions/config-env.
|
||||
*/
|
||||
function config() {
|
||||
// K_CONFIGURATION is only set in GCFv2
|
||||
if (process.env.K_CONFIGURATION) {
|
||||
throw new Error("functions.config() is no longer available in Cloud Functions for " +
|
||||
"Firebase v2. Please see the latest documentation for information " +
|
||||
"on how to transition to using environment variables");
|
||||
}
|
||||
if (typeof exports.singleton === "undefined") {
|
||||
init();
|
||||
}
|
||||
return exports.singleton;
|
||||
}
|
||||
exports.config = config;
|
||||
function init() {
|
||||
try {
|
||||
const parsed = JSON.parse(process.env.CLOUD_RUNTIME_CONFIG);
|
||||
delete parsed.firebase;
|
||||
exports.singleton = parsed;
|
||||
return;
|
||||
}
|
||||
catch (e) {
|
||||
// Do nothing
|
||||
}
|
||||
try {
|
||||
const configPath = process.env.CLOUD_RUNTIME_CONFIG || path.join(process.cwd(), ".runtimeconfig.json");
|
||||
const contents = fs.readFileSync(configPath);
|
||||
const parsed = JSON.parse(contents.toString("utf8"));
|
||||
delete parsed.firebase;
|
||||
exports.singleton = parsed;
|
||||
return;
|
||||
}
|
||||
catch (e) {
|
||||
// Do nothing
|
||||
}
|
||||
exports.singleton = {};
|
||||
}
|
||||
191
node_modules/firebase-functions/lib/v1/function-builder.d.ts
generated
vendored
Normal file
191
node_modules/firebase-functions/lib/v1/function-builder.d.ts
generated
vendored
Normal file
@@ -0,0 +1,191 @@
|
||||
import * as express from "express";
|
||||
import { ResetValue } from "../common/options";
|
||||
import { Expression } from "../params/types";
|
||||
import { EventContext } from "./cloud-functions";
|
||||
import { DeploymentOptions, RuntimeOptions, SUPPORTED_REGIONS } from "./function-configuration";
|
||||
import * as analytics from "./providers/analytics";
|
||||
import * as auth from "./providers/auth";
|
||||
import * as database from "./providers/database";
|
||||
import * as firestore from "./providers/firestore";
|
||||
import * as https from "./providers/https";
|
||||
import * as pubsub from "./providers/pubsub";
|
||||
import * as remoteConfig from "./providers/remoteConfig";
|
||||
import * as storage from "./providers/storage";
|
||||
import * as tasks from "./providers/tasks";
|
||||
import * as testLab from "./providers/testLab";
|
||||
/**
|
||||
* Configure the regions that the function is deployed to.
|
||||
* @param regions One of more region strings.
|
||||
* @example
|
||||
* functions.region('us-east1')
|
||||
* @example
|
||||
* functions.region('us-east1', 'us-central1')
|
||||
*/
|
||||
export declare function region(...regions: Array<(typeof SUPPORTED_REGIONS)[number] | string | Expression<string> | ResetValue>): FunctionBuilder;
|
||||
/**
|
||||
* Configure runtime options for the function.
|
||||
* @param runtimeOptions Object with optional fields:
|
||||
* 1. `memory`: amount of memory to allocate to the function, possible values
|
||||
* are: '128MB', '256MB', '512MB', '1GB', '2GB', '4GB', and '8GB'.
|
||||
* 2. `timeoutSeconds`: timeout for the function in seconds, possible values are
|
||||
* 0 to 540.
|
||||
* 3. `failurePolicy`: failure policy of the function, with boolean `true` being
|
||||
* equivalent to providing an empty retry object.
|
||||
* 4. `vpcConnector`: id of a VPC connector in same project and region.
|
||||
* 5. `vpcConnectorEgressSettings`: when a vpcConnector is set, control which
|
||||
* egress traffic is sent through the vpcConnector.
|
||||
* 6. `serviceAccount`: Specific service account for the function.
|
||||
* 7. `ingressSettings`: ingress settings for the function, which control where a HTTPS
|
||||
* function can be called from.
|
||||
*
|
||||
* Value must not be null.
|
||||
*/
|
||||
export declare function runWith(runtimeOptions: RuntimeOptions): FunctionBuilder;
|
||||
export declare class FunctionBuilder {
|
||||
private options;
|
||||
constructor(options: DeploymentOptions);
|
||||
/**
|
||||
* Configure the regions that the function is deployed to.
|
||||
* @param regions One or more region strings.
|
||||
* @example
|
||||
* functions.region('us-east1')
|
||||
* @example
|
||||
* functions.region('us-east1', 'us-central1')
|
||||
*/
|
||||
region(...regions: Array<(typeof SUPPORTED_REGIONS)[number] | string | Expression<string> | ResetValue>): FunctionBuilder;
|
||||
/**
|
||||
* Configure runtime options for the function.
|
||||
* @param runtimeOptions Object with optional fields:
|
||||
* 1. `memory`: amount of memory to allocate to the function, possible values
|
||||
* are: '128MB', '256MB', '512MB', '1GB', '2GB', '4GB', and '8GB'.
|
||||
* 2. `timeoutSeconds`: timeout for the function in seconds, possible values are
|
||||
* 0 to 540.
|
||||
* 3. `failurePolicy`: failure policy of the function, with boolean `true` being
|
||||
* equivalent to providing an empty retry object.
|
||||
* 4. `vpcConnector`: id of a VPC connector in the same project and region
|
||||
* 5. `vpcConnectorEgressSettings`: when a `vpcConnector` is set, control which
|
||||
* egress traffic is sent through the `vpcConnector`.
|
||||
*
|
||||
* Value must not be null.
|
||||
*/
|
||||
runWith(runtimeOptions: RuntimeOptions): FunctionBuilder;
|
||||
get https(): {
|
||||
/**
|
||||
* Handle HTTP requests.
|
||||
* @param handler A function that takes a request and response object,
|
||||
* same signature as an Express app.
|
||||
*/
|
||||
onRequest: (handler: (req: https.Request, resp: express.Response) => void | Promise<void>) => import("./cloud-functions").HttpsFunction;
|
||||
/**
|
||||
* Declares a callable method for clients to call using a Firebase SDK.
|
||||
* @param handler A method that takes a data and context and returns a value.
|
||||
*/
|
||||
onCall: (handler: (data: any, context: https.CallableContext) => any | Promise<any>) => import("./cloud-functions").HttpsFunction & import("./cloud-functions").Runnable<any>;
|
||||
};
|
||||
get tasks(): {
|
||||
/**
|
||||
* Declares a task queue function for clients to call using a Firebase Admin SDK.
|
||||
* @param options Configurations for the task queue function.
|
||||
*/
|
||||
/** @hidden */
|
||||
taskQueue: (options?: tasks.TaskQueueOptions) => tasks.TaskQueueBuilder;
|
||||
};
|
||||
get database(): {
|
||||
/**
|
||||
* Selects a database instance that will trigger the function. If omitted,
|
||||
* will pick the default database for your project.
|
||||
* @param instance The Realtime Database instance to use.
|
||||
*/
|
||||
instance: (instance: string) => database.InstanceBuilder;
|
||||
/**
|
||||
* Select Firebase Realtime Database Reference to listen to.
|
||||
*
|
||||
* This method behaves very similarly to the method of the same name in
|
||||
* the client and Admin Firebase SDKs. Any change to the Database that
|
||||
* affects the data at or below the provided `path` will fire an event in
|
||||
* Cloud Functions.
|
||||
*
|
||||
* There are three important differences between listening to a Realtime
|
||||
* Database event in Cloud Functions and using the Realtime Database in
|
||||
* the client and Admin SDKs:
|
||||
* 1. Cloud Functions allows wildcards in the `path` name. Any `path`
|
||||
* component in curly brackets (`{}`) is a wildcard that matches all
|
||||
* strings. The value that matched a certain invocation of a Cloud
|
||||
* Function is returned as part of the `context.params` object. For
|
||||
* example, `ref("messages/{messageId}")` matches changes at
|
||||
* `/messages/message1` or `/messages/message2`, resulting in
|
||||
* `context.params.messageId` being set to `"message1"` or
|
||||
* `"message2"`, respectively.
|
||||
* 2. Cloud Functions do not fire an event for data that already existed
|
||||
* before the Cloud Function was deployed.
|
||||
* 3. Cloud Function events have access to more information, including
|
||||
* information about the user who triggered the Cloud Function.
|
||||
* @param ref Path of the database to listen to.
|
||||
*/
|
||||
ref: <Ref extends string>(path: Ref) => database.RefBuilder<Ref>;
|
||||
};
|
||||
get firestore(): {
|
||||
/**
|
||||
* Select the Firestore document to listen to for events.
|
||||
* @param path Full database path to listen to. This includes the name of
|
||||
* the collection that the document is a part of. For example, if the
|
||||
* collection is named "users" and the document is named "Ada", then the
|
||||
* path is "/users/Ada".
|
||||
*/
|
||||
document: <Path extends string>(path: Path) => firestore.DocumentBuilder<Path>;
|
||||
/** @hidden */
|
||||
namespace: (namespace: string) => firestore.NamespaceBuilder;
|
||||
/** @hidden */
|
||||
database: (database: string) => firestore.DatabaseBuilder;
|
||||
};
|
||||
get analytics(): {
|
||||
/**
|
||||
* Select analytics events to listen to for events.
|
||||
* @param analyticsEventType Name of the analytics event type.
|
||||
*/
|
||||
event: (analyticsEventType: string) => analytics.AnalyticsEventBuilder;
|
||||
};
|
||||
get remoteConfig(): {
|
||||
/**
|
||||
* Handle all updates (including rollbacks) that affect a Remote Config
|
||||
* project.
|
||||
* @param handler A function that takes the updated Remote Config template
|
||||
* version metadata as an argument.
|
||||
*/
|
||||
onUpdate: (handler: (version: remoteConfig.TemplateVersion, context: EventContext) => PromiseLike<any> | any) => import("./cloud-functions").CloudFunction<remoteConfig.TemplateVersion>;
|
||||
};
|
||||
get storage(): {
|
||||
/**
|
||||
* The optional bucket function allows you to choose which buckets' events
|
||||
* to handle. This step can be bypassed by calling object() directly,
|
||||
* which will use the default Cloud Storage for Firebase bucket.
|
||||
* @param bucket Name of the Google Cloud Storage bucket to listen to.
|
||||
*/
|
||||
bucket: (bucket?: string) => storage.BucketBuilder;
|
||||
/**
|
||||
* Handle events related to Cloud Storage objects.
|
||||
*/
|
||||
object: () => storage.ObjectBuilder;
|
||||
};
|
||||
get pubsub(): {
|
||||
/**
|
||||
* Select Cloud Pub/Sub topic to listen to.
|
||||
* @param topic Name of Pub/Sub topic, must belong to the same project as
|
||||
* the function.
|
||||
*/
|
||||
topic: (topic: string) => pubsub.TopicBuilder;
|
||||
schedule: (schedule: string) => pubsub.ScheduleBuilder;
|
||||
};
|
||||
get auth(): {
|
||||
/**
|
||||
* Handle events related to Firebase authentication users.
|
||||
*/
|
||||
user: (userOptions?: auth.UserOptions) => auth.UserBuilder;
|
||||
};
|
||||
get testLab(): {
|
||||
/**
|
||||
* Handle events related to Test Lab test matrices.
|
||||
*/
|
||||
testMatrix: () => testLab.TestMatrixBuilder;
|
||||
};
|
||||
}
|
||||
383
node_modules/firebase-functions/lib/v1/function-builder.js
generated
vendored
Normal file
383
node_modules/firebase-functions/lib/v1/function-builder.js
generated
vendored
Normal file
@@ -0,0 +1,383 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FunctionBuilder = exports.runWith = exports.region = void 0;
|
||||
const options_1 = require("../common/options");
|
||||
const types_1 = require("../params/types");
|
||||
const function_configuration_1 = require("./function-configuration");
|
||||
const analytics = require("./providers/analytics");
|
||||
const auth = require("./providers/auth");
|
||||
const database = require("./providers/database");
|
||||
const firestore = require("./providers/firestore");
|
||||
const https = require("./providers/https");
|
||||
const pubsub = require("./providers/pubsub");
|
||||
const remoteConfig = require("./providers/remoteConfig");
|
||||
const storage = require("./providers/storage");
|
||||
const tasks = require("./providers/tasks");
|
||||
const testLab = require("./providers/testLab");
|
||||
/**
|
||||
* Assert that the runtime options passed in are valid.
|
||||
* @param runtimeOptions object containing memory and timeout information.
|
||||
* @throws { Error } Memory and TimeoutSeconds values must be valid.
|
||||
*/
|
||||
function assertRuntimeOptionsValid(runtimeOptions) {
|
||||
const mem = runtimeOptions.memory;
|
||||
if (mem && typeof mem !== "object" && !function_configuration_1.VALID_MEMORY_OPTIONS.includes(mem)) {
|
||||
throw new Error(`The only valid memory allocation values are: ${function_configuration_1.VALID_MEMORY_OPTIONS.join(", ")}`);
|
||||
}
|
||||
if (typeof runtimeOptions.timeoutSeconds === "number" &&
|
||||
(runtimeOptions.timeoutSeconds > function_configuration_1.MAX_TIMEOUT_SECONDS || runtimeOptions.timeoutSeconds < 0)) {
|
||||
throw new Error(`TimeoutSeconds must be between 0 and ${function_configuration_1.MAX_TIMEOUT_SECONDS}`);
|
||||
}
|
||||
if (runtimeOptions.ingressSettings &&
|
||||
!(runtimeOptions.ingressSettings instanceof options_1.ResetValue) &&
|
||||
!function_configuration_1.INGRESS_SETTINGS_OPTIONS.includes(runtimeOptions.ingressSettings)) {
|
||||
throw new Error(`The only valid ingressSettings values are: ${function_configuration_1.INGRESS_SETTINGS_OPTIONS.join(",")}`);
|
||||
}
|
||||
if (runtimeOptions.vpcConnectorEgressSettings &&
|
||||
!(runtimeOptions.vpcConnectorEgressSettings instanceof options_1.ResetValue) &&
|
||||
!function_configuration_1.VPC_EGRESS_SETTINGS_OPTIONS.includes(runtimeOptions.vpcConnectorEgressSettings)) {
|
||||
throw new Error(`The only valid vpcConnectorEgressSettings values are: ${function_configuration_1.VPC_EGRESS_SETTINGS_OPTIONS.join(",")}`);
|
||||
}
|
||||
validateFailurePolicy(runtimeOptions.failurePolicy);
|
||||
const serviceAccount = runtimeOptions.serviceAccount;
|
||||
if (serviceAccount &&
|
||||
!(serviceAccount === "default" ||
|
||||
serviceAccount instanceof options_1.ResetValue ||
|
||||
serviceAccount instanceof types_1.Expression ||
|
||||
serviceAccount.includes("@"))) {
|
||||
throw new Error(`serviceAccount must be set to 'default', a string expression, a service account email, or '{serviceAccountName}@'`);
|
||||
}
|
||||
if (runtimeOptions.labels) {
|
||||
// Labels must follow the rules listed in
|
||||
// https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements
|
||||
if (Object.keys(runtimeOptions.labels).length > function_configuration_1.MAX_NUMBER_USER_LABELS) {
|
||||
throw new Error(`A function must not have more than ${function_configuration_1.MAX_NUMBER_USER_LABELS} user-defined labels.`);
|
||||
}
|
||||
// We reserve the 'deployment' and 'firebase' namespaces for future feature development.
|
||||
const reservedKeys = Object.keys(runtimeOptions.labels).filter((key) => key.startsWith("deployment") || key.startsWith("firebase"));
|
||||
if (reservedKeys.length) {
|
||||
throw new Error(`Invalid labels: ${reservedKeys.join(", ")}. Labels may not start with reserved names 'deployment' or 'firebase'`);
|
||||
}
|
||||
const invalidLengthKeys = Object.keys(runtimeOptions.labels).filter((key) => key.length < 1 || key.length > 63);
|
||||
if (invalidLengthKeys.length > 0) {
|
||||
throw new Error(`Invalid labels: ${invalidLengthKeys.join(", ")}. Label keys must be between 1 and 63 characters in length.`);
|
||||
}
|
||||
const invalidLengthValues = Object.values(runtimeOptions.labels).filter((value) => value.length > 63);
|
||||
if (invalidLengthValues.length > 0) {
|
||||
throw new Error(`Invalid labels: ${invalidLengthValues.join(", ")}. Label values must be less than 64 charcters.`);
|
||||
}
|
||||
// Keys can contain lowercase letters, foreign characters, numbers, _ or -. They must start with a letter.
|
||||
const validKeyPattern = /^[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}$/u;
|
||||
const invalidKeys = Object.keys(runtimeOptions.labels).filter((key) => !validKeyPattern.test(key));
|
||||
if (invalidKeys.length > 0) {
|
||||
throw new Error(`Invalid labels: ${invalidKeys.join(", ")}. Label keys can only contain lowercase letters, international characters, numbers, _ or -, and must start with a letter.`);
|
||||
}
|
||||
// Values can contain lowercase letters, foreign characters, numbers, _ or -.
|
||||
const validValuePattern = /^[\p{Ll}\p{Lo}\p{N}_-]{0,63}$/u;
|
||||
const invalidValues = Object.values(runtimeOptions.labels).filter((value) => !validValuePattern.test(value));
|
||||
if (invalidValues.length > 0) {
|
||||
throw new Error(`Invalid labels: ${invalidValues.join(", ")}. Label values can only contain lowercase letters, international characters, numbers, _ or -.`);
|
||||
}
|
||||
}
|
||||
if (typeof runtimeOptions.invoker === "string" && runtimeOptions.invoker.length === 0) {
|
||||
throw new Error("Invalid service account for function invoker, must be a non-empty string");
|
||||
}
|
||||
if (runtimeOptions.invoker !== undefined && Array.isArray(runtimeOptions.invoker)) {
|
||||
if (runtimeOptions.invoker.length === 0) {
|
||||
throw new Error("Invalid invoker array, must contain at least 1 service account entry");
|
||||
}
|
||||
for (const serviceAccount of runtimeOptions.invoker) {
|
||||
if (serviceAccount.length === 0) {
|
||||
throw new Error("Invalid invoker array, a service account must be a non-empty string");
|
||||
}
|
||||
if (serviceAccount === "public") {
|
||||
throw new Error("Invalid invoker array, a service account cannot be set to the 'public' identifier");
|
||||
}
|
||||
if (serviceAccount === "private") {
|
||||
throw new Error("Invalid invoker array, a service account cannot be set to the 'private' identifier");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (runtimeOptions.secrets !== undefined) {
|
||||
const invalidSecrets = runtimeOptions.secrets.filter((s) => !/^[A-Za-z\d\-_]+$/.test(s instanceof types_1.SecretParam ? s.name : s));
|
||||
if (invalidSecrets.length > 0) {
|
||||
throw new Error(`Invalid secrets: ${invalidSecrets.join(",")}. ` +
|
||||
"Secret must be configured using the resource id (e.g. API_KEY)");
|
||||
}
|
||||
}
|
||||
if ("allowInvalidAppCheckToken" in runtimeOptions) {
|
||||
throw new Error('runWith option "allowInvalidAppCheckToken" has been inverted and ' +
|
||||
'renamed "enforceAppCheck"');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function validateFailurePolicy(policy) {
|
||||
if (typeof policy === "boolean" || typeof policy === "undefined") {
|
||||
return;
|
||||
}
|
||||
if (typeof policy !== "object") {
|
||||
throw new Error(`failurePolicy must be a boolean or an object.`);
|
||||
}
|
||||
const retry = policy.retry;
|
||||
if (typeof retry !== "object" || Object.keys(retry).length) {
|
||||
throw new Error("failurePolicy.retry must be an empty object.");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Assert regions specified are valid.
|
||||
* @param regions list of regions.
|
||||
* @throws { Error } Regions must be in list of supported regions.
|
||||
*/
|
||||
function assertRegionsAreValid(regions) {
|
||||
if (!regions.length) {
|
||||
throw new Error("You must specify at least one region");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Configure the regions that the function is deployed to.
|
||||
* @param regions One of more region strings.
|
||||
* @example
|
||||
* functions.region('us-east1')
|
||||
* @example
|
||||
* functions.region('us-east1', 'us-central1')
|
||||
*/
|
||||
function region(...regions) {
|
||||
if (assertRegionsAreValid(regions)) {
|
||||
return new FunctionBuilder({ regions });
|
||||
}
|
||||
}
|
||||
exports.region = region;
|
||||
/**
|
||||
* Configure runtime options for the function.
|
||||
* @param runtimeOptions Object with optional fields:
|
||||
* 1. `memory`: amount of memory to allocate to the function, possible values
|
||||
* are: '128MB', '256MB', '512MB', '1GB', '2GB', '4GB', and '8GB'.
|
||||
* 2. `timeoutSeconds`: timeout for the function in seconds, possible values are
|
||||
* 0 to 540.
|
||||
* 3. `failurePolicy`: failure policy of the function, with boolean `true` being
|
||||
* equivalent to providing an empty retry object.
|
||||
* 4. `vpcConnector`: id of a VPC connector in same project and region.
|
||||
* 5. `vpcConnectorEgressSettings`: when a vpcConnector is set, control which
|
||||
* egress traffic is sent through the vpcConnector.
|
||||
* 6. `serviceAccount`: Specific service account for the function.
|
||||
* 7. `ingressSettings`: ingress settings for the function, which control where a HTTPS
|
||||
* function can be called from.
|
||||
*
|
||||
* Value must not be null.
|
||||
*/
|
||||
function runWith(runtimeOptions) {
|
||||
if (assertRuntimeOptionsValid(runtimeOptions)) {
|
||||
return new FunctionBuilder(runtimeOptions);
|
||||
}
|
||||
}
|
||||
exports.runWith = runWith;
|
||||
class FunctionBuilder {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Configure the regions that the function is deployed to.
|
||||
* @param regions One or more region strings.
|
||||
* @example
|
||||
* functions.region('us-east1')
|
||||
* @example
|
||||
* functions.region('us-east1', 'us-central1')
|
||||
*/
|
||||
region(...regions) {
|
||||
if (assertRegionsAreValid(regions)) {
|
||||
this.options.regions = regions;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Configure runtime options for the function.
|
||||
* @param runtimeOptions Object with optional fields:
|
||||
* 1. `memory`: amount of memory to allocate to the function, possible values
|
||||
* are: '128MB', '256MB', '512MB', '1GB', '2GB', '4GB', and '8GB'.
|
||||
* 2. `timeoutSeconds`: timeout for the function in seconds, possible values are
|
||||
* 0 to 540.
|
||||
* 3. `failurePolicy`: failure policy of the function, with boolean `true` being
|
||||
* equivalent to providing an empty retry object.
|
||||
* 4. `vpcConnector`: id of a VPC connector in the same project and region
|
||||
* 5. `vpcConnectorEgressSettings`: when a `vpcConnector` is set, control which
|
||||
* egress traffic is sent through the `vpcConnector`.
|
||||
*
|
||||
* Value must not be null.
|
||||
*/
|
||||
runWith(runtimeOptions) {
|
||||
if (assertRuntimeOptionsValid(runtimeOptions)) {
|
||||
this.options = {
|
||||
...this.options,
|
||||
...runtimeOptions,
|
||||
};
|
||||
return this;
|
||||
}
|
||||
}
|
||||
get https() {
|
||||
if (this.options.failurePolicy !== undefined) {
|
||||
console.warn("RuntimeOptions.failurePolicy is not supported in https functions.");
|
||||
}
|
||||
return {
|
||||
/**
|
||||
* Handle HTTP requests.
|
||||
* @param handler A function that takes a request and response object,
|
||||
* same signature as an Express app.
|
||||
*/
|
||||
onRequest: (handler) => https._onRequestWithOptions(handler, this.options),
|
||||
/**
|
||||
* Declares a callable method for clients to call using a Firebase SDK.
|
||||
* @param handler A method that takes a data and context and returns a value.
|
||||
*/
|
||||
onCall: (handler) => https._onCallWithOptions(handler, this.options),
|
||||
};
|
||||
}
|
||||
get tasks() {
|
||||
return {
|
||||
/**
|
||||
* Declares a task queue function for clients to call using a Firebase Admin SDK.
|
||||
* @param options Configurations for the task queue function.
|
||||
*/
|
||||
/** @hidden */
|
||||
taskQueue: (options) => {
|
||||
return new tasks.TaskQueueBuilder(options, this.options);
|
||||
},
|
||||
};
|
||||
}
|
||||
get database() {
|
||||
return {
|
||||
/**
|
||||
* Selects a database instance that will trigger the function. If omitted,
|
||||
* will pick the default database for your project.
|
||||
* @param instance The Realtime Database instance to use.
|
||||
*/
|
||||
instance: (instance) => database._instanceWithOptions(instance, this.options),
|
||||
/**
|
||||
* Select Firebase Realtime Database Reference to listen to.
|
||||
*
|
||||
* This method behaves very similarly to the method of the same name in
|
||||
* the client and Admin Firebase SDKs. Any change to the Database that
|
||||
* affects the data at or below the provided `path` will fire an event in
|
||||
* Cloud Functions.
|
||||
*
|
||||
* There are three important differences between listening to a Realtime
|
||||
* Database event in Cloud Functions and using the Realtime Database in
|
||||
* the client and Admin SDKs:
|
||||
* 1. Cloud Functions allows wildcards in the `path` name. Any `path`
|
||||
* component in curly brackets (`{}`) is a wildcard that matches all
|
||||
* strings. The value that matched a certain invocation of a Cloud
|
||||
* Function is returned as part of the `context.params` object. For
|
||||
* example, `ref("messages/{messageId}")` matches changes at
|
||||
* `/messages/message1` or `/messages/message2`, resulting in
|
||||
* `context.params.messageId` being set to `"message1"` or
|
||||
* `"message2"`, respectively.
|
||||
* 2. Cloud Functions do not fire an event for data that already existed
|
||||
* before the Cloud Function was deployed.
|
||||
* 3. Cloud Function events have access to more information, including
|
||||
* information about the user who triggered the Cloud Function.
|
||||
* @param ref Path of the database to listen to.
|
||||
*/
|
||||
ref: (path) => database._refWithOptions(path, this.options),
|
||||
};
|
||||
}
|
||||
get firestore() {
|
||||
return {
|
||||
/**
|
||||
* Select the Firestore document to listen to for events.
|
||||
* @param path Full database path to listen to. This includes the name of
|
||||
* the collection that the document is a part of. For example, if the
|
||||
* collection is named "users" and the document is named "Ada", then the
|
||||
* path is "/users/Ada".
|
||||
*/
|
||||
document: (path) => firestore._documentWithOptions(path, this.options),
|
||||
/** @hidden */
|
||||
namespace: (namespace) => firestore._namespaceWithOptions(namespace, this.options),
|
||||
/** @hidden */
|
||||
database: (database) => firestore._databaseWithOptions(database, this.options),
|
||||
};
|
||||
}
|
||||
get analytics() {
|
||||
return {
|
||||
/**
|
||||
* Select analytics events to listen to for events.
|
||||
* @param analyticsEventType Name of the analytics event type.
|
||||
*/
|
||||
event: (analyticsEventType) => analytics._eventWithOptions(analyticsEventType, this.options),
|
||||
};
|
||||
}
|
||||
get remoteConfig() {
|
||||
return {
|
||||
/**
|
||||
* Handle all updates (including rollbacks) that affect a Remote Config
|
||||
* project.
|
||||
* @param handler A function that takes the updated Remote Config template
|
||||
* version metadata as an argument.
|
||||
*/
|
||||
onUpdate: (handler) => remoteConfig._onUpdateWithOptions(handler, this.options),
|
||||
};
|
||||
}
|
||||
get storage() {
|
||||
return {
|
||||
/**
|
||||
* The optional bucket function allows you to choose which buckets' events
|
||||
* to handle. This step can be bypassed by calling object() directly,
|
||||
* which will use the default Cloud Storage for Firebase bucket.
|
||||
* @param bucket Name of the Google Cloud Storage bucket to listen to.
|
||||
*/
|
||||
bucket: (bucket) => storage._bucketWithOptions(this.options, bucket),
|
||||
/**
|
||||
* Handle events related to Cloud Storage objects.
|
||||
*/
|
||||
object: () => storage._objectWithOptions(this.options),
|
||||
};
|
||||
}
|
||||
get pubsub() {
|
||||
return {
|
||||
/**
|
||||
* Select Cloud Pub/Sub topic to listen to.
|
||||
* @param topic Name of Pub/Sub topic, must belong to the same project as
|
||||
* the function.
|
||||
*/
|
||||
topic: (topic) => pubsub._topicWithOptions(topic, this.options),
|
||||
schedule: (schedule) => pubsub._scheduleWithOptions(schedule, this.options),
|
||||
};
|
||||
}
|
||||
get auth() {
|
||||
return {
|
||||
/**
|
||||
* Handle events related to Firebase authentication users.
|
||||
*/
|
||||
user: (userOptions) => auth._userWithOptions(this.options, userOptions),
|
||||
};
|
||||
}
|
||||
get testLab() {
|
||||
return {
|
||||
/**
|
||||
* Handle events related to Test Lab test matrices.
|
||||
*/
|
||||
testMatrix: () => testLab._testMatrixWithOpts(this.options),
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.FunctionBuilder = FunctionBuilder;
|
||||
226
node_modules/firebase-functions/lib/v1/function-configuration.d.ts
generated
vendored
Normal file
226
node_modules/firebase-functions/lib/v1/function-configuration.d.ts
generated
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
import { Expression } from "../params";
|
||||
import { ResetValue } from "../common/options";
|
||||
import { SecretParam } from "../params/types";
|
||||
export { RESET_VALUE } from "../common/options";
|
||||
/**
|
||||
* List of all regions supported by Cloud Functions.
|
||||
*/
|
||||
export declare const SUPPORTED_REGIONS: readonly ["us-central1", "us-east1", "us-east4", "us-west2", "us-west3", "us-west4", "europe-central2", "europe-west1", "europe-west2", "europe-west3", "europe-west6", "asia-east1", "asia-east2", "asia-northeast1", "asia-northeast2", "asia-northeast3", "asia-south1", "asia-southeast1", "asia-southeast2", "northamerica-northeast1", "southamerica-east1", "australia-southeast1"];
|
||||
/**
|
||||
* Cloud Functions min timeout value.
|
||||
*/
|
||||
export declare const MIN_TIMEOUT_SECONDS = 0;
|
||||
/**
|
||||
* Cloud Functions max timeout value.
|
||||
*/
|
||||
export declare const MAX_TIMEOUT_SECONDS = 540;
|
||||
/**
|
||||
* List of available memory options supported by Cloud Functions.
|
||||
*/
|
||||
export declare const VALID_MEMORY_OPTIONS: readonly ["128MB", "256MB", "512MB", "1GB", "2GB", "4GB", "8GB"];
|
||||
/**
|
||||
* List of available options for VpcConnectorEgressSettings.
|
||||
*/
|
||||
export declare const VPC_EGRESS_SETTINGS_OPTIONS: readonly ["VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED", "PRIVATE_RANGES_ONLY", "ALL_TRAFFIC"];
|
||||
/**
|
||||
* List of available options for IngressSettings.
|
||||
*/
|
||||
export declare const INGRESS_SETTINGS_OPTIONS: readonly ["INGRESS_SETTINGS_UNSPECIFIED", "ALLOW_ALL", "ALLOW_INTERNAL_ONLY", "ALLOW_INTERNAL_AND_GCLB"];
|
||||
/**
|
||||
* Scheduler retry options. Applies only to scheduled functions.
|
||||
*/
|
||||
export interface ScheduleRetryConfig {
|
||||
/**
|
||||
* The number of attempts that the system will make to run a job using the exponential backoff procedure described by {@link ScheduleRetryConfig.maxDoublings}.
|
||||
*
|
||||
* @defaultValue 0 (infinite retry)
|
||||
*/
|
||||
retryCount?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* The time limit for retrying a failed job, measured from time when an execution was first attempted.
|
||||
*
|
||||
* If specified with {@link ScheduleRetryConfig.retryCount}, the job will be retried until both limits are reached.
|
||||
*
|
||||
* @defaultValue 0
|
||||
*/
|
||||
maxRetryDuration?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* The minimum amount of time to wait before retrying a job after it fails.
|
||||
*
|
||||
* @defaultValue 5 seconds
|
||||
*/
|
||||
minBackoffDuration?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* The maximum amount of time to wait before retrying a job after it fails.
|
||||
*
|
||||
* @defaultValue 1 hour
|
||||
*/
|
||||
maxBackoffDuration?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* The max number of backoff doubling applied at each retry.
|
||||
*
|
||||
* @defaultValue 5
|
||||
*/
|
||||
maxDoublings?: number | Expression<number> | ResetValue;
|
||||
}
|
||||
/**
|
||||
* Configuration options for scheduled functions.
|
||||
*/
|
||||
export interface Schedule {
|
||||
/**
|
||||
* Describes the schedule on which the job will be executed.
|
||||
*
|
||||
* The schedule can be either of the following types:
|
||||
*
|
||||
* 1. {@link https://en.wikipedia.org/wiki/Cron#Overview | Crontab}
|
||||
*
|
||||
* 2. English-like {@link https://cloud.google.com/scheduler/docs/configuring/cron-job-schedules | schedule}
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* // Crontab schedule
|
||||
* schedule: "0 9 * * 1"` // Every Monday at 09:00 AM
|
||||
*
|
||||
* // English-like schedule
|
||||
* schedule: "every 5 minutes"
|
||||
* ```
|
||||
*/
|
||||
schedule: string;
|
||||
/**
|
||||
* Specifies the time zone to be used in interpreting {@link Schedule.schedule}.
|
||||
*
|
||||
* The value of this field must be a time zone name from the tz database.
|
||||
*/
|
||||
timeZone?: string | ResetValue;
|
||||
/**
|
||||
* Settings that determine the retry behavior.
|
||||
*/
|
||||
retryConfig?: ScheduleRetryConfig;
|
||||
}
|
||||
/**
|
||||
* Configuration option for failure policy on background functions.
|
||||
*/
|
||||
export interface FailurePolicy {
|
||||
/**
|
||||
* Retry configuration. Must be an empty object.
|
||||
*
|
||||
*/
|
||||
retry: Record<string, never>;
|
||||
}
|
||||
export declare const DEFAULT_FAILURE_POLICY: FailurePolicy;
|
||||
export declare const MAX_NUMBER_USER_LABELS = 58;
|
||||
/**
|
||||
* Configuration options for a function that applicable at runtime.
|
||||
*/
|
||||
export interface RuntimeOptions {
|
||||
/**
|
||||
* Failure policy of the function, with boolean `true` being equivalent to
|
||||
* providing an empty retry object.
|
||||
*/
|
||||
failurePolicy?: FailurePolicy | boolean;
|
||||
/**
|
||||
* Amount of memory to allocate to the function.
|
||||
*/
|
||||
memory?: (typeof VALID_MEMORY_OPTIONS)[number] | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Timeout for the function in seconds, possible values are 0 to 540.
|
||||
*/
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Min number of actual instances to be running at a given time.
|
||||
*
|
||||
* @remarks
|
||||
* Instances will be billed for memory allocation and 10% of CPU allocation
|
||||
* while idle.
|
||||
*/
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Max number of actual instances allowed to be running in parallel.
|
||||
*/
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Connect cloud function to specified VPC connector.
|
||||
*/
|
||||
vpcConnector?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Egress settings for VPC connector.
|
||||
*/
|
||||
vpcConnectorEgressSettings?: (typeof VPC_EGRESS_SETTINGS_OPTIONS)[number] | ResetValue;
|
||||
/**
|
||||
* Specific service account for the function to run as.
|
||||
*/
|
||||
serviceAccount?: "default" | string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Ingress settings which control where this function can be called from.
|
||||
*/
|
||||
ingressSettings?: (typeof INGRESS_SETTINGS_OPTIONS)[number] | ResetValue;
|
||||
/**
|
||||
* User labels to set on the function.
|
||||
*/
|
||||
labels?: Record<string, string>;
|
||||
/**
|
||||
* Invoker to set access control on https functions.
|
||||
*/
|
||||
invoker?: "public" | "private" | string | string[];
|
||||
secrets?: (string | SecretParam)[];
|
||||
/**
|
||||
* Determines whether Firebase AppCheck is enforced.
|
||||
*
|
||||
* @remarks
|
||||
* When true, requests with invalid tokens autorespond with a 401
|
||||
* (Unauthorized) error.
|
||||
* When false, requests with invalid tokens set context.app to undefiend.
|
||||
*/
|
||||
enforceAppCheck?: boolean;
|
||||
/**
|
||||
* Determines whether Firebase App Check token is consumed on request. Defaults to false.
|
||||
*
|
||||
* @remarks
|
||||
* Set this to true to enable the App Check replay protection feature by consuming the App Check token on callable
|
||||
* request. Tokens that are found to be already consumed will have the `request.app.alreadyConsumed` property set
|
||||
* to true.
|
||||
*
|
||||
*
|
||||
* Tokens are only considered to be consumed if it is sent to the App Check service by setting this option to true.
|
||||
* Other uses of the token do not consume it.
|
||||
*
|
||||
* This replay protection feature requires an additional network call to the App Check backend and forces the clients
|
||||
* to obtain a fresh attestation from the chosen attestation providers. This can therefore negatively impact
|
||||
* performance and can potentially deplete your attestation providers' quotas faster. Use this feature only for
|
||||
* protecting low volume, security critical, or expensive operations.
|
||||
*
|
||||
* This option does not affect the `enforceAppCheck` option. Setting the latter to true will cause the callable function
|
||||
* to automatically respond with a 401 Unauthorized status code when the request includes an invalid App Check token.
|
||||
* When the request includes valid but consumed App Check tokens, requests will not be automatically rejected. Instead,
|
||||
* the `request.app.alreadyConsumed` property will be set to true and pass the execution to the handler code for making
|
||||
* further decisions, such as requiring additional security checks or rejecting the request.
|
||||
*/
|
||||
consumeAppCheckToken?: boolean;
|
||||
/**
|
||||
* Controls whether function configuration modified outside of function source is preserved. Defaults to false.
|
||||
*
|
||||
* @remarks
|
||||
* When setting configuration available in the underlying platform that is not yet available in the Firebase Functions
|
||||
* SDK, we highly recommend setting `preserveExternalChanges` to `true`. Otherwise, when the Firebase Functions SDK releases
|
||||
* a new version of the SDK with support for the missing configuration, your function's manually configured setting
|
||||
* may inadvertently be wiped out.
|
||||
*/
|
||||
preserveExternalChanges?: boolean;
|
||||
}
|
||||
/**
|
||||
* Configuration options for a function that applies during function deployment.
|
||||
*/
|
||||
export interface DeploymentOptions extends RuntimeOptions {
|
||||
/**
|
||||
* If true, do not deploy or emulate this function.
|
||||
*/
|
||||
omit?: boolean | Expression<boolean>;
|
||||
/**
|
||||
* Regions where function should be deployed.
|
||||
*/
|
||||
regions?: Array<(typeof SUPPORTED_REGIONS)[number] | string | Expression<string> | ResetValue>;
|
||||
/**
|
||||
* Schedule for the scheduled function.
|
||||
*/
|
||||
schedule?: Schedule;
|
||||
}
|
||||
73
node_modules/firebase-functions/lib/v1/function-configuration.js
generated
vendored
Normal file
73
node_modules/firebase-functions/lib/v1/function-configuration.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MAX_NUMBER_USER_LABELS = exports.DEFAULT_FAILURE_POLICY = exports.INGRESS_SETTINGS_OPTIONS = exports.VPC_EGRESS_SETTINGS_OPTIONS = exports.VALID_MEMORY_OPTIONS = exports.MAX_TIMEOUT_SECONDS = exports.MIN_TIMEOUT_SECONDS = exports.SUPPORTED_REGIONS = exports.RESET_VALUE = void 0;
|
||||
var options_1 = require("../common/options");
|
||||
Object.defineProperty(exports, "RESET_VALUE", { enumerable: true, get: function () { return options_1.RESET_VALUE; } });
|
||||
/**
|
||||
* List of all regions supported by Cloud Functions.
|
||||
*/
|
||||
exports.SUPPORTED_REGIONS = [
|
||||
"us-central1",
|
||||
"us-east1",
|
||||
"us-east4",
|
||||
"us-west2",
|
||||
"us-west3",
|
||||
"us-west4",
|
||||
"europe-central2",
|
||||
"europe-west1",
|
||||
"europe-west2",
|
||||
"europe-west3",
|
||||
"europe-west6",
|
||||
"asia-east1",
|
||||
"asia-east2",
|
||||
"asia-northeast1",
|
||||
"asia-northeast2",
|
||||
"asia-northeast3",
|
||||
"asia-south1",
|
||||
"asia-southeast1",
|
||||
"asia-southeast2",
|
||||
"northamerica-northeast1",
|
||||
"southamerica-east1",
|
||||
"australia-southeast1",
|
||||
];
|
||||
/**
|
||||
* Cloud Functions min timeout value.
|
||||
*/
|
||||
exports.MIN_TIMEOUT_SECONDS = 0;
|
||||
/**
|
||||
* Cloud Functions max timeout value.
|
||||
*/
|
||||
exports.MAX_TIMEOUT_SECONDS = 540;
|
||||
/**
|
||||
* List of available memory options supported by Cloud Functions.
|
||||
*/
|
||||
exports.VALID_MEMORY_OPTIONS = [
|
||||
"128MB",
|
||||
"256MB",
|
||||
"512MB",
|
||||
"1GB",
|
||||
"2GB",
|
||||
"4GB",
|
||||
"8GB",
|
||||
];
|
||||
/**
|
||||
* List of available options for VpcConnectorEgressSettings.
|
||||
*/
|
||||
exports.VPC_EGRESS_SETTINGS_OPTIONS = [
|
||||
"VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED",
|
||||
"PRIVATE_RANGES_ONLY",
|
||||
"ALL_TRAFFIC",
|
||||
];
|
||||
/**
|
||||
* List of available options for IngressSettings.
|
||||
*/
|
||||
exports.INGRESS_SETTINGS_OPTIONS = [
|
||||
"INGRESS_SETTINGS_UNSPECIFIED",
|
||||
"ALLOW_ALL",
|
||||
"ALLOW_INTERNAL_ONLY",
|
||||
"ALLOW_INTERNAL_AND_GCLB",
|
||||
];
|
||||
exports.DEFAULT_FAILURE_POLICY = {
|
||||
retry: {},
|
||||
};
|
||||
exports.MAX_NUMBER_USER_LABELS = 58;
|
||||
23
node_modules/firebase-functions/lib/v1/index.d.ts
generated
vendored
Normal file
23
node_modules/firebase-functions/lib/v1/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as logger from "../logger";
|
||||
import * as analytics from "./providers/analytics";
|
||||
import * as auth from "./providers/auth";
|
||||
import * as database from "./providers/database";
|
||||
import * as firestore from "./providers/firestore";
|
||||
import * as https from "./providers/https";
|
||||
import * as pubsub from "./providers/pubsub";
|
||||
import * as remoteConfig from "./providers/remoteConfig";
|
||||
import * as storage from "./providers/storage";
|
||||
import * as tasks from "./providers/tasks";
|
||||
import * as testLab from "./providers/testLab";
|
||||
import { setApp as setEmulatedAdminApp } from "../common/app";
|
||||
export { analytics, auth, database, firestore, https, pubsub, remoteConfig, storage, tasks, testLab, logger, };
|
||||
export declare const app: {
|
||||
setEmulatedAdminApp: typeof setEmulatedAdminApp;
|
||||
};
|
||||
export * from "./cloud-functions";
|
||||
export * from "./config";
|
||||
export * from "./function-builder";
|
||||
export * from "./function-configuration";
|
||||
import * as params from "../params";
|
||||
export { params };
|
||||
export { onInit } from "../common/onInit";
|
||||
73
node_modules/firebase-functions/lib/v1/index.js
generated
vendored
Normal file
73
node_modules/firebase-functions/lib/v1/index.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.onInit = exports.params = exports.app = exports.logger = exports.testLab = exports.tasks = exports.storage = exports.remoteConfig = exports.pubsub = exports.https = exports.firestore = exports.database = exports.auth = exports.analytics = void 0;
|
||||
// Providers:
|
||||
const logger = require("../logger");
|
||||
exports.logger = logger;
|
||||
const analytics = require("./providers/analytics");
|
||||
exports.analytics = analytics;
|
||||
const auth = require("./providers/auth");
|
||||
exports.auth = auth;
|
||||
const database = require("./providers/database");
|
||||
exports.database = database;
|
||||
const firestore = require("./providers/firestore");
|
||||
exports.firestore = firestore;
|
||||
const https = require("./providers/https");
|
||||
exports.https = https;
|
||||
const pubsub = require("./providers/pubsub");
|
||||
exports.pubsub = pubsub;
|
||||
const remoteConfig = require("./providers/remoteConfig");
|
||||
exports.remoteConfig = remoteConfig;
|
||||
const storage = require("./providers/storage");
|
||||
exports.storage = storage;
|
||||
const tasks = require("./providers/tasks");
|
||||
exports.tasks = tasks;
|
||||
const testLab = require("./providers/testLab");
|
||||
exports.testLab = testLab;
|
||||
const app_1 = require("../common/app");
|
||||
exports.app = { setEmulatedAdminApp: app_1.setApp };
|
||||
// Exported root types:
|
||||
__exportStar(require("./cloud-functions"), exports);
|
||||
__exportStar(require("./config"), exports);
|
||||
__exportStar(require("./function-builder"), exports);
|
||||
__exportStar(require("./function-configuration"), exports);
|
||||
// NOTE: Equivalent to `export * as params from "../params"` but api-extractor doesn't support that syntax.
|
||||
const params = require("../params");
|
||||
exports.params = params;
|
||||
var onInit_1 = require("../common/onInit");
|
||||
Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return onInit_1.onInit; } });
|
||||
241
node_modules/firebase-functions/lib/v1/providers/analytics.d.ts
generated
vendored
Normal file
241
node_modules/firebase-functions/lib/v1/providers/analytics.d.ts
generated
vendored
Normal file
@@ -0,0 +1,241 @@
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
import { DeploymentOptions } from "../function-configuration";
|
||||
/**
|
||||
* Registers a function to handle analytics events.
|
||||
*
|
||||
* @param analyticsEventType Name of the analytics event type to which
|
||||
* this Cloud Function is scoped.
|
||||
*
|
||||
* @returns Analytics event builder interface.
|
||||
*/
|
||||
export declare function event(analyticsEventType: string): AnalyticsEventBuilder;
|
||||
/**
|
||||
* The Firebase Analytics event builder interface.
|
||||
*
|
||||
* Access via `functions.analytics.event()`.
|
||||
*/
|
||||
export declare class AnalyticsEventBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/** @hidden */
|
||||
constructor(triggerResource: () => string, options: DeploymentOptions);
|
||||
/**
|
||||
* Event handler that fires every time a Firebase Analytics event occurs.
|
||||
*
|
||||
* @param handler Event handler that fires every time a Firebase Analytics event
|
||||
* occurs.
|
||||
*
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onLog(handler: (event: AnalyticsEvent, context: EventContext) => PromiseLike<any> | any): CloudFunction<AnalyticsEvent>;
|
||||
}
|
||||
/** Interface representing a Firebase Analytics event that was logged for a specific user. */
|
||||
export declare class AnalyticsEvent {
|
||||
/**
|
||||
* The date on which the event.was logged.
|
||||
* (`YYYYMMDD` format in the registered timezone of your app).
|
||||
*/
|
||||
reportingDate: string;
|
||||
/** The name of the event. */
|
||||
name: string;
|
||||
/**
|
||||
* A map of parameters and their values associated with the event.
|
||||
*
|
||||
* Note: Values in this map are cast to the most appropriate type. Due to
|
||||
* the nature of JavaScript's number handling, this might entail a loss of
|
||||
* precision in cases of very large integers.
|
||||
*/
|
||||
params: {
|
||||
[key: string]: any;
|
||||
};
|
||||
/** UTC client time when the event happened. */
|
||||
logTime: string;
|
||||
/** UTC client time when the previous event happened. */
|
||||
previousLogTime?: string;
|
||||
/** Value parameter in USD. */
|
||||
valueInUSD?: number;
|
||||
/** User-related dimensions. */
|
||||
user?: UserDimensions;
|
||||
/** @hidden */
|
||||
constructor(wireFormat: any);
|
||||
}
|
||||
/**
|
||||
* Interface representing the user who triggered the events.
|
||||
*/
|
||||
export declare class UserDimensions {
|
||||
/**
|
||||
* The user ID set via the `setUserId` API.
|
||||
* [Android](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#setUserId(java.lang.String))
|
||||
* [iOS](https://firebase.google.com/docs/reference/ios/firebaseanalytics/api/reference/Classes/FIRAnalytics#/c:objc(cs)FIRAnalytics(cm)setUserID)
|
||||
*/
|
||||
userId?: string;
|
||||
/** The time (in UTC) at which the user first opened the app. */
|
||||
firstOpenTime?: string;
|
||||
/**
|
||||
* A map of user properties set with the
|
||||
* [`setUserProperty`](https://firebase.google.com/docs/analytics/android/properties) API.
|
||||
*
|
||||
* All values are [`UserPropertyValue`](providers_analytics_.userpropertyvalue) objects.
|
||||
*/
|
||||
userProperties: {
|
||||
[key: string]: UserPropertyValue;
|
||||
};
|
||||
/** Device information. */
|
||||
deviceInfo: DeviceInfo;
|
||||
/** User's geographic information. */
|
||||
geoInfo: GeoInfo;
|
||||
/** App information. */
|
||||
appInfo?: AppInfo;
|
||||
/** Information regarding the bundle in which these events were uploaded. */
|
||||
bundleInfo: ExportBundleInfo;
|
||||
/** @hidden */
|
||||
constructor(wireFormat: any);
|
||||
}
|
||||
/** Predefined or custom properties stored on the client side. */
|
||||
export declare class UserPropertyValue {
|
||||
/** The last set value of a user property. */
|
||||
value: string;
|
||||
/** UTC client time when the user property was last set. */
|
||||
setTime: string;
|
||||
/** @hidden */
|
||||
constructor(wireFormat: any);
|
||||
}
|
||||
/**
|
||||
* Interface representing the device that triggered these
|
||||
* Firebase Analytics events.
|
||||
*/
|
||||
export interface DeviceInfo {
|
||||
/**
|
||||
* Device category.
|
||||
*
|
||||
* Examples: "tablet" or "mobile".
|
||||
*/
|
||||
deviceCategory?: string;
|
||||
/**
|
||||
* Device brand name.
|
||||
*
|
||||
* Examples: "Samsung", "HTC"
|
||||
*/
|
||||
mobileBrandName?: string;
|
||||
/**
|
||||
* Device model name in human-readable format.
|
||||
*
|
||||
* Example: "iPhone 7"
|
||||
*/
|
||||
mobileModelName?: string;
|
||||
/**
|
||||
* Device marketing name.
|
||||
*
|
||||
* Example: "Galaxy S4 Mini"
|
||||
*/
|
||||
mobileMarketingName?: string;
|
||||
/**
|
||||
* Device model, as read from the OS.
|
||||
*
|
||||
* Example: "iPhone9,1"
|
||||
*/
|
||||
deviceModel?: string;
|
||||
/**
|
||||
* Device OS version when data capture ended.
|
||||
*
|
||||
* Example: "4.4.2"
|
||||
*/
|
||||
platformVersion?: string;
|
||||
/**
|
||||
* Vendor specific device identifier. This is IDFV on iOS. Not used for Android.
|
||||
*
|
||||
* Example: '599F9C00-92DC-4B5C-9464-7971F01F8370'
|
||||
*/
|
||||
deviceId?: string;
|
||||
/**
|
||||
* The type of the [`resettable_device_id`](https://support.google.com/dfp_premium/answer/6238701?hl=en)
|
||||
* is IDFA on iOS (when available) and AdId on Android.
|
||||
*
|
||||
* Example: "71683BF9-FA3B-4B0D-9535-A1F05188BAF3"
|
||||
*/
|
||||
resettableDeviceId?: string;
|
||||
/**
|
||||
* The user language in language-country format, where language is an ISO 639
|
||||
* value and country is an ISO 3166 value.
|
||||
*
|
||||
* Examples: "en-us", "en-za", "zh-tw", "jp"
|
||||
*/
|
||||
userDefaultLanguage: string;
|
||||
/**
|
||||
* The time zone of the device when data was uploaded, as seconds skew from UTC.
|
||||
* Use this to calculate the device's local time for
|
||||
* [`EventContext.timestamp`](cloud_functions_eventcontext.html#timestamp).
|
||||
*/
|
||||
deviceTimeZoneOffsetSeconds: number;
|
||||
/**
|
||||
* The device's Limit Ad Tracking setting.
|
||||
* When `true`, you cannot use `resettableDeviceId` for remarketing, demographics or influencing ads serving
|
||||
* behaviour. However, you can use `resettableDeviceId` for conversion tracking and campaign attribution.
|
||||
*/
|
||||
limitedAdTracking: boolean;
|
||||
}
|
||||
/** Interface representing the geographic origin of the events. */
|
||||
export interface GeoInfo {
|
||||
/**
|
||||
* The geographic continent.
|
||||
*
|
||||
* Example: "South America".
|
||||
*/
|
||||
continent?: string;
|
||||
/**
|
||||
* The geographic country.
|
||||
*
|
||||
* Example: "Brazil".
|
||||
*/
|
||||
country?: string;
|
||||
/**
|
||||
* The geographic region.
|
||||
*
|
||||
* Example: "State of Sao Paulo".
|
||||
*/
|
||||
region?: string;
|
||||
/**
|
||||
* The geographic city.
|
||||
*
|
||||
* Example: "Sao Paulo".
|
||||
*/
|
||||
city?: string;
|
||||
}
|
||||
/** Interface representing the application that triggered these events. */
|
||||
export interface AppInfo {
|
||||
/**
|
||||
* The app's version name.
|
||||
*
|
||||
* Examples: "1.0", "4.3.1.1.213361", "2.3 (1824253)", "v1.8b22p6".
|
||||
*/
|
||||
appVersion?: string;
|
||||
/**
|
||||
* Unique ID for this instance of the app.
|
||||
*
|
||||
* Example: "71683BF9FA3B4B0D9535A1F05188BAF3".
|
||||
*/
|
||||
appInstanceId: string;
|
||||
/**
|
||||
* The identifier of the store that installed the app.
|
||||
*
|
||||
* Examples: "com.sec.android.app.samsungapps", "com.amazon.venezia", "com.nokia.nstore".
|
||||
*/
|
||||
appStore?: string;
|
||||
/**
|
||||
* The app platform.
|
||||
*
|
||||
* Examples: "ANDROID", "IOS".
|
||||
*/
|
||||
appPlatform: string;
|
||||
/** Unique application identifier within an app store. */
|
||||
appId?: string;
|
||||
}
|
||||
/** Interface representing the bundle these events were uploaded to. */
|
||||
export declare class ExportBundleInfo {
|
||||
/** Monotonically increasing index for each bundle set by the Analytics SDK. */
|
||||
bundleSequenceId: number;
|
||||
/** Timestamp offset (in milliseconds) between collection time and upload time. */
|
||||
serverTimestampOffset: number;
|
||||
/** @hidden */
|
||||
constructor(wireFormat: any);
|
||||
}
|
||||
247
node_modules/firebase-functions/lib/v1/providers/analytics.js
generated
vendored
Normal file
247
node_modules/firebase-functions/lib/v1/providers/analytics.js
generated
vendored
Normal file
@@ -0,0 +1,247 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the 'Software'), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ExportBundleInfo = exports.UserPropertyValue = exports.UserDimensions = exports.AnalyticsEvent = exports.AnalyticsEventBuilder = exports._eventWithOptions = exports.event = exports.service = exports.provider = void 0;
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.analytics";
|
||||
/** @internal */
|
||||
exports.service = "app-measurement.com";
|
||||
/**
|
||||
* Registers a function to handle analytics events.
|
||||
*
|
||||
* @param analyticsEventType Name of the analytics event type to which
|
||||
* this Cloud Function is scoped.
|
||||
*
|
||||
* @returns Analytics event builder interface.
|
||||
*/
|
||||
function event(analyticsEventType) {
|
||||
return _eventWithOptions(analyticsEventType, {});
|
||||
}
|
||||
exports.event = event;
|
||||
/** @internal */
|
||||
function _eventWithOptions(analyticsEventType, options) {
|
||||
return new AnalyticsEventBuilder(() => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
return "projects/" + process.env.GCLOUD_PROJECT + "/events/" + analyticsEventType;
|
||||
}, options);
|
||||
}
|
||||
exports._eventWithOptions = _eventWithOptions;
|
||||
/**
|
||||
* The Firebase Analytics event builder interface.
|
||||
*
|
||||
* Access via `functions.analytics.event()`.
|
||||
*/
|
||||
class AnalyticsEventBuilder {
|
||||
/** @hidden */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time a Firebase Analytics event occurs.
|
||||
*
|
||||
* @param handler Event handler that fires every time a Firebase Analytics event
|
||||
* occurs.
|
||||
*
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onLog(handler) {
|
||||
const dataConstructor = (raw) => {
|
||||
return new AnalyticsEvent(raw.data);
|
||||
};
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
eventType: "event.log",
|
||||
service: exports.service,
|
||||
legacyEventType: `providers/google.firebase.analytics/eventTypes/event.log`,
|
||||
triggerResource: this.triggerResource,
|
||||
dataConstructor,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.AnalyticsEventBuilder = AnalyticsEventBuilder;
|
||||
/** Interface representing a Firebase Analytics event that was logged for a specific user. */
|
||||
class AnalyticsEvent {
|
||||
/** @hidden */
|
||||
constructor(wireFormat) {
|
||||
this.params = {}; // In case of absent field, show empty (not absent) map.
|
||||
if (wireFormat.eventDim && wireFormat.eventDim.length > 0) {
|
||||
// If there's an eventDim, there'll always be exactly one.
|
||||
const eventDim = wireFormat.eventDim[0];
|
||||
copyField(eventDim, this, "name");
|
||||
copyField(eventDim, this, "params", (p) => mapKeys(p, unwrapValue));
|
||||
copyFieldTo(eventDim, this, "valueInUsd", "valueInUSD");
|
||||
copyFieldTo(eventDim, this, "date", "reportingDate");
|
||||
copyTimestampToString(eventDim, this, "timestampMicros", "logTime");
|
||||
copyTimestampToString(eventDim, this, "previousTimestampMicros", "previousLogTime");
|
||||
}
|
||||
copyFieldTo(wireFormat, this, "userDim", "user", (dim) => new UserDimensions(dim));
|
||||
}
|
||||
}
|
||||
exports.AnalyticsEvent = AnalyticsEvent;
|
||||
/**
|
||||
* Interface representing the user who triggered the events.
|
||||
*/
|
||||
class UserDimensions {
|
||||
/** @hidden */
|
||||
constructor(wireFormat) {
|
||||
// These are interfaces or primitives, no transformation needed.
|
||||
copyFields(wireFormat, this, ["userId", "deviceInfo", "geoInfo", "appInfo"]);
|
||||
// The following fields do need transformations of some sort.
|
||||
copyTimestampToString(wireFormat, this, "firstOpenTimestampMicros", "firstOpenTime");
|
||||
this.userProperties = {}; // With no entries in the wire format, present an empty (as opposed to absent) map.
|
||||
copyField(wireFormat, this, "userProperties", (r) => {
|
||||
const entries = Object.entries(r).map(([k, v]) => [k, new UserPropertyValue(v)]);
|
||||
return Object.fromEntries(entries);
|
||||
});
|
||||
copyField(wireFormat, this, "bundleInfo", (r) => new ExportBundleInfo(r));
|
||||
// BUG(36000368) Remove when no longer necessary
|
||||
/* tslint:disable:no-string-literal */
|
||||
if (!this.userId && this.userProperties["user_id"]) {
|
||||
this.userId = this.userProperties["user_id"].value;
|
||||
}
|
||||
/* tslint:enable:no-string-literal */
|
||||
}
|
||||
}
|
||||
exports.UserDimensions = UserDimensions;
|
||||
/** Predefined or custom properties stored on the client side. */
|
||||
class UserPropertyValue {
|
||||
/** @hidden */
|
||||
constructor(wireFormat) {
|
||||
copyField(wireFormat, this, "value", unwrapValueAsString);
|
||||
copyTimestampToString(wireFormat, this, "setTimestampUsec", "setTime");
|
||||
}
|
||||
}
|
||||
exports.UserPropertyValue = UserPropertyValue;
|
||||
/** Interface representing the bundle these events were uploaded to. */
|
||||
class ExportBundleInfo {
|
||||
/** @hidden */
|
||||
constructor(wireFormat) {
|
||||
copyField(wireFormat, this, "bundleSequenceId");
|
||||
copyTimestampToMillis(wireFormat, this, "serverTimestampOffsetMicros", "serverTimestampOffset");
|
||||
}
|
||||
}
|
||||
exports.ExportBundleInfo = ExportBundleInfo;
|
||||
/** @hidden */
|
||||
function copyFieldTo(from, to, fromField, toField, transform) {
|
||||
if (typeof from[fromField] === "undefined") {
|
||||
return;
|
||||
}
|
||||
if (transform) {
|
||||
to[toField] = transform(from[fromField]);
|
||||
return;
|
||||
}
|
||||
to[toField] = from[fromField];
|
||||
}
|
||||
/** @hidden */
|
||||
function copyField(from, to, field, transform = (from) => from) {
|
||||
copyFieldTo(from, to, field, field, transform);
|
||||
}
|
||||
/** @hidden */
|
||||
function copyFields(from, to, fields) {
|
||||
for (const field of fields) {
|
||||
copyField(from, to, field);
|
||||
}
|
||||
}
|
||||
function mapKeys(obj, transform) {
|
||||
const entries = Object.entries(obj).map(([k, v]) => [k, transform(v)]);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
// The incoming payload will have fields like:
|
||||
// {
|
||||
// 'myInt': {
|
||||
// 'intValue': '123'
|
||||
// },
|
||||
// 'myDouble': {
|
||||
// 'doubleValue': 1.0
|
||||
// },
|
||||
// 'myFloat': {
|
||||
// 'floatValue': 1.1
|
||||
// },
|
||||
// 'myString': {
|
||||
// 'stringValue': 'hi!'
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// The following method will remove these four types of 'xValue' fields, flattening them
|
||||
// to just their values, as a string:
|
||||
// {
|
||||
// 'myInt': '123',
|
||||
// 'myDouble': '1.0',
|
||||
// 'myFloat': '1.1',
|
||||
// 'myString': 'hi!'
|
||||
// }
|
||||
//
|
||||
// Note that while 'intValue' will have a quoted payload, 'doubleValue' and 'floatValue' will not. This
|
||||
// is due to the encoding library, which renders int64 values as strings to avoid loss of precision. This
|
||||
// method always returns a string, similarly to avoid loss of precision, unlike the less-conservative
|
||||
// 'unwrapValue' method just below.
|
||||
/** @hidden */
|
||||
function unwrapValueAsString(wrapped) {
|
||||
const key = Object.keys(wrapped)[0];
|
||||
return wrapped[key].toString();
|
||||
}
|
||||
// Ditto as the method above, but returning the values in the idiomatic JavaScript type (string for strings,
|
||||
// number for numbers):
|
||||
// {
|
||||
// 'myInt': 123,
|
||||
// 'myDouble': 1.0,
|
||||
// 'myFloat': 1.1,
|
||||
// 'myString': 'hi!'
|
||||
// }
|
||||
//
|
||||
// The field names in the incoming xValue fields identify the type a value has, which for JavaScript's
|
||||
// purposes can be divided into 'number' versus 'string'. This method will render all the numbers as
|
||||
// JavaScript's 'number' type, since we prefer using idiomatic types. Note that this may lead to loss
|
||||
// in precision for int64 fields, so use with care.
|
||||
/** @hidden */
|
||||
const xValueNumberFields = ["intValue", "floatValue", "doubleValue"];
|
||||
/** @hidden */
|
||||
function unwrapValue(wrapped) {
|
||||
const key = Object.keys(wrapped)[0];
|
||||
const value = unwrapValueAsString(wrapped);
|
||||
return xValueNumberFields.includes(key) ? Number(value) : value;
|
||||
}
|
||||
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
|
||||
// The JavaScript convention is to use numbers denoted in milliseconds. This method
|
||||
// makes it easy to convert a field of one type into the other.
|
||||
/** @hidden */
|
||||
function copyTimestampToMillis(from, to, fromName, toName) {
|
||||
if (from[fromName] !== undefined) {
|
||||
to[toName] = Math.round(from[fromName] / 1000);
|
||||
}
|
||||
}
|
||||
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
|
||||
// In our SDK, we'd like to present timestamp as ISO-format strings. This method makes it easy
|
||||
// to convert a field of one type into the other.
|
||||
/** @hidden */
|
||||
function copyTimestampToString(from, to, fromName, toName) {
|
||||
if (from[fromName] !== undefined) {
|
||||
to[toName] = new Date(from[fromName] / 1000).toISOString();
|
||||
}
|
||||
}
|
||||
73
node_modules/firebase-functions/lib/v1/providers/auth.d.ts
generated
vendored
Normal file
73
node_modules/firebase-functions/lib/v1/providers/auth.d.ts
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
import { AuthEventContext, AuthUserRecord, BeforeCreateResponse, BeforeEmailResponse, BeforeSignInResponse, BeforeSmsResponse, HttpsError, MaybeAsync, UserInfo, UserRecord, userRecordConstructor, UserRecordMetadata } from "../../common/providers/identity";
|
||||
import { BlockingFunction, CloudFunction, EventContext } from "../cloud-functions";
|
||||
export { UserRecord, UserInfo, UserRecordMetadata, userRecordConstructor };
|
||||
export { HttpsError };
|
||||
/**
|
||||
* Options for Auth blocking function.
|
||||
*/
|
||||
export interface UserOptions {
|
||||
/** Options to set configuration at the resource level for blocking functions. */
|
||||
blockingOptions?: {
|
||||
/** Pass the ID Token credential to the function. */
|
||||
idToken?: boolean;
|
||||
/** Pass the Access Token credential to the function. */
|
||||
accessToken?: boolean;
|
||||
/** Pass the Refresh Token credential to the function. */
|
||||
refreshToken?: boolean;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Handles events related to Firebase Auth users events.
|
||||
*
|
||||
* @param userOptions - Resource level options
|
||||
* @returns UserBuilder - Builder used to create functions for Firebase Auth user lifecycle events
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export declare function user(userOptions?: UserOptions): UserBuilder;
|
||||
/**
|
||||
* Builder used to create functions for Firebase Auth user lifecycle events.
|
||||
* @public
|
||||
*/
|
||||
export declare class UserBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
private userOptions?;
|
||||
private static dataConstructor;
|
||||
/**
|
||||
* Responds to the creation of a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that responds to the creation of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
onCreate(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
|
||||
/**
|
||||
* Responds to the deletion of a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that responds to the deletion of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
onDelete(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
|
||||
/**
|
||||
* Blocks request to create a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that blocks creation of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
beforeCreate(handler: (user: AuthUserRecord, context: AuthEventContext) => MaybeAsync<BeforeCreateResponse | void>): BlockingFunction;
|
||||
/**
|
||||
* Blocks request to sign-in a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that blocks sign-in of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
beforeSignIn(handler: (user: AuthUserRecord, context: AuthEventContext) => MaybeAsync<BeforeSignInResponse | void>): BlockingFunction;
|
||||
beforeEmail(handler: (context: AuthEventContext) => MaybeAsync<BeforeEmailResponse | void>): BlockingFunction;
|
||||
beforeSms(handler: (context: AuthEventContext) => MaybeAsync<BeforeSmsResponse | void>): BlockingFunction;
|
||||
private onOperation;
|
||||
private beforeOperation;
|
||||
}
|
||||
174
node_modules/firebase-functions/lib/v1/providers/auth.js
generated
vendored
Normal file
174
node_modules/firebase-functions/lib/v1/providers/auth.js
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserBuilder = exports._userWithOptions = exports.user = exports.service = exports.provider = exports.HttpsError = exports.userRecordConstructor = exports.UserRecordMetadata = void 0;
|
||||
const identity_1 = require("../../common/providers/identity");
|
||||
Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function () { return identity_1.HttpsError; } });
|
||||
Object.defineProperty(exports, "userRecordConstructor", { enumerable: true, get: function () { return identity_1.userRecordConstructor; } });
|
||||
Object.defineProperty(exports, "UserRecordMetadata", { enumerable: true, get: function () { return identity_1.UserRecordMetadata; } });
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
const manifest_1 = require("../../runtime/manifest");
|
||||
/** @internal */
|
||||
exports.provider = "google.firebase.auth";
|
||||
/** @internal */
|
||||
exports.service = "firebaseauth.googleapis.com";
|
||||
/**
|
||||
* Handles events related to Firebase Auth users events.
|
||||
*
|
||||
* @param userOptions - Resource level options
|
||||
* @returns UserBuilder - Builder used to create functions for Firebase Auth user lifecycle events
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
function user(userOptions) {
|
||||
return _userWithOptions({}, userOptions || {});
|
||||
}
|
||||
exports.user = user;
|
||||
/** @internal */
|
||||
function _userWithOptions(options, userOptions) {
|
||||
return new UserBuilder(() => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
return "projects/" + process.env.GCLOUD_PROJECT;
|
||||
}, options, userOptions);
|
||||
}
|
||||
exports._userWithOptions = _userWithOptions;
|
||||
/**
|
||||
* Builder used to create functions for Firebase Auth user lifecycle events.
|
||||
* @public
|
||||
*/
|
||||
class UserBuilder {
|
||||
static dataConstructor(raw) {
|
||||
return (0, identity_1.userRecordConstructor)(raw.data);
|
||||
}
|
||||
/* @internal */
|
||||
constructor(triggerResource, options, userOptions) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
this.userOptions = userOptions;
|
||||
}
|
||||
/**
|
||||
* Responds to the creation of a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that responds to the creation of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
onCreate(handler) {
|
||||
return this.onOperation(handler, "user.create");
|
||||
}
|
||||
/**
|
||||
* Responds to the deletion of a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that responds to the deletion of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
onDelete(handler) {
|
||||
return this.onOperation(handler, "user.delete");
|
||||
}
|
||||
/**
|
||||
* Blocks request to create a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that blocks creation of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
beforeCreate(handler) {
|
||||
return this.beforeOperation(handler, "beforeCreate");
|
||||
}
|
||||
/**
|
||||
* Blocks request to sign-in a Firebase Auth user.
|
||||
*
|
||||
* @param handler Event handler that blocks sign-in of a Firebase Auth user.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
beforeSignIn(handler) {
|
||||
return this.beforeOperation(handler, "beforeSignIn");
|
||||
}
|
||||
beforeEmail(handler) {
|
||||
return this.beforeOperation(handler, "beforeSendEmail");
|
||||
}
|
||||
beforeSms(handler) {
|
||||
return this.beforeOperation(handler, "beforeSendSms");
|
||||
}
|
||||
onOperation(handler, eventType) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
eventType,
|
||||
service: exports.service,
|
||||
triggerResource: this.triggerResource,
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
dataConstructor: UserBuilder.dataConstructor,
|
||||
legacyEventType: `providers/firebase.auth/eventTypes/${eventType}`,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
beforeOperation(handler, eventType) {
|
||||
var _a, _b, _c, _d, _e, _f;
|
||||
const accessToken = ((_b = (_a = this.userOptions) === null || _a === void 0 ? void 0 : _a.blockingOptions) === null || _b === void 0 ? void 0 : _b.accessToken) || false;
|
||||
const idToken = ((_d = (_c = this.userOptions) === null || _c === void 0 ? void 0 : _c.blockingOptions) === null || _d === void 0 ? void 0 : _d.idToken) || false;
|
||||
const refreshToken = ((_f = (_e = this.userOptions) === null || _e === void 0 ? void 0 : _e.blockingOptions) === null || _f === void 0 ? void 0 : _f.refreshToken) || false;
|
||||
const annotatedHandler = Object.assign(handler, { platform: "gcfv1" });
|
||||
const func = (0, identity_1.wrapHandler)(eventType, annotatedHandler);
|
||||
const legacyEventType = `providers/cloud.auth/eventTypes/user.${eventType}`;
|
||||
func.__trigger = {
|
||||
labels: {},
|
||||
...(0, cloud_functions_1.optionsToTrigger)(this.options),
|
||||
blockingTrigger: {
|
||||
eventType: legacyEventType,
|
||||
options: {
|
||||
accessToken,
|
||||
idToken,
|
||||
refreshToken,
|
||||
},
|
||||
},
|
||||
};
|
||||
func.__endpoint = {
|
||||
platform: "gcfv1",
|
||||
labels: {},
|
||||
...(0, manifest_1.initV1Endpoint)(this.options),
|
||||
...(0, cloud_functions_1.optionsToEndpoint)(this.options),
|
||||
blockingTrigger: {
|
||||
eventType: legacyEventType,
|
||||
options: {
|
||||
accessToken,
|
||||
idToken,
|
||||
refreshToken,
|
||||
},
|
||||
},
|
||||
};
|
||||
func.__requiredAPIs = [
|
||||
{
|
||||
api: "identitytoolkit.googleapis.com",
|
||||
reason: "Needed for auth blocking functions",
|
||||
},
|
||||
];
|
||||
func.run = handler;
|
||||
return func;
|
||||
}
|
||||
}
|
||||
exports.UserBuilder = UserBuilder;
|
||||
117
node_modules/firebase-functions/lib/v1/providers/database.d.ts
generated
vendored
Normal file
117
node_modules/firebase-functions/lib/v1/providers/database.d.ts
generated
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
import { Change } from "../../common/change";
|
||||
import { ParamsOf } from "../../common/params";
|
||||
import { DataSnapshot } from "../../common/providers/database";
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
import { DeploymentOptions } from "../function-configuration";
|
||||
export { DataSnapshot };
|
||||
/**
|
||||
* Registers a function that triggers on events from a specific
|
||||
* Firebase Realtime Database instance.
|
||||
*
|
||||
* @remarks
|
||||
* Use this method together with `ref` to specify the instance on which to
|
||||
* watch for database events. For example: `firebase.database.instance('my-app-db-2').ref('/foo/bar')`
|
||||
*
|
||||
* Note that `functions.database.ref` used without `instance` watches the
|
||||
* *default* instance for events.
|
||||
*
|
||||
* @param instance The instance name of the database instance
|
||||
* to watch for write events.
|
||||
* @returns Firebase Realtime Database instance builder interface.
|
||||
*/
|
||||
export declare function instance(instance: string): InstanceBuilder;
|
||||
/**
|
||||
* Registers a function that triggers on Firebase Realtime Database write
|
||||
* events.
|
||||
*
|
||||
* @remarks
|
||||
* This method behaves very similarly to the method of the same name in the
|
||||
* client and Admin Firebase SDKs. Any change to the Database that affects the
|
||||
* data at or below the provided `path` will fire an event in Cloud Functions.
|
||||
*
|
||||
* There are three important differences between listening to a Realtime
|
||||
* Database event in Cloud Functions and using the Realtime Database in the
|
||||
* client and Admin SDKs:
|
||||
*
|
||||
* 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
|
||||
* in curly brackets (`{}`) is a wildcard that matches all strings. The value
|
||||
* that matched a certain invocation of a Cloud Function is returned as part
|
||||
* of the [`EventContext.params`](cloud_functions_eventcontext.html#params object. For
|
||||
* example, `ref("messages/{messageId}")` matches changes at
|
||||
* `/messages/message1` or `/messages/message2`, resulting in
|
||||
* `event.params.messageId` being set to `"message1"` or `"message2"`,
|
||||
* respectively.
|
||||
*
|
||||
* 2. Cloud Functions do not fire an event for data that already existed before
|
||||
* the Cloud Function was deployed.
|
||||
*
|
||||
* 3. Cloud Function events have access to more information, including a
|
||||
* snapshot of the previous event data and information about the user who
|
||||
* triggered the Cloud Function.
|
||||
*
|
||||
* @param path The path within the Database to watch for write events.
|
||||
* @returns Firebase Realtime Database builder interface.
|
||||
*/
|
||||
export declare function ref<Ref extends string>(path: Ref): RefBuilder<Ref>;
|
||||
/**
|
||||
* The Firebase Realtime Database instance builder interface.
|
||||
*
|
||||
* Access via [`database.instance()`](providers_database_.html#instance).
|
||||
*/
|
||||
export declare class InstanceBuilder {
|
||||
private instance;
|
||||
private options;
|
||||
constructor(instance: string, options: DeploymentOptions);
|
||||
/**
|
||||
* @returns Firebase Realtime Database reference builder interface.
|
||||
*/
|
||||
ref<Ref extends string>(path: Ref): RefBuilder<Ref>;
|
||||
}
|
||||
/**
|
||||
* The Firebase Realtime Database reference builder interface.
|
||||
*
|
||||
* Access via [`functions.database.ref()`](functions.database#.ref).
|
||||
*/
|
||||
export declare class RefBuilder<Ref extends string> {
|
||||
private triggerResource;
|
||||
private options;
|
||||
constructor(triggerResource: () => string, options: DeploymentOptions);
|
||||
/**
|
||||
* Event handler that fires every time a Firebase Realtime Database write
|
||||
* of any kind (creation, update, or delete) occurs.
|
||||
*
|
||||
* @param handler Event handler that runs every time a Firebase Realtime Database
|
||||
* write occurs.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onWrite(handler: (change: Change<DataSnapshot>, context: EventContext<ParamsOf<Ref>>) => PromiseLike<any> | any): CloudFunction<Change<DataSnapshot>>;
|
||||
/**
|
||||
* Event handler that fires every time data is updated in
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Firebase Realtime Database
|
||||
* write occurs.
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onUpdate(handler: (change: Change<DataSnapshot>, context: EventContext<ParamsOf<Ref>>) => PromiseLike<any> | any): CloudFunction<Change<DataSnapshot>>;
|
||||
/**
|
||||
* Event handler that fires every time new data is created in
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler that runs every time new data is created in
|
||||
* Firebase Realtime Database.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onCreate(handler: (snapshot: DataSnapshot, context: EventContext<ParamsOf<Ref>>) => PromiseLike<any> | any): CloudFunction<DataSnapshot>;
|
||||
/**
|
||||
* Event handler that fires every time data is deleted from
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler that runs every time data is deleted from
|
||||
* Firebase Realtime Database.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onDelete(handler: (snapshot: DataSnapshot, context: EventContext<ParamsOf<Ref>>) => PromiseLike<any> | any): CloudFunction<DataSnapshot>;
|
||||
private onOperation;
|
||||
private changeConstructor;
|
||||
}
|
||||
263
node_modules/firebase-functions/lib/v1/providers/database.js
generated
vendored
Normal file
263
node_modules/firebase-functions/lib/v1/providers/database.js
generated
vendored
Normal file
@@ -0,0 +1,263 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.extractInstanceAndPath = exports.RefBuilder = exports._refWithOptions = exports.InstanceBuilder = exports._instanceWithOptions = exports.ref = exports.instance = exports.service = exports.provider = exports.DataSnapshot = void 0;
|
||||
const app_1 = require("../../common/app");
|
||||
const config_1 = require("../../common/config");
|
||||
const database_1 = require("../../common/providers/database");
|
||||
Object.defineProperty(exports, "DataSnapshot", { enumerable: true, get: function () { return database_1.DataSnapshot; } });
|
||||
const path_1 = require("../../common/utilities/path");
|
||||
const utils_1 = require("../../common/utilities/utils");
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.firebase.database";
|
||||
/** @internal */
|
||||
exports.service = "firebaseio.com";
|
||||
const databaseURLRegex = new RegExp("^https://([^.]+).");
|
||||
const emulatorDatabaseURLRegex = new RegExp("^http://.*ns=([^&]+)");
|
||||
/**
|
||||
* Registers a function that triggers on events from a specific
|
||||
* Firebase Realtime Database instance.
|
||||
*
|
||||
* @remarks
|
||||
* Use this method together with `ref` to specify the instance on which to
|
||||
* watch for database events. For example: `firebase.database.instance('my-app-db-2').ref('/foo/bar')`
|
||||
*
|
||||
* Note that `functions.database.ref` used without `instance` watches the
|
||||
* *default* instance for events.
|
||||
*
|
||||
* @param instance The instance name of the database instance
|
||||
* to watch for write events.
|
||||
* @returns Firebase Realtime Database instance builder interface.
|
||||
*/
|
||||
function instance(instance) {
|
||||
return _instanceWithOptions(instance, {});
|
||||
}
|
||||
exports.instance = instance;
|
||||
/**
|
||||
* Registers a function that triggers on Firebase Realtime Database write
|
||||
* events.
|
||||
*
|
||||
* @remarks
|
||||
* This method behaves very similarly to the method of the same name in the
|
||||
* client and Admin Firebase SDKs. Any change to the Database that affects the
|
||||
* data at or below the provided `path` will fire an event in Cloud Functions.
|
||||
*
|
||||
* There are three important differences between listening to a Realtime
|
||||
* Database event in Cloud Functions and using the Realtime Database in the
|
||||
* client and Admin SDKs:
|
||||
*
|
||||
* 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
|
||||
* in curly brackets (`{}`) is a wildcard that matches all strings. The value
|
||||
* that matched a certain invocation of a Cloud Function is returned as part
|
||||
* of the [`EventContext.params`](cloud_functions_eventcontext.html#params object. For
|
||||
* example, `ref("messages/{messageId}")` matches changes at
|
||||
* `/messages/message1` or `/messages/message2`, resulting in
|
||||
* `event.params.messageId` being set to `"message1"` or `"message2"`,
|
||||
* respectively.
|
||||
*
|
||||
* 2. Cloud Functions do not fire an event for data that already existed before
|
||||
* the Cloud Function was deployed.
|
||||
*
|
||||
* 3. Cloud Function events have access to more information, including a
|
||||
* snapshot of the previous event data and information about the user who
|
||||
* triggered the Cloud Function.
|
||||
*
|
||||
* @param path The path within the Database to watch for write events.
|
||||
* @returns Firebase Realtime Database builder interface.
|
||||
*/
|
||||
function ref(path) {
|
||||
return _refWithOptions(path, {});
|
||||
}
|
||||
exports.ref = ref;
|
||||
/** @internal */
|
||||
function _instanceWithOptions(instance, options) {
|
||||
return new InstanceBuilder(instance, options);
|
||||
}
|
||||
exports._instanceWithOptions = _instanceWithOptions;
|
||||
/**
|
||||
* The Firebase Realtime Database instance builder interface.
|
||||
*
|
||||
* Access via [`database.instance()`](providers_database_.html#instance).
|
||||
*/
|
||||
class InstanceBuilder {
|
||||
constructor(instance, options) {
|
||||
this.instance = instance;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* @returns Firebase Realtime Database reference builder interface.
|
||||
*/
|
||||
ref(path) {
|
||||
const normalized = (0, path_1.normalizePath)(path);
|
||||
return new RefBuilder(() => `projects/_/instances/${this.instance}/refs/${normalized}`, this.options);
|
||||
}
|
||||
}
|
||||
exports.InstanceBuilder = InstanceBuilder;
|
||||
/** @internal */
|
||||
function _refWithOptions(path, options) {
|
||||
const resourceGetter = () => {
|
||||
const normalized = (0, path_1.normalizePath)(path);
|
||||
const databaseURL = (0, config_1.firebaseConfig)().databaseURL;
|
||||
if (!databaseURL) {
|
||||
throw new Error("Missing expected firebase config value databaseURL, " +
|
||||
"config is actually" +
|
||||
JSON.stringify((0, config_1.firebaseConfig)()) +
|
||||
"\n If you are unit testing, please set process.env.FIREBASE_CONFIG");
|
||||
}
|
||||
let instance;
|
||||
const prodMatch = databaseURL.match(databaseURLRegex);
|
||||
if (prodMatch) {
|
||||
instance = prodMatch[1];
|
||||
}
|
||||
else {
|
||||
const emulatorMatch = databaseURL.match(emulatorDatabaseURLRegex);
|
||||
if (emulatorMatch) {
|
||||
instance = emulatorMatch[1];
|
||||
}
|
||||
}
|
||||
if (!instance) {
|
||||
throw new Error("Invalid value for config firebase.databaseURL: " + databaseURL);
|
||||
}
|
||||
return `projects/_/instances/${instance}/refs/${normalized}`;
|
||||
};
|
||||
return new RefBuilder(resourceGetter, options);
|
||||
}
|
||||
exports._refWithOptions = _refWithOptions;
|
||||
/**
|
||||
* The Firebase Realtime Database reference builder interface.
|
||||
*
|
||||
* Access via [`functions.database.ref()`](functions.database#.ref).
|
||||
*/
|
||||
class RefBuilder {
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
this.changeConstructor = (raw) => {
|
||||
const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
|
||||
const before = new database_1.DataSnapshot(raw.data.data, path, (0, app_1.getApp)(), dbInstance);
|
||||
const after = new database_1.DataSnapshot((0, utils_1.applyChange)(raw.data.data, raw.data.delta), path, (0, app_1.getApp)(), dbInstance);
|
||||
return {
|
||||
before,
|
||||
after,
|
||||
};
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time a Firebase Realtime Database write
|
||||
* of any kind (creation, update, or delete) occurs.
|
||||
*
|
||||
* @param handler Event handler that runs every time a Firebase Realtime Database
|
||||
* write occurs.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onWrite(handler) {
|
||||
return this.onOperation(handler, "ref.write", this.changeConstructor);
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time data is updated in
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Firebase Realtime Database
|
||||
* write occurs.
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onUpdate(handler) {
|
||||
return this.onOperation(handler, "ref.update", this.changeConstructor);
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time new data is created in
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler that runs every time new data is created in
|
||||
* Firebase Realtime Database.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onCreate(handler) {
|
||||
const dataConstructor = (raw) => {
|
||||
const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
|
||||
return new database_1.DataSnapshot(raw.data.delta, path, (0, app_1.getApp)(), dbInstance);
|
||||
};
|
||||
return this.onOperation(handler, "ref.create", dataConstructor);
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time data is deleted from
|
||||
* Firebase Realtime Database.
|
||||
*
|
||||
* @param handler Event handler that runs every time data is deleted from
|
||||
* Firebase Realtime Database.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onDelete(handler) {
|
||||
const dataConstructor = (raw) => {
|
||||
const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
|
||||
return new database_1.DataSnapshot(raw.data.data, path, (0, app_1.getApp)(), dbInstance);
|
||||
};
|
||||
return this.onOperation(handler, "ref.delete", dataConstructor);
|
||||
}
|
||||
onOperation(handler, eventType, dataConstructor) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
service: exports.service,
|
||||
eventType,
|
||||
legacyEventType: `providers/${exports.provider}/eventTypes/${eventType}`,
|
||||
triggerResource: this.triggerResource,
|
||||
dataConstructor,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.RefBuilder = RefBuilder;
|
||||
const resourceRegex = /^projects\/([^/]+)\/instances\/([a-zA-Z0-9-]+)\/refs(\/.+)?/;
|
||||
/**
|
||||
* Utility function to extract database reference from resource string
|
||||
*
|
||||
* @param optional database domain override for the original of the source database.
|
||||
* It defaults to `firebaseio.com`.
|
||||
* Multi-region RTDB will be served from different domains.
|
||||
* Since region is not part of the resource name, it is provided through context.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
function extractInstanceAndPath(resource, domain = "firebaseio.com") {
|
||||
const match = resource.match(new RegExp(resourceRegex));
|
||||
if (!match) {
|
||||
throw new Error(`Unexpected resource string for Firebase Realtime Database event: ${resource}. ` +
|
||||
'Expected string in the format of "projects/_/instances/{firebaseioSubdomain}/refs/{ref=**}"');
|
||||
}
|
||||
const [, project, dbInstanceName, path] = match;
|
||||
if (project !== "_") {
|
||||
throw new Error(`Expect project to be '_' in a Firebase Realtime Database event`);
|
||||
}
|
||||
const emuHost = process.env.FIREBASE_DATABASE_EMULATOR_HOST;
|
||||
if (emuHost) {
|
||||
const dbInstance = `http://${emuHost}/?ns=${dbInstanceName}`;
|
||||
return [dbInstance, path];
|
||||
}
|
||||
else {
|
||||
const dbInstance = "https://" + dbInstanceName + "." + domain;
|
||||
return [dbInstance, path];
|
||||
}
|
||||
}
|
||||
exports.extractInstanceAndPath = extractInstanceAndPath;
|
||||
47
node_modules/firebase-functions/lib/v1/providers/firestore.d.ts
generated
vendored
Normal file
47
node_modules/firebase-functions/lib/v1/providers/firestore.d.ts
generated
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
import * as firestore from "firebase-admin/firestore";
|
||||
import { Change } from "../../common/change";
|
||||
import { ParamsOf } from "../../common/params";
|
||||
import { CloudFunction, Event, EventContext } from "../cloud-functions";
|
||||
import { DeploymentOptions } from "../function-configuration";
|
||||
export type DocumentSnapshot = firestore.DocumentSnapshot;
|
||||
export type QueryDocumentSnapshot = firestore.QueryDocumentSnapshot;
|
||||
/**
|
||||
* Select the Firestore document to listen to for events.
|
||||
* @param path Full database path to listen to. This includes the name of
|
||||
* the collection that the document is a part of. For example, if the
|
||||
* collection is named "users" and the document is named "Ada", then the
|
||||
* path is "/users/Ada".
|
||||
*/
|
||||
export declare function document<Path extends string>(path: Path): DocumentBuilder<Path>;
|
||||
export declare function namespace(namespace: string): NamespaceBuilder;
|
||||
export declare function database(database: string): DatabaseBuilder;
|
||||
export declare class DatabaseBuilder {
|
||||
private database;
|
||||
private options;
|
||||
constructor(database: string, options: DeploymentOptions);
|
||||
namespace(namespace: string): NamespaceBuilder;
|
||||
document<Path extends string>(path: Path): DocumentBuilder<Path>;
|
||||
}
|
||||
export declare class NamespaceBuilder {
|
||||
private database;
|
||||
private options;
|
||||
private namespace?;
|
||||
constructor(database: string, options: DeploymentOptions, namespace?: string);
|
||||
document<Path extends string>(path: Path): DocumentBuilder<Path>;
|
||||
}
|
||||
export declare function snapshotConstructor(event: Event): DocumentSnapshot;
|
||||
export declare function beforeSnapshotConstructor(event: Event): DocumentSnapshot;
|
||||
export declare class DocumentBuilder<Path extends string> {
|
||||
private triggerResource;
|
||||
private options;
|
||||
constructor(triggerResource: () => string, options: DeploymentOptions);
|
||||
/** Respond to all document writes (creates, updates, or deletes). */
|
||||
onWrite(handler: (change: Change<DocumentSnapshot>, context: EventContext<ParamsOf<Path>>) => PromiseLike<any> | any): CloudFunction<Change<DocumentSnapshot>>;
|
||||
/** Respond only to document updates. */
|
||||
onUpdate(handler: (change: Change<QueryDocumentSnapshot>, context: EventContext<ParamsOf<Path>>) => PromiseLike<any> | any): CloudFunction<Change<QueryDocumentSnapshot>>;
|
||||
/** Respond only to document creations. */
|
||||
onCreate(handler: (snapshot: QueryDocumentSnapshot, context: EventContext<ParamsOf<Path>>) => PromiseLike<any> | any): CloudFunction<QueryDocumentSnapshot>;
|
||||
/** Respond only to document deletions. */
|
||||
onDelete(handler: (snapshot: QueryDocumentSnapshot, context: EventContext<ParamsOf<Path>>) => PromiseLike<any> | any): CloudFunction<QueryDocumentSnapshot>;
|
||||
private onOperation;
|
||||
}
|
||||
150
node_modules/firebase-functions/lib/v1/providers/firestore.js
generated
vendored
Normal file
150
node_modules/firebase-functions/lib/v1/providers/firestore.js
generated
vendored
Normal file
@@ -0,0 +1,150 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DocumentBuilder = exports.beforeSnapshotConstructor = exports.snapshotConstructor = exports.NamespaceBuilder = exports.DatabaseBuilder = exports._documentWithOptions = exports._namespaceWithOptions = exports._databaseWithOptions = exports.database = exports.namespace = exports.document = exports.defaultDatabase = exports.service = exports.provider = void 0;
|
||||
const path_1 = require("path");
|
||||
const change_1 = require("../../common/change");
|
||||
const firestore_1 = require("../../common/providers/firestore");
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.firestore";
|
||||
/** @internal */
|
||||
exports.service = "firestore.googleapis.com";
|
||||
/** @internal */
|
||||
exports.defaultDatabase = "(default)";
|
||||
/**
|
||||
* Select the Firestore document to listen to for events.
|
||||
* @param path Full database path to listen to. This includes the name of
|
||||
* the collection that the document is a part of. For example, if the
|
||||
* collection is named "users" and the document is named "Ada", then the
|
||||
* path is "/users/Ada".
|
||||
*/
|
||||
function document(path) {
|
||||
return _documentWithOptions(path, {});
|
||||
}
|
||||
exports.document = document;
|
||||
// Multiple namespaces are not yet supported by Firestore.
|
||||
function namespace(namespace) {
|
||||
return _namespaceWithOptions(namespace, {});
|
||||
}
|
||||
exports.namespace = namespace;
|
||||
// Multiple databases are not yet supported by Firestore.
|
||||
function database(database) {
|
||||
return _databaseWithOptions(database, {});
|
||||
}
|
||||
exports.database = database;
|
||||
/** @internal */
|
||||
function _databaseWithOptions(database = exports.defaultDatabase, options) {
|
||||
return new DatabaseBuilder(database, options);
|
||||
}
|
||||
exports._databaseWithOptions = _databaseWithOptions;
|
||||
/** @internal */
|
||||
function _namespaceWithOptions(namespace, options) {
|
||||
return _databaseWithOptions(exports.defaultDatabase, options).namespace(namespace);
|
||||
}
|
||||
exports._namespaceWithOptions = _namespaceWithOptions;
|
||||
/** @internal */
|
||||
function _documentWithOptions(path, options) {
|
||||
return _databaseWithOptions(exports.defaultDatabase, options).document(path);
|
||||
}
|
||||
exports._documentWithOptions = _documentWithOptions;
|
||||
class DatabaseBuilder {
|
||||
constructor(database, options) {
|
||||
this.database = database;
|
||||
this.options = options;
|
||||
}
|
||||
namespace(namespace) {
|
||||
return new NamespaceBuilder(this.database, this.options, namespace);
|
||||
}
|
||||
document(path) {
|
||||
return new NamespaceBuilder(this.database, this.options).document(path);
|
||||
}
|
||||
}
|
||||
exports.DatabaseBuilder = DatabaseBuilder;
|
||||
class NamespaceBuilder {
|
||||
constructor(database, options, namespace) {
|
||||
this.database = database;
|
||||
this.options = options;
|
||||
this.namespace = namespace;
|
||||
}
|
||||
document(path) {
|
||||
return new DocumentBuilder(() => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
const database = path_1.posix.join("projects", process.env.GCLOUD_PROJECT, "databases", this.database);
|
||||
return path_1.posix.join(database, this.namespace ? `documents@${this.namespace}` : "documents", path);
|
||||
}, this.options);
|
||||
}
|
||||
}
|
||||
exports.NamespaceBuilder = NamespaceBuilder;
|
||||
function snapshotConstructor(event) {
|
||||
var _a, _b, _c, _d;
|
||||
return (0, firestore_1.createSnapshotFromJson)(event.data, event.context.resource.name, (_b = (_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.readTime, (_d = (_c = event === null || event === void 0 ? void 0 : event.data) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d.updateTime);
|
||||
}
|
||||
exports.snapshotConstructor = snapshotConstructor;
|
||||
// TODO remove this function when wire format changes to new format
|
||||
function beforeSnapshotConstructor(event) {
|
||||
var _a, _b;
|
||||
return (0, firestore_1.createBeforeSnapshotFromJson)(event.data, event.context.resource.name, (_b = (_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.oldValue) === null || _b === void 0 ? void 0 : _b.readTime, undefined);
|
||||
}
|
||||
exports.beforeSnapshotConstructor = beforeSnapshotConstructor;
|
||||
function changeConstructor(raw) {
|
||||
return change_1.Change.fromObjects(beforeSnapshotConstructor(raw), snapshotConstructor(raw));
|
||||
}
|
||||
class DocumentBuilder {
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
// TODO what validation do we want to do here?
|
||||
}
|
||||
/** Respond to all document writes (creates, updates, or deletes). */
|
||||
onWrite(handler) {
|
||||
return this.onOperation(handler, "document.write", changeConstructor);
|
||||
}
|
||||
/** Respond only to document updates. */
|
||||
onUpdate(handler) {
|
||||
return this.onOperation(handler, "document.update", changeConstructor);
|
||||
}
|
||||
/** Respond only to document creations. */
|
||||
onCreate(handler) {
|
||||
return this.onOperation(handler, "document.create", snapshotConstructor);
|
||||
}
|
||||
/** Respond only to document deletions. */
|
||||
onDelete(handler) {
|
||||
return this.onOperation(handler, "document.delete", beforeSnapshotConstructor);
|
||||
}
|
||||
onOperation(handler, eventType, dataConstructor) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
eventType,
|
||||
service: exports.service,
|
||||
triggerResource: this.triggerResource,
|
||||
legacyEventType: `providers/cloud.firestore/eventTypes/${eventType}`,
|
||||
dataConstructor,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.DocumentBuilder = DocumentBuilder;
|
||||
15
node_modules/firebase-functions/lib/v1/providers/https.d.ts
generated
vendored
Normal file
15
node_modules/firebase-functions/lib/v1/providers/https.d.ts
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import * as express from "express";
|
||||
import { CallableContext, FunctionsErrorCode, HttpsError, Request } from "../../common/providers/https";
|
||||
import { HttpsFunction, Runnable } from "../cloud-functions";
|
||||
export { Request, CallableContext, FunctionsErrorCode, HttpsError };
|
||||
/**
|
||||
* Handle HTTP requests.
|
||||
* @param handler A function that takes a request and response object,
|
||||
* same signature as an Express app.
|
||||
*/
|
||||
export declare function onRequest(handler: (req: Request, resp: express.Response) => void | Promise<void>): HttpsFunction;
|
||||
/**
|
||||
* Declares a callable method for clients to call using a Firebase SDK.
|
||||
* @param handler A method that takes a data and context and returns a value.
|
||||
*/
|
||||
export declare function onCall(handler: (data: any, context: CallableContext) => any | Promise<any>): HttpsFunction & Runnable<any>;
|
||||
99
node_modules/firebase-functions/lib/v1/providers/https.js
generated
vendored
Normal file
99
node_modules/firebase-functions/lib/v1/providers/https.js
generated
vendored
Normal file
@@ -0,0 +1,99 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports._onCallWithOptions = exports._onRequestWithOptions = exports.onCall = exports.onRequest = exports.HttpsError = void 0;
|
||||
const encoding_1 = require("../../common/encoding");
|
||||
const https_1 = require("../../common/providers/https");
|
||||
Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function () { return https_1.HttpsError; } });
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
const manifest_1 = require("../../runtime/manifest");
|
||||
const onInit_1 = require("../../common/onInit");
|
||||
const trace_1 = require("../../v2/trace");
|
||||
/**
|
||||
* Handle HTTP requests.
|
||||
* @param handler A function that takes a request and response object,
|
||||
* same signature as an Express app.
|
||||
*/
|
||||
function onRequest(handler) {
|
||||
return _onRequestWithOptions(handler, {});
|
||||
}
|
||||
exports.onRequest = onRequest;
|
||||
/**
|
||||
* Declares a callable method for clients to call using a Firebase SDK.
|
||||
* @param handler A method that takes a data and context and returns a value.
|
||||
*/
|
||||
function onCall(handler) {
|
||||
return _onCallWithOptions(handler, {});
|
||||
}
|
||||
exports.onCall = onCall;
|
||||
/** @internal */
|
||||
function _onRequestWithOptions(handler, options) {
|
||||
// lets us add __endpoint without altering handler:
|
||||
const cloudFunction = (req, res) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(req, res);
|
||||
};
|
||||
cloudFunction.__trigger = {
|
||||
...(0, cloud_functions_1.optionsToTrigger)(options),
|
||||
httpsTrigger: {},
|
||||
};
|
||||
(0, encoding_1.convertIfPresent)(cloudFunction.__trigger.httpsTrigger, options, "invoker", "invoker", encoding_1.convertInvoker);
|
||||
// TODO parse the options
|
||||
cloudFunction.__endpoint = {
|
||||
platform: "gcfv1",
|
||||
...(0, manifest_1.initV1Endpoint)(options),
|
||||
...(0, cloud_functions_1.optionsToEndpoint)(options),
|
||||
httpsTrigger: {},
|
||||
};
|
||||
(0, encoding_1.convertIfPresent)(cloudFunction.__endpoint.httpsTrigger, options, "invoker", "invoker", encoding_1.convertInvoker);
|
||||
return cloudFunction;
|
||||
}
|
||||
exports._onRequestWithOptions = _onRequestWithOptions;
|
||||
/** @internal */
|
||||
function _onCallWithOptions(handler, options) {
|
||||
// fix the length of handler to make the call to handler consistent
|
||||
// in the onCallHandler
|
||||
const fixedLen = (data, context) => {
|
||||
return (0, onInit_1.withInit)(handler)(data, context);
|
||||
};
|
||||
const func = (0, trace_1.wrapTraceContext)((0, https_1.onCallHandler)({
|
||||
enforceAppCheck: options.enforceAppCheck,
|
||||
consumeAppCheckToken: options.consumeAppCheckToken,
|
||||
cors: { origin: true, methods: "POST" },
|
||||
}, fixedLen, "gcfv1"));
|
||||
func.__trigger = {
|
||||
labels: {},
|
||||
...(0, cloud_functions_1.optionsToTrigger)(options),
|
||||
httpsTrigger: {},
|
||||
};
|
||||
func.__trigger.labels["deployment-callable"] = "true";
|
||||
func.__endpoint = {
|
||||
platform: "gcfv1",
|
||||
labels: {},
|
||||
...(0, manifest_1.initV1Endpoint)(options),
|
||||
...(0, cloud_functions_1.optionsToEndpoint)(options),
|
||||
callableTrigger: {},
|
||||
};
|
||||
func.run = fixedLen;
|
||||
return func;
|
||||
}
|
||||
exports._onCallWithOptions = _onCallWithOptions;
|
||||
93
node_modules/firebase-functions/lib/v1/providers/pubsub.d.ts
generated
vendored
Normal file
93
node_modules/firebase-functions/lib/v1/providers/pubsub.d.ts
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
import { DeploymentOptions, ScheduleRetryConfig } from "../function-configuration";
|
||||
/**
|
||||
* Registers a Cloud Function triggered when a Google Cloud Pub/Sub message
|
||||
* is sent to a specified topic.
|
||||
*
|
||||
* @param topic - The Pub/Sub topic to watch for message events.
|
||||
* @returns Pub/Sub topic builder interface.
|
||||
*/
|
||||
export declare function topic(topic: string): TopicBuilder;
|
||||
/**
|
||||
* The Google Cloud Pub/Sub topic builder.
|
||||
*
|
||||
* Access via `functions.pubsub.topic()`.
|
||||
*/
|
||||
export declare class TopicBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/** @hidden */
|
||||
constructor(triggerResource: () => string, options: DeploymentOptions);
|
||||
/**
|
||||
* Event handler that fires every time a Cloud Pub/Sub message is
|
||||
* published.
|
||||
*
|
||||
* @param handler - Event handler that runs every time a Cloud Pub/Sub message
|
||||
* is published.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onPublish(handler: (message: Message, context: EventContext) => PromiseLike<any> | any): CloudFunction<Message>;
|
||||
}
|
||||
/**
|
||||
* Registers a Cloud Function to run at specified times.
|
||||
*
|
||||
* @param schedule - The schedule, in Unix Crontab or AppEngine syntax.
|
||||
* @returns ScheduleBuilder interface.
|
||||
*/
|
||||
export declare function schedule(schedule: string): ScheduleBuilder;
|
||||
/**
|
||||
* The builder for scheduled functions, which are powered by
|
||||
* Google Pub/Sub and Cloud Scheduler. Describes the Cloud Scheduler
|
||||
* job that is deployed to trigger a scheduled function at the provided
|
||||
* frequency. For more information, see
|
||||
* [Schedule functions](/docs/functions/schedule-functions).
|
||||
*
|
||||
* Access via `functions.pubsub.schedule()`.
|
||||
*/
|
||||
export declare class ScheduleBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/** @hidden */
|
||||
constructor(triggerResource: () => string, options: DeploymentOptions);
|
||||
retryConfig(config: ScheduleRetryConfig): ScheduleBuilder;
|
||||
timeZone(timeZone: string): ScheduleBuilder;
|
||||
/**
|
||||
* Event handler for scheduled functions. Triggered whenever the associated
|
||||
* scheduler job sends a Pub/Sub message.
|
||||
*
|
||||
* @param handler - Handler that fires whenever the associated
|
||||
* scheduler job sends a Pub/Sub message.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onRun(handler: (context: EventContext) => PromiseLike<any> | any): CloudFunction<unknown>;
|
||||
}
|
||||
/**
|
||||
* Interface representing a Google Cloud Pub/Sub message.
|
||||
*
|
||||
* @param data - Payload of a Pub/Sub message.
|
||||
*/
|
||||
export declare class Message {
|
||||
/**
|
||||
* The data payload of this message object as a base64-encoded string.
|
||||
*/
|
||||
readonly data: string;
|
||||
/**
|
||||
* User-defined attributes published with the message, if any.
|
||||
*/
|
||||
readonly attributes: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/** @hidden */
|
||||
private _json;
|
||||
constructor(data: any);
|
||||
/**
|
||||
* The JSON data payload of this message object, if any.
|
||||
*/
|
||||
get json(): any;
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*
|
||||
* @returns A JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON(): any;
|
||||
}
|
||||
186
node_modules/firebase-functions/lib/v1/providers/pubsub.js
generated
vendored
Normal file
186
node_modules/firebase-functions/lib/v1/providers/pubsub.js
generated
vendored
Normal file
@@ -0,0 +1,186 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Message = exports.ScheduleBuilder = exports._scheduleWithOptions = exports.schedule = exports.TopicBuilder = exports._topicWithOptions = exports.topic = exports.service = exports.provider = void 0;
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.pubsub";
|
||||
/** @internal */
|
||||
exports.service = "pubsub.googleapis.com";
|
||||
/**
|
||||
* Registers a Cloud Function triggered when a Google Cloud Pub/Sub message
|
||||
* is sent to a specified topic.
|
||||
*
|
||||
* @param topic - The Pub/Sub topic to watch for message events.
|
||||
* @returns Pub/Sub topic builder interface.
|
||||
*/
|
||||
function topic(topic) {
|
||||
return _topicWithOptions(topic, {});
|
||||
}
|
||||
exports.topic = topic;
|
||||
/** @internal */
|
||||
function _topicWithOptions(topic, options) {
|
||||
if (topic.indexOf("/") !== -1) {
|
||||
throw new Error("Topic name may not have a /");
|
||||
}
|
||||
return new TopicBuilder(() => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
return `projects/${process.env.GCLOUD_PROJECT}/topics/${topic}`;
|
||||
}, options);
|
||||
}
|
||||
exports._topicWithOptions = _topicWithOptions;
|
||||
/**
|
||||
* The Google Cloud Pub/Sub topic builder.
|
||||
*
|
||||
* Access via `functions.pubsub.topic()`.
|
||||
*/
|
||||
class TopicBuilder {
|
||||
/** @hidden */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Event handler that fires every time a Cloud Pub/Sub message is
|
||||
* published.
|
||||
*
|
||||
* @param handler - Event handler that runs every time a Cloud Pub/Sub message
|
||||
* is published.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onPublish(handler) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
service: exports.service,
|
||||
triggerResource: this.triggerResource,
|
||||
eventType: "topic.publish",
|
||||
dataConstructor: (raw) => new Message(raw.data),
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.TopicBuilder = TopicBuilder;
|
||||
/**
|
||||
* Registers a Cloud Function to run at specified times.
|
||||
*
|
||||
* @param schedule - The schedule, in Unix Crontab or AppEngine syntax.
|
||||
* @returns ScheduleBuilder interface.
|
||||
*/
|
||||
function schedule(schedule) {
|
||||
return _scheduleWithOptions(schedule, {});
|
||||
}
|
||||
exports.schedule = schedule;
|
||||
/** @internal */
|
||||
function _scheduleWithOptions(schedule, options) {
|
||||
const triggerResource = () => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
// The CLI will append the correct topic name based on region and function name
|
||||
return `projects/${process.env.GCLOUD_PROJECT}/topics`;
|
||||
};
|
||||
return new ScheduleBuilder(triggerResource, {
|
||||
...options,
|
||||
schedule: { schedule },
|
||||
});
|
||||
}
|
||||
exports._scheduleWithOptions = _scheduleWithOptions;
|
||||
/**
|
||||
* The builder for scheduled functions, which are powered by
|
||||
* Google Pub/Sub and Cloud Scheduler. Describes the Cloud Scheduler
|
||||
* job that is deployed to trigger a scheduled function at the provided
|
||||
* frequency. For more information, see
|
||||
* [Schedule functions](/docs/functions/schedule-functions).
|
||||
*
|
||||
* Access via `functions.pubsub.schedule()`.
|
||||
*/
|
||||
class ScheduleBuilder {
|
||||
/** @hidden */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
retryConfig(config) {
|
||||
this.options.schedule.retryConfig = config;
|
||||
return this;
|
||||
}
|
||||
timeZone(timeZone) {
|
||||
this.options.schedule.timeZone = timeZone;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Event handler for scheduled functions. Triggered whenever the associated
|
||||
* scheduler job sends a Pub/Sub message.
|
||||
*
|
||||
* @param handler - Handler that fires whenever the associated
|
||||
* scheduler job sends a Pub/Sub message.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
onRun(handler) {
|
||||
const cloudFunction = (0, cloud_functions_1.makeCloudFunction)({
|
||||
contextOnlyHandler: handler,
|
||||
provider: exports.provider,
|
||||
service: exports.service,
|
||||
triggerResource: this.triggerResource,
|
||||
eventType: "topic.publish",
|
||||
options: this.options,
|
||||
labels: { "deployment-scheduled": "true" },
|
||||
});
|
||||
return cloudFunction;
|
||||
}
|
||||
}
|
||||
exports.ScheduleBuilder = ScheduleBuilder;
|
||||
/**
|
||||
* Interface representing a Google Cloud Pub/Sub message.
|
||||
*
|
||||
* @param data - Payload of a Pub/Sub message.
|
||||
*/
|
||||
class Message {
|
||||
constructor(data) {
|
||||
[this.data, this.attributes, this._json] = [data.data, data.attributes || {}, data.json];
|
||||
}
|
||||
/**
|
||||
* The JSON data payload of this message object, if any.
|
||||
*/
|
||||
get json() {
|
||||
if (typeof this._json === "undefined") {
|
||||
this._json = JSON.parse(Buffer.from(this.data, "base64").toString("utf8"));
|
||||
}
|
||||
return this._json;
|
||||
}
|
||||
/**
|
||||
* Returns a JSON-serializable representation of this object.
|
||||
*
|
||||
* @returns A JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON() {
|
||||
return {
|
||||
data: this.data,
|
||||
attributes: this.attributes,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.Message = Message;
|
||||
71
node_modules/firebase-functions/lib/v1/providers/remoteConfig.d.ts
generated
vendored
Normal file
71
node_modules/firebase-functions/lib/v1/providers/remoteConfig.d.ts
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
/**
|
||||
* Registers a function that triggers on Firebase Remote Config template
|
||||
* update events.
|
||||
*
|
||||
* @param handler A function that takes the updated Remote Config
|
||||
* template version metadata as an argument.
|
||||
*
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onUpdate(handler: (version: TemplateVersion, context: EventContext) => PromiseLike<any> | any): CloudFunction<TemplateVersion>;
|
||||
/** Builder used to create Cloud Functions for Remote Config. */
|
||||
export declare class UpdateBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/**
|
||||
* Handle all updates (including rollbacks) that affect a Remote Config
|
||||
* project.
|
||||
* @param handler A function that takes the updated Remote Config template
|
||||
* version metadata as an argument.
|
||||
*/
|
||||
onUpdate(handler: (version: TemplateVersion, context: EventContext) => PromiseLike<any> | any): CloudFunction<TemplateVersion>;
|
||||
}
|
||||
/**
|
||||
* An interface representing a Remote Config template version metadata object
|
||||
* emitted when a project is updated.
|
||||
*/
|
||||
export interface TemplateVersion {
|
||||
/** The version number of the updated Remote Config template. */
|
||||
versionNumber: number;
|
||||
/** When the template was updated in format (ISO8601 timestamp). */
|
||||
updateTime: string;
|
||||
/**
|
||||
* Metadata about the account that performed the update, of
|
||||
* type [`RemoteConfigUser`](/docs/reference/remote-config/rest/v1/Version#remoteconfiguser).
|
||||
*/
|
||||
updateUser: RemoteConfigUser;
|
||||
/** A description associated with this Remote Config template version. */
|
||||
description: string;
|
||||
/**
|
||||
* The origin of the caller - either the Firebase console or the Remote Config
|
||||
* REST API. See [`RemoteConfigUpdateOrigin`](/docs/reference/remote-config/rest/v1/Version#remoteconfigupdateorigin)
|
||||
* for valid values.
|
||||
*/
|
||||
updateOrigin: string;
|
||||
/**
|
||||
* The type of update action that was performed, whether forced,
|
||||
* incremental, or a rollback operation. See
|
||||
* [`RemoteConfigUpdateType`](/docs/reference/remote-config/rest/v1/Version#remoteconfigupdatetype)
|
||||
* for valid values.
|
||||
*/
|
||||
updateType: string;
|
||||
/**
|
||||
* The version number of the Remote Config template that this update rolled back to.
|
||||
* Only applies if this update was a rollback.
|
||||
*/
|
||||
rollbackSource?: number;
|
||||
}
|
||||
/**
|
||||
* An interface representing metadata for a Remote Config account
|
||||
* that performed the update. Contains the same fields as
|
||||
* [`RemoteConfigUser`](/docs/reference/remote-config/rest/v1/Version#remoteconfiguser).
|
||||
*/
|
||||
export interface RemoteConfigUser {
|
||||
/** Name of the Remote Config account that performed the update. */
|
||||
name?: string;
|
||||
/** Email address of the Remote Config account that performed the update. */
|
||||
email: string;
|
||||
/** Image URL of the Remote Config account that performed the update. */
|
||||
imageUrl?: string;
|
||||
}
|
||||
78
node_modules/firebase-functions/lib/v1/providers/remoteConfig.js
generated
vendored
Normal file
78
node_modules/firebase-functions/lib/v1/providers/remoteConfig.js
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2018 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the 'Software'), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UpdateBuilder = exports._onUpdateWithOptions = exports.onUpdate = exports.service = exports.provider = void 0;
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.firebase.remoteconfig";
|
||||
/** @internal */
|
||||
exports.service = "firebaseremoteconfig.googleapis.com";
|
||||
/**
|
||||
* Registers a function that triggers on Firebase Remote Config template
|
||||
* update events.
|
||||
*
|
||||
* @param handler A function that takes the updated Remote Config
|
||||
* template version metadata as an argument.
|
||||
*
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onUpdate(handler) {
|
||||
return _onUpdateWithOptions(handler, {});
|
||||
}
|
||||
exports.onUpdate = onUpdate;
|
||||
/** @internal */
|
||||
function _onUpdateWithOptions(handler, options) {
|
||||
const triggerResource = () => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
return `projects/${process.env.GCLOUD_PROJECT}`;
|
||||
};
|
||||
return new UpdateBuilder(triggerResource, options).onUpdate(handler);
|
||||
}
|
||||
exports._onUpdateWithOptions = _onUpdateWithOptions;
|
||||
/** Builder used to create Cloud Functions for Remote Config. */
|
||||
class UpdateBuilder {
|
||||
/** @internal */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Handle all updates (including rollbacks) that affect a Remote Config
|
||||
* project.
|
||||
* @param handler A function that takes the updated Remote Config template
|
||||
* version metadata as an argument.
|
||||
*/
|
||||
onUpdate(handler) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
service: exports.service,
|
||||
triggerResource: this.triggerResource,
|
||||
eventType: "update",
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.UpdateBuilder = UpdateBuilder;
|
||||
220
node_modules/firebase-functions/lib/v1/providers/storage.d.ts
generated
vendored
Normal file
220
node_modules/firebase-functions/lib/v1/providers/storage.d.ts
generated
vendored
Normal file
@@ -0,0 +1,220 @@
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
/**
|
||||
* Registers a Cloud Function scoped to a specific storage bucket.
|
||||
*
|
||||
* @param bucket Name of the bucket to which this Cloud Function is
|
||||
* scoped.
|
||||
*
|
||||
* @returns Storage bucket builder interface.
|
||||
*/
|
||||
export declare function bucket(bucket?: string): BucketBuilder;
|
||||
/**
|
||||
* Registers a Cloud Function scoped to the default storage bucket for the
|
||||
* project.
|
||||
*
|
||||
* @returns Storage object builder interface.
|
||||
*/
|
||||
export declare function object(): ObjectBuilder;
|
||||
/**
|
||||
* The Google Cloud Storage bucket builder interface.
|
||||
*
|
||||
* Access via `functions.storage.bucket()`.
|
||||
*/
|
||||
export declare class BucketBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage change occurs.
|
||||
*
|
||||
* @returns Storage object builder interface scoped to the specified storage
|
||||
* bucket.
|
||||
*/
|
||||
object(): ObjectBuilder;
|
||||
}
|
||||
/**
|
||||
* The Google Cloud Storage object builder interface.
|
||||
*
|
||||
* Access via `functions.storage.object()`.
|
||||
*/
|
||||
export declare class ObjectBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/**
|
||||
* Event handler sent only when a bucket has enabled object versioning.
|
||||
* This event indicates that the live version of an object has become an
|
||||
* archived version, either because it was archived or because it was
|
||||
* overwritten by the upload of an object of the same name.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* archival occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onArchive(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage deletion occurs.
|
||||
*
|
||||
* Sent when an object has been permanently deleted. This includes objects
|
||||
* that are overwritten or are deleted as part of the bucket's lifecycle
|
||||
* configuration. For buckets with object versioning enabled, this is not
|
||||
* sent when an object is archived, even if archival occurs
|
||||
* via the `storage.objects.delete` method.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* deletion occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onDelete(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage object
|
||||
* creation occurs.
|
||||
*
|
||||
* Sent when a new object (or a new generation of an existing object)
|
||||
* is successfully created in the bucket. This includes copying or rewriting
|
||||
* an existing object. A failed upload does not trigger this event.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* object creation occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onFinalize(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
|
||||
/**
|
||||
* Event handler which fires every time the metadata of an existing object
|
||||
* changes.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* metadata update occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onMetadataUpdate(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
|
||||
/** @hidden */
|
||||
private onOperation;
|
||||
}
|
||||
/** Interface representing a Google Google Cloud Storage object metadata object. */
|
||||
export interface ObjectMetadata {
|
||||
/** The kind of the object, which is always `storage#object`. */
|
||||
kind: string;
|
||||
/**
|
||||
* The ID of the object, including the bucket name, object name, and
|
||||
* generation number.
|
||||
*/
|
||||
id: string;
|
||||
/** Storage bucket that contains the object. */
|
||||
bucket: string;
|
||||
/** Storage class of the object. */
|
||||
storageClass: string;
|
||||
/**
|
||||
* The value of the `Content-Length` header, used to determine the length of
|
||||
* the object data in bytes.
|
||||
*/
|
||||
size: string;
|
||||
/** The creation time of the object in RFC 3339 format. */
|
||||
timeCreated: string;
|
||||
/**
|
||||
* The modification time of the object metadata in RFC 3339 format.
|
||||
*/
|
||||
updated: string;
|
||||
/** Link to access the object, assuming you have sufficient permissions. */
|
||||
selfLink?: string;
|
||||
/** The object's name. */
|
||||
name?: string;
|
||||
/**
|
||||
* Generation version number that changes each time the object is
|
||||
* overwritten.
|
||||
*/
|
||||
generation?: string;
|
||||
/** The object's content type, also known as the MIME type. */
|
||||
contentType?: string;
|
||||
/**
|
||||
* Meta-generation version number that changes each time the object's metadata
|
||||
* is updated.
|
||||
*/
|
||||
metageneration?: string;
|
||||
/**
|
||||
* The deletion time of the object in RFC 3339 format. Returned
|
||||
* only if this version of the object has been deleted.
|
||||
*/
|
||||
timeDeleted?: string;
|
||||
timeStorageClassUpdated?: string;
|
||||
/**
|
||||
* MD5 hash for the object. All Google Cloud Storage objects
|
||||
* have a CRC32C hash or MD5 hash.
|
||||
*/
|
||||
md5Hash?: string;
|
||||
/** Media download link. */
|
||||
mediaLink?: string;
|
||||
/**
|
||||
* Content-Encoding to indicate that an object is compressed
|
||||
* (for example, with gzip compression) while maintaining its Content-Type.
|
||||
*/
|
||||
contentEncoding?: string;
|
||||
/**
|
||||
* The value of the `Content-Disposition` header, used to specify presentation
|
||||
* information about the data being transmitted.
|
||||
*/
|
||||
contentDisposition?: string;
|
||||
/** ISO 639-1 language code of the content. */
|
||||
contentLanguage?: string;
|
||||
/**
|
||||
* The value of the `Cache-Control` header, used to determine whether Internet
|
||||
* caches are allowed to cache public data for an object.
|
||||
*/
|
||||
cacheControl?: string;
|
||||
/** User-provided metadata. */
|
||||
metadata?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
acl?: [
|
||||
{
|
||||
kind?: string;
|
||||
id?: string;
|
||||
selfLink?: string;
|
||||
bucket?: string;
|
||||
object?: string;
|
||||
generation?: string;
|
||||
entity?: string;
|
||||
role?: string;
|
||||
email?: string;
|
||||
entityId?: string;
|
||||
domain?: string;
|
||||
projectTeam?: {
|
||||
projectNumber?: string;
|
||||
team?: string;
|
||||
};
|
||||
etag?: string;
|
||||
}
|
||||
];
|
||||
owner?: {
|
||||
entity?: string;
|
||||
entityId?: string;
|
||||
};
|
||||
/**
|
||||
* The object's CRC32C hash. All Google Cloud Storage objects
|
||||
* have a CRC32C hash or MD5 hash.
|
||||
*/
|
||||
crc32c?: string;
|
||||
/**
|
||||
* Specifies the number of originally uploaded objects from which
|
||||
* a composite object was created.
|
||||
*/
|
||||
componentCount?: string;
|
||||
etag?: string;
|
||||
/**
|
||||
* Customer-supplied encryption key.
|
||||
*
|
||||
* This object contains the following properties:
|
||||
* * `encryptionAlgorithm` (`string|undefined`): The encryption algorithm that
|
||||
* was used. Always contains the value `AES256`.
|
||||
* * `keySha256` (`string|undefined`): An RFC 4648 base64-encoded string of the
|
||||
* SHA256 hash of your encryption key. You can use this SHA256 hash to
|
||||
* uniquely identify the AES-256 encryption key required to decrypt the
|
||||
* object, which you must store securely.
|
||||
*/
|
||||
customerEncryption?: {
|
||||
encryptionAlgorithm?: string;
|
||||
keySha256?: string;
|
||||
};
|
||||
}
|
||||
178
node_modules/firebase-functions/lib/v1/providers/storage.js
generated
vendored
Normal file
178
node_modules/firebase-functions/lib/v1/providers/storage.js
generated
vendored
Normal file
@@ -0,0 +1,178 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2017 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ObjectBuilder = exports.BucketBuilder = exports._objectWithOptions = exports._bucketWithOptions = exports.object = exports.bucket = exports.service = exports.provider = void 0;
|
||||
const config_1 = require("../../common/config");
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.provider = "google.storage";
|
||||
/** @internal */
|
||||
exports.service = "storage.googleapis.com";
|
||||
/**
|
||||
* Registers a Cloud Function scoped to a specific storage bucket.
|
||||
*
|
||||
* @param bucket Name of the bucket to which this Cloud Function is
|
||||
* scoped.
|
||||
*
|
||||
* @returns Storage bucket builder interface.
|
||||
*/
|
||||
function bucket(bucket) {
|
||||
return _bucketWithOptions({}, bucket);
|
||||
}
|
||||
exports.bucket = bucket;
|
||||
/**
|
||||
* Registers a Cloud Function scoped to the default storage bucket for the
|
||||
* project.
|
||||
*
|
||||
* @returns Storage object builder interface.
|
||||
*/
|
||||
function object() {
|
||||
return _objectWithOptions({});
|
||||
}
|
||||
exports.object = object;
|
||||
/** @internal */
|
||||
function _bucketWithOptions(options, bucket) {
|
||||
const resourceGetter = () => {
|
||||
bucket = bucket || (0, config_1.firebaseConfig)().storageBucket;
|
||||
if (!bucket) {
|
||||
throw new Error("Missing bucket name. If you are unit testing, please provide a bucket name" +
|
||||
" through `functions.storage.bucket(bucketName)`, or set process.env.FIREBASE_CONFIG.");
|
||||
}
|
||||
if (!/^[a-z\d][a-z\d\\._-]{1,230}[a-z\d]$/.test(bucket)) {
|
||||
throw new Error(`Invalid bucket name ${bucket}`);
|
||||
}
|
||||
return `projects/_/buckets/${bucket}`;
|
||||
};
|
||||
return new BucketBuilder(resourceGetter, options);
|
||||
}
|
||||
exports._bucketWithOptions = _bucketWithOptions;
|
||||
/** @internal */
|
||||
function _objectWithOptions(options) {
|
||||
return _bucketWithOptions(options).object();
|
||||
}
|
||||
exports._objectWithOptions = _objectWithOptions;
|
||||
/**
|
||||
* The Google Cloud Storage bucket builder interface.
|
||||
*
|
||||
* Access via `functions.storage.bucket()`.
|
||||
*/
|
||||
class BucketBuilder {
|
||||
/** @internal */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage change occurs.
|
||||
*
|
||||
* @returns Storage object builder interface scoped to the specified storage
|
||||
* bucket.
|
||||
*/
|
||||
object() {
|
||||
return new ObjectBuilder(this.triggerResource, this.options);
|
||||
}
|
||||
}
|
||||
exports.BucketBuilder = BucketBuilder;
|
||||
/**
|
||||
* The Google Cloud Storage object builder interface.
|
||||
*
|
||||
* Access via `functions.storage.object()`.
|
||||
*/
|
||||
class ObjectBuilder {
|
||||
/** @internal */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* Event handler sent only when a bucket has enabled object versioning.
|
||||
* This event indicates that the live version of an object has become an
|
||||
* archived version, either because it was archived or because it was
|
||||
* overwritten by the upload of an object of the same name.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* archival occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onArchive(handler) {
|
||||
return this.onOperation(handler, "object.archive");
|
||||
}
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage deletion occurs.
|
||||
*
|
||||
* Sent when an object has been permanently deleted. This includes objects
|
||||
* that are overwritten or are deleted as part of the bucket's lifecycle
|
||||
* configuration. For buckets with object versioning enabled, this is not
|
||||
* sent when an object is archived, even if archival occurs
|
||||
* via the `storage.objects.delete` method.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* deletion occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onDelete(handler) {
|
||||
return this.onOperation(handler, "object.delete");
|
||||
}
|
||||
/**
|
||||
* Event handler which fires every time a Google Cloud Storage object
|
||||
* creation occurs.
|
||||
*
|
||||
* Sent when a new object (or a new generation of an existing object)
|
||||
* is successfully created in the bucket. This includes copying or rewriting
|
||||
* an existing object. A failed upload does not trigger this event.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* object creation occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onFinalize(handler) {
|
||||
return this.onOperation(handler, "object.finalize");
|
||||
}
|
||||
/**
|
||||
* Event handler which fires every time the metadata of an existing object
|
||||
* changes.
|
||||
*
|
||||
* @param handler Event handler which is run every time a Google Cloud Storage
|
||||
* metadata update occurs.
|
||||
*
|
||||
* @returns A function which you can export and deploy.
|
||||
*/
|
||||
onMetadataUpdate(handler) {
|
||||
return this.onOperation(handler, "object.metadataUpdate");
|
||||
}
|
||||
/** @hidden */
|
||||
onOperation(handler, eventType) {
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
handler,
|
||||
provider: exports.provider,
|
||||
service: exports.service,
|
||||
eventType,
|
||||
triggerResource: this.triggerResource,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.ObjectBuilder = ObjectBuilder;
|
||||
61
node_modules/firebase-functions/lib/v1/providers/tasks.d.ts
generated
vendored
Normal file
61
node_modules/firebase-functions/lib/v1/providers/tasks.d.ts
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import * as express from "express";
|
||||
import { Request } from "../../common/providers/https";
|
||||
import { RateLimits, RetryConfig, TaskContext } from "../../common/providers/tasks";
|
||||
import { ManifestEndpoint, ManifestRequiredAPI } from "../../runtime/manifest";
|
||||
export { RetryConfig, RateLimits, TaskContext };
|
||||
/**
|
||||
* Options for configuring the task queue to listen to.
|
||||
*/
|
||||
export interface TaskQueueOptions {
|
||||
/** How a task should be retried in the event of a non-2xx return. */
|
||||
retryConfig?: RetryConfig;
|
||||
/** How congestion control should be applied to the function. */
|
||||
rateLimits?: RateLimits;
|
||||
/**
|
||||
* Who can enqueue tasks for this function.
|
||||
* If left unspecified, only service accounts which have
|
||||
* `roles/cloudtasks.enqueuer` and `roles/cloudfunctions.invoker`
|
||||
* will have permissions.
|
||||
*/
|
||||
invoker?: "private" | string | string[];
|
||||
}
|
||||
/**
|
||||
* A handler for tasks.
|
||||
*/
|
||||
export interface TaskQueueFunction {
|
||||
(req: Request, res: express.Response): Promise<void>;
|
||||
/** @alpha */
|
||||
__trigger: unknown;
|
||||
/** @alpha */
|
||||
__endpoint: ManifestEndpoint;
|
||||
/** @alpha */
|
||||
__requiredAPIs?: ManifestRequiredAPI[];
|
||||
/**
|
||||
* The callback passed to the `TaskQueueFunction` constructor.
|
||||
* @param data - The body enqueued into a task queue.
|
||||
* @param context - The request context of the enqueued task
|
||||
* @returns Any return value. Google Cloud Functions will await any promise
|
||||
* before shutting down your function. Resolved return values
|
||||
* are only used for unit testing purposes.
|
||||
*/
|
||||
run(data: any, context: TaskContext): void | Promise<void>;
|
||||
}
|
||||
/**
|
||||
* Builder for creating a `TaskQueueFunction`.
|
||||
*/
|
||||
export declare class TaskQueueBuilder {
|
||||
private readonly tqOpts?;
|
||||
private readonly depOpts?;
|
||||
/**
|
||||
* Creates a handler for tasks sent to a Google Cloud Tasks queue.
|
||||
* @param handler - A callback to handle task requests.
|
||||
* @returns A function you can export and deploy.
|
||||
*/
|
||||
onDispatch(handler: (data: any, context: TaskContext) => void | Promise<void>): TaskQueueFunction;
|
||||
}
|
||||
/**
|
||||
* Declares a function that can handle tasks enqueued using the Firebase Admin SDK.
|
||||
* @param options - Configuration for the Task Queue that feeds into this function.
|
||||
* Omitting options will configure a Task Queue with default settings.
|
||||
*/
|
||||
export declare function taskQueue(options?: TaskQueueOptions): TaskQueueBuilder;
|
||||
85
node_modules/firebase-functions/lib/v1/providers/tasks.js
generated
vendored
Normal file
85
node_modules/firebase-functions/lib/v1/providers/tasks.js
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.taskQueue = exports.TaskQueueBuilder = void 0;
|
||||
const encoding_1 = require("../../common/encoding");
|
||||
const tasks_1 = require("../../common/providers/tasks");
|
||||
const manifest_1 = require("../../runtime/manifest");
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/**
|
||||
* Builder for creating a `TaskQueueFunction`.
|
||||
*/
|
||||
class TaskQueueBuilder {
|
||||
/** @internal */
|
||||
constructor(tqOpts, depOpts) {
|
||||
this.tqOpts = tqOpts;
|
||||
this.depOpts = depOpts;
|
||||
}
|
||||
/**
|
||||
* Creates a handler for tasks sent to a Google Cloud Tasks queue.
|
||||
* @param handler - A callback to handle task requests.
|
||||
* @returns A function you can export and deploy.
|
||||
*/
|
||||
onDispatch(handler) {
|
||||
var _a, _b;
|
||||
// onEnqueueHandler sniffs the function length of the passed-in callback
|
||||
// and the user could have only tried to listen to data. Wrap their handler
|
||||
// in another handler to avoid accidentally triggering the v2 API
|
||||
const fixedLen = (data, context) => handler(data, context);
|
||||
const func = (0, tasks_1.onDispatchHandler)(fixedLen);
|
||||
func.__trigger = {
|
||||
...(0, cloud_functions_1.optionsToTrigger)(this.depOpts || {}),
|
||||
taskQueueTrigger: {},
|
||||
};
|
||||
(0, encoding_1.copyIfPresent)(func.__trigger.taskQueueTrigger, this.tqOpts, "retryConfig");
|
||||
(0, encoding_1.copyIfPresent)(func.__trigger.taskQueueTrigger, this.tqOpts, "rateLimits");
|
||||
(0, encoding_1.convertIfPresent)(func.__trigger.taskQueueTrigger, this.tqOpts, "invoker", "invoker", encoding_1.convertInvoker);
|
||||
func.__endpoint = {
|
||||
platform: "gcfv1",
|
||||
...(0, manifest_1.initV1Endpoint)(this.depOpts),
|
||||
...(0, cloud_functions_1.optionsToEndpoint)(this.depOpts),
|
||||
taskQueueTrigger: (0, manifest_1.initTaskQueueTrigger)(this.depOpts),
|
||||
};
|
||||
(0, encoding_1.copyIfPresent)(func.__endpoint.taskQueueTrigger.retryConfig, ((_a = this.tqOpts) === null || _a === void 0 ? void 0 : _a.retryConfig) || {}, "maxAttempts", "maxBackoffSeconds", "maxDoublings", "maxRetrySeconds", "minBackoffSeconds");
|
||||
(0, encoding_1.copyIfPresent)(func.__endpoint.taskQueueTrigger.rateLimits, ((_b = this.tqOpts) === null || _b === void 0 ? void 0 : _b.rateLimits) || {}, "maxConcurrentDispatches", "maxDispatchesPerSecond");
|
||||
(0, encoding_1.convertIfPresent)(func.__endpoint.taskQueueTrigger, this.tqOpts, "invoker", "invoker", encoding_1.convertInvoker);
|
||||
func.__requiredAPIs = [
|
||||
{
|
||||
api: "cloudtasks.googleapis.com",
|
||||
reason: "Needed for task queue functions",
|
||||
},
|
||||
];
|
||||
func.run = handler;
|
||||
return func;
|
||||
}
|
||||
}
|
||||
exports.TaskQueueBuilder = TaskQueueBuilder;
|
||||
/**
|
||||
* Declares a function that can handle tasks enqueued using the Firebase Admin SDK.
|
||||
* @param options - Configuration for the Task Queue that feeds into this function.
|
||||
* Omitting options will configure a Task Queue with default settings.
|
||||
*/
|
||||
function taskQueue(options) {
|
||||
return new TaskQueueBuilder(options);
|
||||
}
|
||||
exports.taskQueue = taskQueue;
|
||||
184
node_modules/firebase-functions/lib/v1/providers/testLab.d.ts
generated
vendored
Normal file
184
node_modules/firebase-functions/lib/v1/providers/testLab.d.ts
generated
vendored
Normal file
@@ -0,0 +1,184 @@
|
||||
import { CloudFunction, EventContext } from "../cloud-functions";
|
||||
/** Handle events related to Test Lab test matrices. */
|
||||
export declare function testMatrix(): TestMatrixBuilder;
|
||||
/** Builder used to create Cloud Functions for Test Lab test matrices events. */
|
||||
export declare class TestMatrixBuilder {
|
||||
private triggerResource;
|
||||
private options;
|
||||
/** Handle a TestMatrix that reached a final test state. */
|
||||
onComplete(handler: (testMatrix: TestMatrix, context: EventContext) => PromiseLike<any> | any): CloudFunction<TestMatrix>;
|
||||
}
|
||||
/** TestMatrix captures details about a test run. */
|
||||
export declare class TestMatrix {
|
||||
/** Unique id set by the service. */
|
||||
testMatrixId: string;
|
||||
/** When this test matrix was initially created (ISO8601 timestamp). */
|
||||
createTime: string;
|
||||
/** Indicates the current progress of the test matrix */
|
||||
state: TestState;
|
||||
/**
|
||||
* The overall outcome of the test matrix run. Only set when the test matrix
|
||||
* state is FINISHED.
|
||||
*/
|
||||
outcomeSummary?: OutcomeSummary;
|
||||
/** For 'INVALID' matrices only, describes why the matrix is invalid. */
|
||||
invalidMatrixDetails?: InvalidMatrixDetails;
|
||||
/** Where the results for the matrix are located. */
|
||||
resultStorage: ResultStorage;
|
||||
/** Information about the client which invoked the test. */
|
||||
clientInfo: ClientInfo;
|
||||
}
|
||||
/** Information about the client which invoked the test. */
|
||||
export declare class ClientInfo {
|
||||
/** Client name, e.g. 'gcloud'. */
|
||||
name: string;
|
||||
/** Map of detailed information about the client which invoked the test. */
|
||||
details: {
|
||||
[key: string]: string;
|
||||
};
|
||||
}
|
||||
/** Locations where the test results are stored. */
|
||||
export declare class ResultStorage {
|
||||
/** A storage location within Google Cloud Storage (GCS) for the test artifacts. */
|
||||
gcsPath?: string;
|
||||
/** Id of the ToolResults History containing these results. */
|
||||
toolResultsHistoryId?: string;
|
||||
/**
|
||||
* Id of the ToolResults execution that the detailed TestMatrix results are
|
||||
* written to.
|
||||
*/
|
||||
toolResultsExecutionId?: string;
|
||||
/** URL to test results in Firebase Console. */
|
||||
resultsUrl?: string;
|
||||
}
|
||||
/**
|
||||
* The detailed reason that a Matrix was deemed INVALID.
|
||||
*
|
||||
* @remarks
|
||||
* Possible values:
|
||||
*
|
||||
* - `DETAILS_UNAVAILABLE`: The matrix is INVALID, but there are no further details available.
|
||||
*
|
||||
* - `MALFORMED_APK`: The input app APK could not be parsed.
|
||||
*
|
||||
* - `MALFORMED_TEST_APK`: The input test APK could not be parsed.
|
||||
*
|
||||
* - `NO_MANIFEST`: The AndroidManifest.xml could not be found.
|
||||
*
|
||||
* - `NO_PACKAGE_NAME`: The APK manifest does not declare a package name.
|
||||
*
|
||||
* - `INVALID_PACKAGE_NAME`: The APK application ID is invalid.
|
||||
*
|
||||
* - `TEST_SAME_AS_APP`: The test package and app package are the same.
|
||||
*
|
||||
* - `NO_INSTRUMENTATION`: The test apk does not declare an instrumentation.
|
||||
*
|
||||
* - `NO_SIGNATURE`: The input app apk does not have a signature.
|
||||
*
|
||||
* - `INSTRUMENTATION_ORCHESTRATOR_INCOMPATIBLE`: The test runner class specified by
|
||||
* user or in the test APK`s manifest file is not compatible with Android Test Orchestrator.
|
||||
*
|
||||
* - `NO_TEST_RUNNER_CLASS`: The test APK does not contain the test runner class
|
||||
* specified by user or in the manifest file.
|
||||
*
|
||||
* - `NO_LAUNCHER_ACTIVITY`: A main launcher activity could not be found.
|
||||
*
|
||||
* - `FORBIDDEN_PERMISSIONS`: The app declares one or more permissions that are
|
||||
* not allowed.
|
||||
*
|
||||
* - `INVALID_ROBO_DIRECTIVES`: There is a conflict in the provided
|
||||
* robo_directives.
|
||||
*
|
||||
* - `INVALID_RESOURCE_NAME`: There is at least one invalid resource name in the
|
||||
* provided robo directives.
|
||||
*
|
||||
* - `INVALID_DIRECTIVE_ACTION`: Invalid definition of action in the robo
|
||||
* directives, e.g. a click or ignore action includes an input text field.
|
||||
*
|
||||
* - `TEST_LOOP_INTENT_FILTER_NOT_FOUND`: There is no test loop intent filter,
|
||||
* or the one that is given is not formatted correctly.
|
||||
*
|
||||
* - `SCENARIO_LABEL_NOT_DECLARED`: The request contains a scenario label that
|
||||
* was not declared in the manifest.
|
||||
*
|
||||
* - `SCENARIO_LABEL_MALFORMED`: There was an error when parsing a label value.
|
||||
*
|
||||
* - `SCENARIO_NOT_DECLARED`: The request contains a scenario number that was
|
||||
* not declared in the manifest.
|
||||
*
|
||||
* - `DEVICE_ADMIN_RECEIVER`: Device administrator applications are not allowed.
|
||||
*
|
||||
* - `MALFORMED_XC_TEST_ZIP`: The zipped XCTest was malformed. The zip did not ]
|
||||
* contain a single .xctestrun file and the contents of the
|
||||
* DerivedData/Build/Products directory.
|
||||
*
|
||||
* - `BUILT_FOR_IOS_SIMULATOR`: The zipped XCTest was built for the iOS
|
||||
* simulator rather than for a physical device.
|
||||
*
|
||||
* - `NO_TESTS_IN_XC_TEST_ZIP`: The .xctestrun file did not specify any test
|
||||
* targets.
|
||||
*
|
||||
* - `USE_DESTINATION_ARTIFACTS`: One or more of the test targets defined in the
|
||||
* .xctestrun file specifies "UseDestinationArtifacts", which is disallowed.
|
||||
*
|
||||
* - `TEST_NOT_APP_HOSTED`: XC tests which run on physical devices must have
|
||||
* "IsAppHostedTestBundle" == "true" in the xctestrun file.
|
||||
*
|
||||
* - `PLIST_CANNOT_BE_PARSED`: An Info.plist file in the XCTest zip could not be
|
||||
* parsed.
|
||||
*
|
||||
* - `NO_CODE_APK`: APK contains no code.
|
||||
*
|
||||
* - `INVALID_INPUT_APK`: Either the provided input APK path was malformed, the
|
||||
* APK file does not exist, or the user does not have permission to access the
|
||||
* APK file.
|
||||
*
|
||||
* - `INVALID_APK_PREVIEW_SDK`: APK is built for a preview SDK which is
|
||||
* unsupported.
|
||||
*/
|
||||
export type InvalidMatrixDetails = "DETAILS_UNAVAILABLE" | "MALFORMED_APK" | "MALFORMED_TEST_APK" | "NO_MANIFEST" | "NO_PACKAGE_NAME" | "INVALID_PACKAGE_NAME" | "TEST_SAME_AS_APP" | "NO_INSTRUMENTATION" | "NO_SIGNATURE" | "INSTRUMENTATION_ORCHESTRATOR_INCOMPATIBLE" | "NO_TEST_RUNNER_CLASS" | "NO_LAUNCHER_ACTIVITY" | "FORBIDDEN_PERMISSIONS" | "INVALID_ROBO_DIRECTIVES" | "INVALID_RESOURCE_NAME" | "INVALID_DIRECTIVE_ACTION" | "TEST_LOOP_INTENT_FILTER_NOT_FOUND" | "SCENARIO_LABEL_NOT_DECLARED" | "SCENARIO_LABEL_MALFORMED" | "SCENARIO_NOT_DECLARED" | "DEVICE_ADMIN_RECEIVER" | "MALFORMED_XC_TEST_ZIP" | "BUILT_FOR_IOS_SIMULATOR" | "NO_TESTS_IN_XC_TEST_ZIP" | "USE_DESTINATION_ARTIFACTS" | "TEST_NOT_APP_HOSTED" | "PLIST_CANNOT_BE_PARSED" | "NO_CODE_APK" | "INVALID_INPUT_APK" | "INVALID_APK_PREVIEW_SDK";
|
||||
/**
|
||||
* The state (i.e. progress) of a TestMatrix.
|
||||
*
|
||||
* @remarks
|
||||
* Possible values:
|
||||
*
|
||||
* - `VALIDATING`: The matrix is being validated.
|
||||
*
|
||||
* - `PENDING`: The matrix is waiting for resources to become available.
|
||||
*
|
||||
* - `FINISHED`: The matrix has terminated normally. This means that the matrix
|
||||
* level processing completed normally, but individual executions may be in an
|
||||
* ERROR state.
|
||||
*
|
||||
* - `ERROR`: The matrix has stopped because it encountered an infrastructure
|
||||
* failure.
|
||||
*
|
||||
* - `INVALID`: The matrix was not run because the provided inputs are not
|
||||
* valid. E.g. the input file is not of the expected type, or is
|
||||
* malformed/corrupt.
|
||||
*/
|
||||
export type TestState = "VALIDATING" | "PENDING" | "FINISHED" | "ERROR" | "INVALID";
|
||||
/**
|
||||
* Outcome summary for a finished TestMatrix.
|
||||
*
|
||||
* @remarks
|
||||
* Possible values:
|
||||
*
|
||||
* - `SUCCESS`: The test matrix run was successful, for instance:
|
||||
* - All the test cases passed.
|
||||
* - Robo did not detect a crash of the application under test.
|
||||
*
|
||||
* - `FAILURE`: The test run failed, for instance:
|
||||
* - One or more test cases failed.
|
||||
* - A test timed out.
|
||||
* - The application under test crashed.
|
||||
*
|
||||
* - `INCONCLUSIVE`: Something unexpected happened. The run should still be
|
||||
* considered unsuccessful but this is likely a transient problem and
|
||||
* re-running the test might be successful.
|
||||
*
|
||||
* - `SKIPPED`: All tests were skipped, for instance:
|
||||
* - All device configurations were incompatible.
|
||||
*/
|
||||
export type OutcomeSummary = "SUCCESS" | "FAILURE" | "INCONCLUSIVE" | "SKIPPED";
|
||||
108
node_modules/firebase-functions/lib/v1/providers/testLab.js
generated
vendored
Normal file
108
node_modules/firebase-functions/lib/v1/providers/testLab.js
generated
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2019 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the 'Software'), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultStorage = exports.ClientInfo = exports.TestMatrix = exports.TestMatrixBuilder = exports._testMatrixWithOpts = exports.testMatrix = exports.TEST_MATRIX_COMPLETE_EVENT_TYPE = exports.SERVICE = exports.PROVIDER = void 0;
|
||||
const cloud_functions_1 = require("../cloud-functions");
|
||||
/** @internal */
|
||||
exports.PROVIDER = "google.testing";
|
||||
/** @internal */
|
||||
exports.SERVICE = "testing.googleapis.com";
|
||||
/** @internal */
|
||||
exports.TEST_MATRIX_COMPLETE_EVENT_TYPE = "testMatrix.complete";
|
||||
/** Handle events related to Test Lab test matrices. */
|
||||
function testMatrix() {
|
||||
return _testMatrixWithOpts({});
|
||||
}
|
||||
exports.testMatrix = testMatrix;
|
||||
/** @internal */
|
||||
function _testMatrixWithOpts(opts) {
|
||||
return new TestMatrixBuilder(() => {
|
||||
if (!process.env.GCLOUD_PROJECT) {
|
||||
throw new Error("process.env.GCLOUD_PROJECT is not set.");
|
||||
}
|
||||
return "projects/" + process.env.GCLOUD_PROJECT + "/testMatrices/{matrix}";
|
||||
}, opts);
|
||||
}
|
||||
exports._testMatrixWithOpts = _testMatrixWithOpts;
|
||||
/** Builder used to create Cloud Functions for Test Lab test matrices events. */
|
||||
class TestMatrixBuilder {
|
||||
/** @internal */
|
||||
constructor(triggerResource, options) {
|
||||
this.triggerResource = triggerResource;
|
||||
this.options = options;
|
||||
}
|
||||
/** Handle a TestMatrix that reached a final test state. */
|
||||
onComplete(handler) {
|
||||
const dataConstructor = (raw) => {
|
||||
return new TestMatrix(raw.data);
|
||||
};
|
||||
return (0, cloud_functions_1.makeCloudFunction)({
|
||||
provider: exports.PROVIDER,
|
||||
eventType: exports.TEST_MATRIX_COMPLETE_EVENT_TYPE,
|
||||
triggerResource: this.triggerResource,
|
||||
service: exports.SERVICE,
|
||||
dataConstructor,
|
||||
handler,
|
||||
options: this.options,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.TestMatrixBuilder = TestMatrixBuilder;
|
||||
/** TestMatrix captures details about a test run. */
|
||||
class TestMatrix {
|
||||
/** @internal */
|
||||
constructor(data) {
|
||||
this.testMatrixId = data.testMatrixId;
|
||||
this.createTime = data.timestamp;
|
||||
this.state = data.state;
|
||||
this.outcomeSummary = data.outcomeSummary;
|
||||
this.invalidMatrixDetails = data.invalidMatrixDetails;
|
||||
this.resultStorage = new ResultStorage(data.resultStorage);
|
||||
this.clientInfo = new ClientInfo(data.clientInfo);
|
||||
}
|
||||
}
|
||||
exports.TestMatrix = TestMatrix;
|
||||
/** Information about the client which invoked the test. */
|
||||
class ClientInfo {
|
||||
/** @internal */
|
||||
constructor(data) {
|
||||
this.name = (data === null || data === void 0 ? void 0 : data.name) || "";
|
||||
this.details = {};
|
||||
for (const detail of (data === null || data === void 0 ? void 0 : data.clientInfoDetails) || []) {
|
||||
this.details[detail.key] = detail.value || "";
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.ClientInfo = ClientInfo;
|
||||
/** Locations where the test results are stored. */
|
||||
class ResultStorage {
|
||||
/** @internal */
|
||||
constructor(data) {
|
||||
var _a, _b, _c;
|
||||
this.gcsPath = (_a = data === null || data === void 0 ? void 0 : data.googleCloudStorage) === null || _a === void 0 ? void 0 : _a.gcsPath;
|
||||
this.toolResultsHistoryId = (_b = data === null || data === void 0 ? void 0 : data.toolResultsHistory) === null || _b === void 0 ? void 0 : _b.historyId;
|
||||
this.toolResultsExecutionId = (_c = data === null || data === void 0 ? void 0 : data.toolResultsExecution) === null || _c === void 0 ? void 0 : _c.executionId;
|
||||
this.resultsUrl = data === null || data === void 0 ? void 0 : data.resultsUrl;
|
||||
}
|
||||
}
|
||||
exports.ResultStorage = ResultStorage;
|
||||
54
node_modules/firebase-functions/lib/v2/core.d.ts
generated
vendored
Normal file
54
node_modules/firebase-functions/lib/v2/core.d.ts
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Core functionality of the Cloud Functions for Firebase 2nd gen SDK.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
import { Change } from "../common/change";
|
||||
import { ManifestEndpoint } from "../runtime/manifest";
|
||||
export { Change };
|
||||
export { ParamsOf } from "../common/params";
|
||||
export { onInit } from "../common/onInit";
|
||||
/**
|
||||
* A `CloudEventBase` is the base of a cross-platform format for encoding a serverless event.
|
||||
* For more information, see https://github.com/cloudevents/spec.
|
||||
* @typeParam T - The type of the event data.
|
||||
* @beta
|
||||
*/
|
||||
export interface CloudEvent<T> {
|
||||
/** Version of the CloudEvents spec for this event. */
|
||||
readonly specversion: "1.0";
|
||||
/** A globally unique ID for this event. */
|
||||
id: string;
|
||||
/** The resource that published this event. */
|
||||
source: string;
|
||||
/** The resource, provided by source, that this event relates to. */
|
||||
subject?: string;
|
||||
/** The type of event that this represents. */
|
||||
type: string;
|
||||
/** When this event occurred. */
|
||||
time: string;
|
||||
/** Information about this specific event. */
|
||||
data: T;
|
||||
}
|
||||
/**
|
||||
* A handler for CloudEvents.
|
||||
* @typeParam EventType - The kind of event this function handles.
|
||||
* Always a subclass of CloudEvent<>
|
||||
* @beta
|
||||
*/
|
||||
export interface CloudFunction<EventType extends CloudEvent<unknown>> {
|
||||
(raw: CloudEvent<unknown>): any | Promise<any>;
|
||||
/** @alpha */
|
||||
__trigger?: unknown;
|
||||
/** @alpha */
|
||||
__endpoint: ManifestEndpoint;
|
||||
/**
|
||||
* The callback passed to the `CloudFunction` constructor.
|
||||
* Use `run` to test a function.
|
||||
* @param event - The parsed event to handle.
|
||||
* @returns Any return value. Cloud Functions awaits any promise
|
||||
* before shutting down your function. Resolved return values
|
||||
* are only used for unit testing purposes.
|
||||
* @beta
|
||||
*/
|
||||
run(event: EventType): any | Promise<any>;
|
||||
}
|
||||
32
node_modules/firebase-functions/lib/v2/core.js
generated
vendored
Normal file
32
node_modules/firebase-functions/lib/v2/core.js
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.onInit = exports.Change = void 0;
|
||||
/**
|
||||
* Core functionality of the Cloud Functions for Firebase 2nd gen SDK.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
const change_1 = require("../common/change");
|
||||
Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
|
||||
var onInit_1 = require("../common/onInit");
|
||||
Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return onInit_1.onInit; } });
|
||||
31
node_modules/firebase-functions/lib/v2/index.d.ts
generated
vendored
Normal file
31
node_modules/firebase-functions/lib/v2/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The 2nd gen API for Cloud Functions for Firebase.
|
||||
* This SDK supports deep imports. For example, the namespace
|
||||
* `pubsub` is available at `firebase-functions/v2` or is directly importable
|
||||
* from `firebase-functions/v2/pubsub`.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
import * as logger from "../logger";
|
||||
import * as alerts from "./providers/alerts";
|
||||
import * as database from "./providers/database";
|
||||
import * as eventarc from "./providers/eventarc";
|
||||
import * as https from "./providers/https";
|
||||
import * as identity from "./providers/identity";
|
||||
import * as pubsub from "./providers/pubsub";
|
||||
import * as scheduler from "./providers/scheduler";
|
||||
import * as storage from "./providers/storage";
|
||||
import * as tasks from "./providers/tasks";
|
||||
import * as remoteConfig from "./providers/remoteConfig";
|
||||
import * as testLab from "./providers/testLab";
|
||||
import * as firestore from "./providers/firestore";
|
||||
export { alerts, database, storage, https, identity, pubsub, logger, tasks, eventarc, scheduler, remoteConfig, testLab, firestore, };
|
||||
export { setGlobalOptions, GlobalOptions, SupportedRegion, MemoryOption, VpcEgressSetting, IngressSetting, EventHandlerOptions, } from "./options";
|
||||
export { CloudFunction, CloudEvent, ParamsOf, onInit } from "./core";
|
||||
export { Change } from "../common/change";
|
||||
import * as params from "../params";
|
||||
export { params };
|
||||
export { config } from "../v1/config";
|
||||
import { setApp as setEmulatedAdminApp } from "../common/app";
|
||||
export declare const app: {
|
||||
setEmulatedAdminApp: typeof setEmulatedAdminApp;
|
||||
};
|
||||
73
node_modules/firebase-functions/lib/v2/index.js
generated
vendored
Normal file
73
node_modules/firebase-functions/lib/v2/index.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.app = exports.config = exports.params = exports.Change = exports.onInit = exports.setGlobalOptions = exports.firestore = exports.testLab = exports.remoteConfig = exports.scheduler = exports.eventarc = exports.tasks = exports.logger = exports.pubsub = exports.identity = exports.https = exports.storage = exports.database = exports.alerts = void 0;
|
||||
/**
|
||||
* The 2nd gen API for Cloud Functions for Firebase.
|
||||
* This SDK supports deep imports. For example, the namespace
|
||||
* `pubsub` is available at `firebase-functions/v2` or is directly importable
|
||||
* from `firebase-functions/v2/pubsub`.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
const logger = require("../logger");
|
||||
exports.logger = logger;
|
||||
const alerts = require("./providers/alerts");
|
||||
exports.alerts = alerts;
|
||||
const database = require("./providers/database");
|
||||
exports.database = database;
|
||||
const eventarc = require("./providers/eventarc");
|
||||
exports.eventarc = eventarc;
|
||||
const https = require("./providers/https");
|
||||
exports.https = https;
|
||||
const identity = require("./providers/identity");
|
||||
exports.identity = identity;
|
||||
const pubsub = require("./providers/pubsub");
|
||||
exports.pubsub = pubsub;
|
||||
const scheduler = require("./providers/scheduler");
|
||||
exports.scheduler = scheduler;
|
||||
const storage = require("./providers/storage");
|
||||
exports.storage = storage;
|
||||
const tasks = require("./providers/tasks");
|
||||
exports.tasks = tasks;
|
||||
const remoteConfig = require("./providers/remoteConfig");
|
||||
exports.remoteConfig = remoteConfig;
|
||||
const testLab = require("./providers/testLab");
|
||||
exports.testLab = testLab;
|
||||
const firestore = require("./providers/firestore");
|
||||
exports.firestore = firestore;
|
||||
var options_1 = require("./options");
|
||||
Object.defineProperty(exports, "setGlobalOptions", { enumerable: true, get: function () { return options_1.setGlobalOptions; } });
|
||||
var core_1 = require("./core");
|
||||
Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return core_1.onInit; } });
|
||||
var change_1 = require("../common/change");
|
||||
Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
|
||||
// NOTE: Equivalent to `export * as params from "../params"` but api-extractor doesn't support that syntax.
|
||||
const params = require("../params");
|
||||
exports.params = params;
|
||||
// NOTE: Required to support the Functions Emulator which monkey patches `functions.config()`
|
||||
// TODO(danielylee): Remove in next major release.
|
||||
var config_1 = require("../v1/config");
|
||||
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return config_1.config; } });
|
||||
// Required for v1 Emulator support.
|
||||
const app_1 = require("../common/app");
|
||||
exports.app = { setEmulatedAdminApp: app_1.setApp };
|
||||
159
node_modules/firebase-functions/lib/v2/options.d.ts
generated
vendored
Normal file
159
node_modules/firebase-functions/lib/v2/options.d.ts
generated
vendored
Normal file
@@ -0,0 +1,159 @@
|
||||
import { ResetValue } from "../common/options";
|
||||
import { Expression } from "../params";
|
||||
import { ParamSpec, SecretParam } from "../params/types";
|
||||
export { RESET_VALUE } from "../common/options";
|
||||
/**
|
||||
* List of all regions supported by Cloud Functions (2nd gen).
|
||||
*/
|
||||
export type SupportedRegion = "asia-east1" | "asia-northeast1" | "asia-northeast2" | "europe-north1" | "europe-west1" | "europe-west4" | "us-central1" | "us-east1" | "us-east4" | "us-west1" | "asia-east2" | "asia-northeast3" | "asia-southeast1" | "asia-southeast2" | "asia-south1" | "australia-southeast1" | "europe-central2" | "europe-west2" | "europe-west3" | "europe-west6" | "northamerica-northeast1" | "southamerica-east1" | "us-west2" | "us-west3" | "us-west4";
|
||||
/**
|
||||
* List of available memory options supported by Cloud Functions.
|
||||
*/
|
||||
export type MemoryOption = "128MiB" | "256MiB" | "512MiB" | "1GiB" | "2GiB" | "4GiB" | "8GiB" | "16GiB" | "32GiB";
|
||||
/**
|
||||
* List of available options for `VpcConnectorEgressSettings`.
|
||||
*/
|
||||
export type VpcEgressSetting = "PRIVATE_RANGES_ONLY" | "ALL_TRAFFIC";
|
||||
/**
|
||||
* List of available options for `IngressSettings`.
|
||||
*/
|
||||
export type IngressSetting = "ALLOW_ALL" | "ALLOW_INTERNAL_ONLY" | "ALLOW_INTERNAL_AND_GCLB";
|
||||
/**
|
||||
* `GlobalOptions` are options that can be set across an entire project.
|
||||
* These options are common to HTTPS and event handling functions.
|
||||
*/
|
||||
export interface GlobalOptions {
|
||||
/**
|
||||
* If true, do not deploy or emulate this function.
|
||||
*/
|
||||
omit?: boolean | Expression<boolean>;
|
||||
/**
|
||||
* Region where functions should be deployed.
|
||||
*/
|
||||
region?: SupportedRegion | string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Amount of memory to allocate to a function.
|
||||
*/
|
||||
memory?: MemoryOption | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Timeout for the function in seconds, possible values are 0 to 540.
|
||||
* HTTPS functions can specify a higher timeout.
|
||||
*
|
||||
* @remarks
|
||||
* The minimum timeout for a 2nd gen function is 1s. The maximum timeout for a
|
||||
* function depends on the type of function: Event handling functions have a
|
||||
* maximum timeout of 540s (9 minutes). HTTPS and callable functions have a
|
||||
* maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
|
||||
* timeout of 1,800s (30 minutes).
|
||||
*/
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Minimum number of actual instances to be running at a given time.
|
||||
*
|
||||
* @remarks
|
||||
* Instances are billed for memory allocation and 10% of CPU allocation
|
||||
* while idle.
|
||||
*/
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Max number of instances that can be running in parallel.
|
||||
*/
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Number of requests a function can serve at once.
|
||||
*
|
||||
* @remarks
|
||||
* Can be applied only to functions running on Cloud Functions (2nd gen)).
|
||||
* A value of null restores the default concurrency (80 when CPU >= 1, 1 otherwise).
|
||||
* Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
|
||||
* The maximum value for concurrency is 1,000.
|
||||
*/
|
||||
concurrency?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Fractional number of CPUs to allocate to a function.
|
||||
*
|
||||
* @remarks
|
||||
* Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
|
||||
* This is different from the defaults when using the gcloud utility and is different from
|
||||
* the fixed amount assigned in Cloud Functions (1st gen).
|
||||
* To revert to the CPU amounts used in gcloud or in Cloud Functions (1st gen), set this
|
||||
* to the value "gcf_gen1"
|
||||
*/
|
||||
cpu?: number | "gcf_gen1";
|
||||
/**
|
||||
* Connect a function to a specified VPC connector.
|
||||
*/
|
||||
vpcConnector?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Egress settings for VPC connector.
|
||||
*/
|
||||
vpcConnectorEgressSettings?: VpcEgressSetting | ResetValue;
|
||||
/**
|
||||
* Specific service account for the function to run as.
|
||||
*/
|
||||
serviceAccount?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Ingress settings which control where this function can be called from.
|
||||
*/
|
||||
ingressSettings?: IngressSetting | ResetValue;
|
||||
/**
|
||||
* Invoker to set access control on HTTPS functions.
|
||||
*/
|
||||
invoker?: "public" | "private" | string | string[];
|
||||
/**
|
||||
* User labels to set on the function.
|
||||
*/
|
||||
labels?: Record<string, string>;
|
||||
secrets?: (string | SecretParam)[];
|
||||
/**
|
||||
* Determines whether Firebase App Check is enforced. Defaults to false.
|
||||
*
|
||||
* @remarks
|
||||
* When true, requests with invalid tokens autorespond with a 401
|
||||
* (Unauthorized) error.
|
||||
* When false, requests with invalid tokens set `event.app` to `undefined`.
|
||||
*/
|
||||
enforceAppCheck?: boolean;
|
||||
/**
|
||||
* Controls whether function configuration modified outside of function source is preserved. Defaults to false.
|
||||
*
|
||||
* @remarks
|
||||
* When setting configuration available in an underlying platform that is not yet available in the Firebase SDK
|
||||
* for Cloud Functions, we recommend setting `preserveExternalChanges` to `true`. Otherwise, when Google releases
|
||||
* a new version of the SDK with support for the missing configuration, your function's manually configured setting
|
||||
* may inadvertently be wiped out.
|
||||
*/
|
||||
preserveExternalChanges?: boolean;
|
||||
}
|
||||
/**
|
||||
* Sets default options for all functions written using the 2nd gen SDK.
|
||||
* @param options Options to set as default
|
||||
*/
|
||||
export declare function setGlobalOptions(options: GlobalOptions): void;
|
||||
/**
|
||||
* Additional fields that can be set on any event-handling function.
|
||||
*/
|
||||
export interface EventHandlerOptions extends Omit<GlobalOptions, "enforceAppCheck"> {
|
||||
/** Type of the event. Valid values are TODO */
|
||||
eventType?: string;
|
||||
/** TODO */
|
||||
eventFilters?: Record<string, string | Expression<string>>;
|
||||
/** TODO */
|
||||
eventFilterPathPatterns?: Record<string, string | Expression<string>>;
|
||||
/** Whether failed executions should be delivered again. */
|
||||
retry?: boolean | Expression<boolean> | ResetValue;
|
||||
/** Region of the EventArc trigger. */
|
||||
region?: string | Expression<string> | ResetValue;
|
||||
/** The service account that EventArc should use to invoke this function. Requires the P4SA to have ActAs permission on this service account. */
|
||||
serviceAccount?: string | Expression<string> | ResetValue;
|
||||
/** The name of the channel where the function receives events. */
|
||||
channel?: string;
|
||||
}
|
||||
/**
|
||||
* @hidden
|
||||
* @alpha
|
||||
*/
|
||||
export declare function __getSpec(): {
|
||||
globalOptions: GlobalOptions;
|
||||
params: ParamSpec<any>[];
|
||||
};
|
||||
133
node_modules/firebase-functions/lib/v2/options.js
generated
vendored
Normal file
133
node_modules/firebase-functions/lib/v2/options.js
generated
vendored
Normal file
@@ -0,0 +1,133 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2021 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.__getSpec = exports.optionsToEndpoint = exports.optionsToTriggerAnnotations = exports.getGlobalOptions = exports.setGlobalOptions = exports.RESET_VALUE = void 0;
|
||||
/**
|
||||
* Options to configure cloud functions.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
const encoding_1 = require("../common/encoding");
|
||||
const options_1 = require("../common/options");
|
||||
const params_1 = require("../params");
|
||||
const types_1 = require("../params/types");
|
||||
const logger = require("../logger");
|
||||
var options_2 = require("../common/options");
|
||||
Object.defineProperty(exports, "RESET_VALUE", { enumerable: true, get: function () { return options_2.RESET_VALUE; } });
|
||||
const MemoryOptionToMB = {
|
||||
"128MiB": 128,
|
||||
"256MiB": 256,
|
||||
"512MiB": 512,
|
||||
"1GiB": 1024,
|
||||
"2GiB": 2048,
|
||||
"4GiB": 4096,
|
||||
"8GiB": 8192,
|
||||
"16GiB": 16384,
|
||||
"32GiB": 32768,
|
||||
};
|
||||
let globalOptions;
|
||||
/**
|
||||
* Sets default options for all functions written using the 2nd gen SDK.
|
||||
* @param options Options to set as default
|
||||
*/
|
||||
function setGlobalOptions(options) {
|
||||
if (globalOptions) {
|
||||
logger.warn("Calling setGlobalOptions twice leads to undefined behavior");
|
||||
}
|
||||
globalOptions = options;
|
||||
}
|
||||
exports.setGlobalOptions = setGlobalOptions;
|
||||
/**
|
||||
* Get the currently set default options.
|
||||
* Used only for trigger generation.
|
||||
* @internal
|
||||
*/
|
||||
function getGlobalOptions() {
|
||||
return globalOptions || {};
|
||||
}
|
||||
exports.getGlobalOptions = getGlobalOptions;
|
||||
/**
|
||||
* Apply GlobalOptions to trigger definitions.
|
||||
* @internal
|
||||
*/
|
||||
function optionsToTriggerAnnotations(opts) {
|
||||
const annotation = {};
|
||||
(0, encoding_1.copyIfPresent)(annotation, opts, "concurrency", "minInstances", "maxInstances", "ingressSettings", "labels", "vpcConnector", "vpcConnectorEgressSettings", "secrets");
|
||||
(0, encoding_1.convertIfPresent)(annotation, opts, "availableMemoryMb", "memory", (mem) => {
|
||||
return MemoryOptionToMB[mem];
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(annotation, opts, "regions", "region", (region) => {
|
||||
if (typeof region === "string") {
|
||||
return [region];
|
||||
}
|
||||
return region;
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(annotation, opts, "serviceAccountEmail", "serviceAccount", encoding_1.serviceAccountFromShorthand);
|
||||
(0, encoding_1.convertIfPresent)(annotation, opts, "timeout", "timeoutSeconds", encoding_1.durationFromSeconds);
|
||||
(0, encoding_1.convertIfPresent)(annotation, opts, "failurePolicy", "retry", (retry) => {
|
||||
return retry ? { retry: true } : null;
|
||||
});
|
||||
return annotation;
|
||||
}
|
||||
exports.optionsToTriggerAnnotations = optionsToTriggerAnnotations;
|
||||
/**
|
||||
* Apply GlobalOptions to endpoint manifest.
|
||||
* @internal
|
||||
*/
|
||||
function optionsToEndpoint(opts) {
|
||||
const endpoint = {};
|
||||
(0, encoding_1.copyIfPresent)(endpoint, opts, "omit", "concurrency", "minInstances", "maxInstances", "ingressSettings", "labels", "timeoutSeconds", "cpu");
|
||||
(0, encoding_1.convertIfPresent)(endpoint, opts, "serviceAccountEmail", "serviceAccount");
|
||||
if (opts.vpcConnector !== undefined) {
|
||||
if (opts.vpcConnector === null || opts.vpcConnector instanceof options_1.ResetValue) {
|
||||
endpoint.vpc = options_1.RESET_VALUE;
|
||||
}
|
||||
else {
|
||||
const vpc = { connector: opts.vpcConnector };
|
||||
(0, encoding_1.convertIfPresent)(vpc, opts, "egressSettings", "vpcConnectorEgressSettings");
|
||||
endpoint.vpc = vpc;
|
||||
}
|
||||
}
|
||||
(0, encoding_1.convertIfPresent)(endpoint, opts, "availableMemoryMb", "memory", (mem) => {
|
||||
return typeof mem === "object" ? mem : MemoryOptionToMB[mem];
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(endpoint, opts, "region", "region", (region) => {
|
||||
if (typeof region === "string") {
|
||||
return [region];
|
||||
}
|
||||
return region;
|
||||
});
|
||||
(0, encoding_1.convertIfPresent)(endpoint, opts, "secretEnvironmentVariables", "secrets", (secrets) => secrets.map((secret) => ({ key: secret instanceof types_1.SecretParam ? secret.name : secret })));
|
||||
return endpoint;
|
||||
}
|
||||
exports.optionsToEndpoint = optionsToEndpoint;
|
||||
/**
|
||||
* @hidden
|
||||
* @alpha
|
||||
*/
|
||||
function __getSpec() {
|
||||
return {
|
||||
globalOptions: getGlobalOptions(),
|
||||
params: params_1.declaredParams.map((p) => p.toSpec()),
|
||||
};
|
||||
}
|
||||
exports.__getSpec = __getSpec;
|
||||
142
node_modules/firebase-functions/lib/v2/providers/alerts/alerts.d.ts
generated
vendored
Normal file
142
node_modules/firebase-functions/lib/v2/providers/alerts/alerts.d.ts
generated
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
import { ResetValue } from "../../../common/options";
|
||||
import { CloudEvent, CloudFunction } from "../../core";
|
||||
import { Expression } from "../../../params";
|
||||
import * as options from "../../options";
|
||||
import { SecretParam } from "../../../params/types";
|
||||
/**
|
||||
* The CloudEvent data emitted by Firebase Alerts.
|
||||
* @typeParam T - the payload type that is expected for this alert.
|
||||
*/
|
||||
export interface FirebaseAlertData<T = any> {
|
||||
/** Time that the event has created. */
|
||||
createTime: string;
|
||||
/** Time that the event has ended. Optional, only present for ongoing alerts. */
|
||||
endTime: string;
|
||||
/** Payload of the event, which includes the details of the specific alert. */
|
||||
payload: T;
|
||||
}
|
||||
/**
|
||||
* A custom CloudEvent for Firebase Alerts (with custom extension attributes).
|
||||
* @typeParam T - the data type for this alert that is wrapped in a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface AlertEvent<T> extends CloudEvent<FirebaseAlertData<T>> {
|
||||
/** The type of the alerts that got triggered. */
|
||||
alertType: string;
|
||||
/**
|
||||
* The Firebase App ID that’s associated with the alert. This is optional,
|
||||
* and only present when the alert is targeting at a specific Firebase App.
|
||||
*/
|
||||
appId?: string;
|
||||
/** Data for an `AlertEvent` is a `FirebaseAlertData` object with a given payload. */
|
||||
data: FirebaseAlertData<T>;
|
||||
}
|
||||
/** The underlying alert type of the Firebase Alerts provider. */
|
||||
export type AlertType = "crashlytics.newFatalIssue" | "crashlytics.newNonfatalIssue" | "crashlytics.regression" | "crashlytics.stabilityDigest" | "crashlytics.velocity" | "crashlytics.newAnrIssue" | "billing.planUpdate" | "billing.planAutomatedUpdate" | "appDistribution.newTesterIosDevice" | "appDistribution.inAppFeedback" | "performance.threshold" | string;
|
||||
/**
|
||||
* Configuration for Firebase Alert functions.
|
||||
*/
|
||||
export interface FirebaseAlertOptions extends options.EventHandlerOptions {
|
||||
/** Scope the handler to trigger on an alert type. */
|
||||
alertType: AlertType;
|
||||
/** Scope the function to trigger on a specific application. */
|
||||
appId?: string;
|
||||
/**
|
||||
* If true, do not deploy or emulate this function.
|
||||
*/
|
||||
omit?: boolean | Expression<boolean>;
|
||||
/**
|
||||
* Region where functions should be deployed.
|
||||
*/
|
||||
region?: options.SupportedRegion | string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Amount of memory to allocate to a function.
|
||||
* A value of null restores the defaults of 256MB.
|
||||
*/
|
||||
memory?: options.MemoryOption | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Timeout for the function in seconds, possible values are 0 to 540.
|
||||
* HTTPS functions can specify a higher timeout.
|
||||
* A value of null restores the default of 60s
|
||||
* The minimum timeout for a gen 2 function is 1s. The maximum timeout for a
|
||||
* function depends on the type of function: Event handling functions have a
|
||||
* maximum timeout of 540s (9 minutes). HTTPS and callable functions have a
|
||||
* maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
|
||||
* timeout of 1,800s (30 minutes)
|
||||
*/
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Min number of actual instances to be running at a given time.
|
||||
* Instances will be billed for memory allocation and 10% of CPU allocation
|
||||
* while idle.
|
||||
* A value of null restores the default min instances.
|
||||
*/
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Max number of instances to be running in parallel.
|
||||
* A value of null restores the default max instances.
|
||||
*/
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Number of requests a function can serve at once.
|
||||
* Can only be applied to functions running on Cloud Functions v2.
|
||||
* A value of null restores the default concurrency (80 when CPU >= 1, 1 otherwise).
|
||||
* Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
|
||||
* The maximum value for concurrency is 1,000.
|
||||
*/
|
||||
concurrency?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Fractional number of CPUs to allocate to a function.
|
||||
* Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
|
||||
* This is different from the defaults when using the gcloud utility and is different from
|
||||
* the fixed amount assigned in Google Cloud Functions generation 1.
|
||||
* To revert to the CPU amounts used in gcloud or in Cloud Functions generation 1, set this
|
||||
* to the value "gcf_gen1"
|
||||
*/
|
||||
cpu?: number | "gcf_gen1";
|
||||
/**
|
||||
* Connect cloud function to specified VPC connector.
|
||||
* A value of null removes the VPC connector
|
||||
*/
|
||||
vpcConnector?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Egress settings for VPC connector.
|
||||
* A value of null turns off VPC connector egress settings
|
||||
*/
|
||||
vpcConnectorEgressSettings?: options.VpcEgressSetting | ResetValue;
|
||||
/**
|
||||
* Specific service account for the function to run as.
|
||||
* A value of null restores the default service account.
|
||||
*/
|
||||
serviceAccount?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Ingress settings which control where this function can be called from.
|
||||
* A value of null turns off ingress settings.
|
||||
*/
|
||||
ingressSettings?: options.IngressSetting | ResetValue;
|
||||
/**
|
||||
* User labels to set on the function.
|
||||
*/
|
||||
labels?: Record<string, string>;
|
||||
secrets?: (string | SecretParam)[];
|
||||
/** Whether failed executions should be delivered again. */
|
||||
retry?: boolean | Expression<boolean> | ResetValue;
|
||||
}
|
||||
/**
|
||||
* Declares a function that can handle Firebase Alerts from CloudEvents.
|
||||
* @typeParam T - the type of event.data.payload.
|
||||
* @param alertType - the alert type or Firebase Alert function configuration.
|
||||
* @param handler a function that can handle the Firebase Alert inside a CloudEvent.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onAlertPublished<T extends {
|
||||
["@type"]: string;
|
||||
} = any>(alertType: AlertType, handler: (event: AlertEvent<T>) => any | Promise<any>): CloudFunction<AlertEvent<T>>;
|
||||
/**
|
||||
* Declares a function that can handle Firebase Alerts from CloudEvents.
|
||||
* @typeParam T - the type of event.data.payload.
|
||||
* @param options - the alert type and other options for this cloud function.
|
||||
* @param handler a function that can handle the Firebase Alert inside a CloudEvent.
|
||||
*/
|
||||
export declare function onAlertPublished<T extends {
|
||||
["@type"]: string;
|
||||
} = any>(options: FirebaseAlertOptions, handler: (event: AlertEvent<T>) => any | Promise<any>): CloudFunction<AlertEvent<T>>;
|
||||
108
node_modules/firebase-functions/lib/v2/providers/alerts/alerts.js
generated
vendored
Normal file
108
node_modules/firebase-functions/lib/v2/providers/alerts/alerts.js
generated
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.convertAlertAndApp = exports.getOptsAndAlertTypeAndApp = exports.getEndpointAnnotation = exports.onAlertPublished = exports.eventType = void 0;
|
||||
const manifest_1 = require("../../../runtime/manifest");
|
||||
const trace_1 = require("../../trace");
|
||||
const options = require("../../options");
|
||||
const onInit_1 = require("../../../common/onInit");
|
||||
/** @internal */
|
||||
exports.eventType = "google.firebase.firebasealerts.alerts.v1.published";
|
||||
function onAlertPublished(alertTypeOrOpts, handler) {
|
||||
const [opts, alertType, appId] = getOptsAndAlertTypeAndApp(alertTypeOrOpts);
|
||||
const func = (raw) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(convertAlertAndApp(raw));
|
||||
};
|
||||
func.run = handler;
|
||||
func.__endpoint = getEndpointAnnotation(opts, alertType, appId);
|
||||
return func;
|
||||
}
|
||||
exports.onAlertPublished = onAlertPublished;
|
||||
/**
|
||||
* Helper function for getting the endpoint annotation used in alert handling functions.
|
||||
* @internal
|
||||
*/
|
||||
function getEndpointAnnotation(opts, alertType, appId) {
|
||||
var _a;
|
||||
const baseOpts = options.optionsToEndpoint(options.getGlobalOptions());
|
||||
const specificOpts = options.optionsToEndpoint(opts);
|
||||
const endpoint = {
|
||||
...(0, manifest_1.initV2Endpoint)(options.getGlobalOptions(), opts),
|
||||
platform: "gcfv2",
|
||||
...baseOpts,
|
||||
...specificOpts,
|
||||
labels: {
|
||||
...baseOpts === null || baseOpts === void 0 ? void 0 : baseOpts.labels,
|
||||
...specificOpts === null || specificOpts === void 0 ? void 0 : specificOpts.labels,
|
||||
},
|
||||
eventTrigger: {
|
||||
eventType: exports.eventType,
|
||||
eventFilters: {
|
||||
alerttype: alertType,
|
||||
},
|
||||
retry: (_a = opts.retry) !== null && _a !== void 0 ? _a : false,
|
||||
},
|
||||
};
|
||||
if (appId) {
|
||||
endpoint.eventTrigger.eventFilters.appid = appId;
|
||||
}
|
||||
return endpoint;
|
||||
}
|
||||
exports.getEndpointAnnotation = getEndpointAnnotation;
|
||||
/**
|
||||
* Helper function to parse the function opts, alert type, and appId.
|
||||
* @internal
|
||||
*/
|
||||
function getOptsAndAlertTypeAndApp(alertTypeOrOpts) {
|
||||
let opts;
|
||||
let alertType;
|
||||
let appId;
|
||||
if (typeof alertTypeOrOpts === "string") {
|
||||
alertType = alertTypeOrOpts;
|
||||
opts = {};
|
||||
}
|
||||
else {
|
||||
alertType = alertTypeOrOpts.alertType;
|
||||
appId = alertTypeOrOpts.appId;
|
||||
opts = { ...alertTypeOrOpts };
|
||||
delete opts.alertType;
|
||||
delete opts.appId;
|
||||
}
|
||||
return [opts, alertType, appId];
|
||||
}
|
||||
exports.getOptsAndAlertTypeAndApp = getOptsAndAlertTypeAndApp;
|
||||
/**
|
||||
* Helper function to covert alert type & app id in the CloudEvent to camel case.
|
||||
* @internal
|
||||
*/
|
||||
function convertAlertAndApp(raw) {
|
||||
const event = { ...raw };
|
||||
if ("alerttype" in event) {
|
||||
event.alertType = event.alerttype;
|
||||
}
|
||||
if ("appid" in event) {
|
||||
event.appId = event.appid;
|
||||
}
|
||||
return event;
|
||||
}
|
||||
exports.convertAlertAndApp = convertAlertAndApp;
|
||||
186
node_modules/firebase-functions/lib/v2/providers/alerts/appDistribution.d.ts
generated
vendored
Normal file
186
node_modules/firebase-functions/lib/v2/providers/alerts/appDistribution.d.ts
generated
vendored
Normal file
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Cloud functions to handle Firebase App Distribution events from Firebase Alerts.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
import { ResetValue } from "../../../common/options";
|
||||
import { Expression } from "../../../params";
|
||||
import { CloudEvent, CloudFunction } from "../../core";
|
||||
import { FirebaseAlertData } from "./alerts";
|
||||
import * as options from "../../options";
|
||||
import { SecretParam } from "../../../params/types";
|
||||
/**
|
||||
* The internal payload object for adding a new tester device to app distribution.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface NewTesterDevicePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.AppDistroNewTesterIosDevicePayload";
|
||||
/** Name of the tester */
|
||||
testerName: string;
|
||||
/** Email of the tester */
|
||||
testerEmail: string;
|
||||
/** The device model name */
|
||||
testerDeviceModelName: string;
|
||||
/** The device ID */
|
||||
testerDeviceIdentifier: string;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for receiving in-app feedback from a tester.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface InAppFeedbackPayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.AppDistroInAppFeedbackPayload";
|
||||
/** Resource name. Format: `projects/{project_number}/apps/{app_id}/releases/{release_id}/feedbackReports/{feedback_id}` */
|
||||
feedbackReport: string;
|
||||
/** Deep link back to the Firebase console. */
|
||||
feedbackConsoleUri: string;
|
||||
/** Name of the tester */
|
||||
testerName?: string;
|
||||
/** Email of the tester */
|
||||
testerEmail: string;
|
||||
/**
|
||||
* Version consisting of `versionName` and `versionCode` for Android and
|
||||
* `CFBundleShortVersionString` and `CFBundleVersion` for iOS.
|
||||
*/
|
||||
appVersion: string;
|
||||
/** Text entered by the tester */
|
||||
text: string;
|
||||
/** URI to download screenshot. This URI is fast expiring. */
|
||||
screenshotUri?: string;
|
||||
}
|
||||
/**
|
||||
* A custom CloudEvent for Firebase Alerts (with custom extension attributes).
|
||||
* @typeParam T - the data type for app distribution alerts that is wrapped in a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface AppDistributionEvent<T> extends CloudEvent<FirebaseAlertData<T>> {
|
||||
/** The type of the alerts that got triggered. */
|
||||
alertType: string;
|
||||
/** The Firebase App ID that’s associated with the alert. */
|
||||
appId: string;
|
||||
}
|
||||
/**
|
||||
* Configuration for app distribution functions.
|
||||
*/
|
||||
export interface AppDistributionOptions extends options.EventHandlerOptions {
|
||||
/** Scope the function to trigger on a specific application. */
|
||||
appId?: string;
|
||||
/**
|
||||
* If true, do not deploy or emulate this function.
|
||||
*/
|
||||
omit?: boolean | Expression<boolean>;
|
||||
/**
|
||||
* Region where functions should be deployed.
|
||||
*/
|
||||
region?: options.SupportedRegion | string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Amount of memory to allocate to a function.
|
||||
*/
|
||||
memory?: options.MemoryOption | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Timeout for the function in seconds, possible values are 0 to 540.
|
||||
* HTTPS functions can specify a higher timeout.
|
||||
*
|
||||
* @remarks
|
||||
* The minimum timeout for a gen 2 function is 1s. The maximum timeout for a
|
||||
* function depends on the type of function: Event handling functions have a
|
||||
* maximum timeout of 540s (9 minutes). HTTPS and callable functions have a
|
||||
* maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
|
||||
* timeout of 1,800s (30 minutes)
|
||||
*/
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Min number of actual instances to be running at a given time.
|
||||
*
|
||||
* @remarks
|
||||
* Instances will be billed for memory allocation and 10% of CPU allocation
|
||||
* while idle.
|
||||
*/
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Max number of instances to be running in parallel.
|
||||
*/
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Number of requests a function can serve at once.
|
||||
*
|
||||
* @remarks
|
||||
* Can only be applied to functions running on Cloud Functions v2.
|
||||
* A value of null restores the default concurrency (80 when CPU >= 1, 1 otherwise).
|
||||
* Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
|
||||
* The maximum value for concurrency is 1,000.
|
||||
*/
|
||||
concurrency?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Fractional number of CPUs to allocate to a function.
|
||||
*
|
||||
* @remarks
|
||||
* Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
|
||||
* This is different from the defaults when using the gcloud utility and is different from
|
||||
* the fixed amount assigned in Google Cloud Functions generation 1.
|
||||
* To revert to the CPU amounts used in gcloud or in Cloud Functions generation 1, set this
|
||||
* to the value "gcf_gen1"
|
||||
*/
|
||||
cpu?: number | "gcf_gen1";
|
||||
/**
|
||||
* Connect cloud function to specified VPC connector.
|
||||
*/
|
||||
vpcConnector?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Egress settings for VPC connector.
|
||||
*/
|
||||
vpcConnectorEgressSettings?: options.VpcEgressSetting | ResetValue;
|
||||
/**
|
||||
* Specific service account for the function to run as.
|
||||
*/
|
||||
serviceAccount?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Ingress settings which control where this function can be called from.
|
||||
*/
|
||||
ingressSettings?: options.IngressSetting | ResetValue;
|
||||
/**
|
||||
* User labels to set on the function.
|
||||
*/
|
||||
labels?: Record<string, string>;
|
||||
secrets?: (string | SecretParam)[];
|
||||
/** Whether failed executions should be delivered again. */
|
||||
retry?: boolean | Expression<boolean> | ResetValue;
|
||||
}
|
||||
/**
|
||||
* Declares a function that can handle adding a new tester iOS device.
|
||||
* @param handler - Event handler which is run every time a new tester iOS device is added.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewTesterIosDevicePublished(handler: (event: AppDistributionEvent<NewTesterDevicePayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<NewTesterDevicePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle adding a new tester iOS device.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler which is run every time a new tester iOS device is added.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewTesterIosDevicePublished(appId: string, handler: (event: AppDistributionEvent<NewTesterDevicePayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<NewTesterDevicePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle adding a new tester iOS device.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler which is run every time a new tester iOS device is added.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewTesterIosDevicePublished(opts: AppDistributionOptions, handler: (event: AppDistributionEvent<NewTesterDevicePayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<NewTesterDevicePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle receiving new in-app feedback from a tester.
|
||||
* @param handler - Event handler which is run every time new feedback is received.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onInAppFeedbackPublished(handler: (event: AppDistributionEvent<InAppFeedbackPayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<InAppFeedbackPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle receiving new in-app feedback from a tester.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler which is run every time new feedback is received.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onInAppFeedbackPublished(appId: string, handler: (event: AppDistributionEvent<InAppFeedbackPayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<InAppFeedbackPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle receiving new in-app feedback from a tester.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler which is run every time new feedback is received.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onInAppFeedbackPublished(opts: AppDistributionOptions, handler: (event: AppDistributionEvent<InAppFeedbackPayload>) => any | Promise<any>): CloudFunction<AppDistributionEvent<InAppFeedbackPayload>>;
|
||||
90
node_modules/firebase-functions/lib/v2/providers/alerts/appDistribution.js
generated
vendored
Normal file
90
node_modules/firebase-functions/lib/v2/providers/alerts/appDistribution.js
generated
vendored
Normal file
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getOptsAndApp = exports.onInAppFeedbackPublished = exports.onNewTesterIosDevicePublished = exports.inAppFeedbackAlert = exports.newTesterIosDeviceAlert = void 0;
|
||||
const trace_1 = require("../../trace");
|
||||
const alerts_1 = require("./alerts");
|
||||
const onInit_1 = require("../../../common/onInit");
|
||||
/** @internal */
|
||||
exports.newTesterIosDeviceAlert = "appDistribution.newTesterIosDevice";
|
||||
/** @internal */
|
||||
exports.inAppFeedbackAlert = "appDistribution.inAppFeedback";
|
||||
/**
|
||||
* Declares a function that can handle adding a new tester iOS device.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler which is run every time a new tester iOS device is added.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onNewTesterIosDevicePublished(appIdOrOptsOrHandler, handler) {
|
||||
if (typeof appIdOrOptsOrHandler === "function") {
|
||||
handler = appIdOrOptsOrHandler;
|
||||
appIdOrOptsOrHandler = {};
|
||||
}
|
||||
const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
|
||||
const func = (raw) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
|
||||
};
|
||||
func.run = handler;
|
||||
func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, exports.newTesterIosDeviceAlert, appId);
|
||||
return func;
|
||||
}
|
||||
exports.onNewTesterIosDevicePublished = onNewTesterIosDevicePublished;
|
||||
/**
|
||||
* Declares a function that can handle receiving new in-app feedback from a tester.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler which is run every time new feedback is received.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onInAppFeedbackPublished(appIdOrOptsOrHandler, handler) {
|
||||
if (typeof appIdOrOptsOrHandler === "function") {
|
||||
handler = appIdOrOptsOrHandler;
|
||||
appIdOrOptsOrHandler = {};
|
||||
}
|
||||
const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
|
||||
const func = (raw) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
|
||||
};
|
||||
func.run = handler;
|
||||
func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, exports.inAppFeedbackAlert, appId);
|
||||
return func;
|
||||
}
|
||||
exports.onInAppFeedbackPublished = onInAppFeedbackPublished;
|
||||
/**
|
||||
* Helper function to parse the function opts and appId.
|
||||
* @internal
|
||||
*/
|
||||
function getOptsAndApp(appIdOrOpts) {
|
||||
let opts;
|
||||
let appId;
|
||||
if (typeof appIdOrOpts === "string") {
|
||||
opts = {};
|
||||
appId = appIdOrOpts;
|
||||
}
|
||||
else {
|
||||
appId = appIdOrOpts.appId;
|
||||
opts = { ...appIdOrOpts };
|
||||
delete opts.appId;
|
||||
}
|
||||
return [opts, appId];
|
||||
}
|
||||
exports.getOptsAndApp = getOptsAndApp;
|
||||
65
node_modules/firebase-functions/lib/v2/providers/alerts/billing.d.ts
generated
vendored
Normal file
65
node_modules/firebase-functions/lib/v2/providers/alerts/billing.d.ts
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Cloud functions to handle billing events from Firebase Alerts.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
import { CloudEvent, CloudFunction } from "../../core";
|
||||
import { FirebaseAlertData } from "./alerts";
|
||||
import * as options from "../../options";
|
||||
/**
|
||||
* The internal payload object for billing plan updates.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface PlanUpdatePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.BillingPlanUpdatePayload";
|
||||
/** A Firebase billing plan. */
|
||||
billingPlan: string;
|
||||
/** The email address of the person that triggered billing plan change */
|
||||
principalEmail: string;
|
||||
/** The type of the notification, e.g. upgrade, downgrade */
|
||||
notificationType: string;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for billing plan automated updates.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface PlanAutomatedUpdatePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.BillingPlanAutomatedUpdatePayload";
|
||||
/** A Firebase billing plan. */
|
||||
billingPlan: string;
|
||||
/** The type of the notification, e.g. upgrade, downgrade */
|
||||
notificationType: string;
|
||||
}
|
||||
/**
|
||||
* A custom CloudEvent for billing Firebase Alerts (with custom extension attributes).
|
||||
* @typeParam T - the data type for billing alerts that is wrapped in a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface BillingEvent<T> extends CloudEvent<FirebaseAlertData<T>> {
|
||||
/** The type of the alerts that got triggered. */
|
||||
alertType: string;
|
||||
}
|
||||
/**
|
||||
* Declares a function that can handle a billing plan update event.
|
||||
* @param handler - Event handler which is run every time a billing plan is updated.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onPlanUpdatePublished(handler: (event: BillingEvent<PlanUpdatePayload>) => any | Promise<any>): CloudFunction<BillingEvent<PlanUpdatePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a billing plan update event.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler which is run every time a billing plan is updated.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onPlanUpdatePublished(opts: options.EventHandlerOptions, handler: (event: BillingEvent<PlanUpdatePayload>) => any | Promise<any>): CloudFunction<BillingEvent<PlanUpdatePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle an automated billing plan update event.
|
||||
* @param handler - Event handler which is run every time an automated billing plan update occurs.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onPlanAutomatedUpdatePublished(handler: (event: BillingEvent<PlanAutomatedUpdatePayload>) => any | Promise<any>): CloudFunction<BillingEvent<PlanAutomatedUpdatePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle an automated billing plan update event.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler which is run every time an automated billing plan update occurs.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onPlanAutomatedUpdatePublished(opts: options.EventHandlerOptions, handler: (event: BillingEvent<PlanAutomatedUpdatePayload>) => any | Promise<any>): CloudFunction<BillingEvent<PlanAutomatedUpdatePayload>>;
|
||||
65
node_modules/firebase-functions/lib/v2/providers/alerts/billing.js
generated
vendored
Normal file
65
node_modules/firebase-functions/lib/v2/providers/alerts/billing.js
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.onOperation = exports.onPlanAutomatedUpdatePublished = exports.onPlanUpdatePublished = exports.planAutomatedUpdateAlert = exports.planUpdateAlert = void 0;
|
||||
const trace_1 = require("../../trace");
|
||||
const alerts_1 = require("./alerts");
|
||||
const onInit_1 = require("../../../common/onInit");
|
||||
/** @internal */
|
||||
exports.planUpdateAlert = "billing.planUpdate";
|
||||
/** @internal */
|
||||
exports.planAutomatedUpdateAlert = "billing.planAutomatedUpdate";
|
||||
/**
|
||||
* Declares a function that can handle a billing plan update event.
|
||||
* @param optsOrHandler - Options or an event-handling function.
|
||||
* @param handler - Event handler which is run every time a billing plan is updated.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onPlanUpdatePublished(optsOrHandler, handler) {
|
||||
return onOperation(exports.planUpdateAlert, optsOrHandler, handler);
|
||||
}
|
||||
exports.onPlanUpdatePublished = onPlanUpdatePublished;
|
||||
/**
|
||||
* Declares a function that can handle an automated billing plan update event.
|
||||
* @param optsOrHandler - Options or an event-handling function.
|
||||
* @param handler - Event handler which is run every time an automated billing plan update occurs.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onPlanAutomatedUpdatePublished(optsOrHandler, handler) {
|
||||
return onOperation(exports.planAutomatedUpdateAlert, optsOrHandler, handler);
|
||||
}
|
||||
exports.onPlanAutomatedUpdatePublished = onPlanAutomatedUpdatePublished;
|
||||
/** @internal */
|
||||
function onOperation(alertType, optsOrHandler, handler) {
|
||||
if (typeof optsOrHandler === "function") {
|
||||
handler = optsOrHandler;
|
||||
optsOrHandler = {};
|
||||
}
|
||||
const func = (raw) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
|
||||
};
|
||||
func.run = handler;
|
||||
func.__endpoint = (0, alerts_1.getEndpointAnnotation)(optsOrHandler, alertType);
|
||||
return func;
|
||||
}
|
||||
exports.onOperation = onOperation;
|
||||
338
node_modules/firebase-functions/lib/v2/providers/alerts/crashlytics.d.ts
generated
vendored
Normal file
338
node_modules/firebase-functions/lib/v2/providers/alerts/crashlytics.d.ts
generated
vendored
Normal file
@@ -0,0 +1,338 @@
|
||||
/**
|
||||
* Cloud functions to handle Crashlytics events from Firebase Alerts.
|
||||
* @packageDocumentation
|
||||
*/
|
||||
import { ResetValue } from "../../../common/options";
|
||||
import { Expression } from "../../../params";
|
||||
import { CloudEvent, CloudFunction } from "../../core";
|
||||
import { FirebaseAlertData } from "./alerts";
|
||||
import * as options from "../../options";
|
||||
import { SecretParam } from "../../../params/types";
|
||||
/** Generic Crashlytics issue interface */
|
||||
export interface Issue {
|
||||
/** The ID of the Crashlytics issue */
|
||||
id: string;
|
||||
/** The title of the Crashlytics issue */
|
||||
title: string;
|
||||
/** The subtitle of the Crashlytics issue */
|
||||
subtitle: string;
|
||||
/** The application version of the Crashlytics issue */
|
||||
appVersion: string;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a new fatal issue.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface NewFatalIssuePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsNewFatalIssuePayload";
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a new non-fatal issue.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface NewNonfatalIssuePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsNewNonfatalIssuePayload";
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a regression alert.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface RegressionAlertPayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsRegressionAlertPayload";
|
||||
/** The type of the Crashlytics issue, e.g. new fatal, new nonfatal, ANR */
|
||||
type: string;
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
/**
|
||||
* The time that the Crashlytics issues was most recently resolved before it
|
||||
* began to reoccur.
|
||||
*/
|
||||
resolveTime: string;
|
||||
}
|
||||
/** Generic Crashlytics trending issue interface */
|
||||
export interface TrendingIssueDetails {
|
||||
/** The type of the Crashlytics issue, e.g. new fatal, new nonfatal, ANR */
|
||||
type: string;
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
/** The number of crashes that occurred with the issue */
|
||||
eventCount: number;
|
||||
/** The number of distinct users that were affected by the issue */
|
||||
userCount: number;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a stability digest.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface StabilityDigestPayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsStabilityDigestPayload";
|
||||
/**
|
||||
* The date that the digest gets created. Issues in the digest should have the
|
||||
* same date as the digest date
|
||||
*/
|
||||
digestDate: string;
|
||||
/** A stability digest containing several trending Crashlytics issues */
|
||||
trendingIssues: TrendingIssueDetails[];
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a velocity alert.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface VelocityAlertPayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsVelocityAlertPayload";
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
/** The time that the Crashlytics issue gets created */
|
||||
createTime: string;
|
||||
/**
|
||||
* The number of user sessions for the given app version that had this
|
||||
* specific crash issue in the time period used to trigger the velocity alert.
|
||||
*/
|
||||
crashCount: number;
|
||||
/**
|
||||
* The percentage of user sessions for the given app version that had this
|
||||
* specific crash issue in the time period used to trigger the velocity alert.
|
||||
*/
|
||||
crashPercentage: number;
|
||||
/**
|
||||
* The first app version where this issue was seen, and not necessarily the
|
||||
* version that has triggered the alert.
|
||||
*/
|
||||
firstVersion: string;
|
||||
}
|
||||
/**
|
||||
* The internal payload object for a new Application Not Responding issue.
|
||||
* Payload is wrapped inside a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface NewAnrIssuePayload {
|
||||
["@type"]: "type.googleapis.com/google.events.firebase.firebasealerts.v1.CrashlyticsNewAnrIssuePayload";
|
||||
/** Basic information of the Crashlytics issue */
|
||||
issue: Issue;
|
||||
}
|
||||
/**
|
||||
* A custom CloudEvent for Firebase Alerts (with custom extension attributes).
|
||||
* @typeParam T - the data type for Crashlytics alerts that is wrapped in a `FirebaseAlertData` object.
|
||||
*/
|
||||
export interface CrashlyticsEvent<T> extends CloudEvent<FirebaseAlertData<T>> {
|
||||
/** The type of the alerts that got triggered. */
|
||||
alertType: string;
|
||||
/** The Firebase App ID that’s associated with the alert. */
|
||||
appId: string;
|
||||
}
|
||||
/**
|
||||
* Configuration for Crashlytics functions.
|
||||
*/
|
||||
export interface CrashlyticsOptions extends options.EventHandlerOptions {
|
||||
/** Scope the function to trigger on a specific application. */
|
||||
appId?: string;
|
||||
/**
|
||||
* If true, do not deploy or emulate this function.
|
||||
*/
|
||||
omit?: boolean | Expression<boolean>;
|
||||
/**
|
||||
* Region where functions should be deployed.
|
||||
*/
|
||||
region?: options.SupportedRegion | string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Amount of memory to allocate to a function.
|
||||
*/
|
||||
memory?: options.MemoryOption | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Timeout for the function in seconds, possible values are 0 to 540.
|
||||
* HTTPS functions can specify a higher timeout.
|
||||
*
|
||||
* @remarks
|
||||
* The minimum timeout for a gen 2 function is 1s. The maximum timeout for a
|
||||
* function depends on the type of function: Event handling functions have a
|
||||
* maximum timeout of 540s (9 minutes). HTTPS and callable functions have a
|
||||
* maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
|
||||
* timeout of 1,800s (30 minutes)
|
||||
*/
|
||||
timeoutSeconds?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Min number of actual instances to be running at a given time.
|
||||
*
|
||||
* @remarks
|
||||
* Instances will be billed for memory allocation and 10% of CPU allocation
|
||||
* while idle.
|
||||
*/
|
||||
minInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Max number of instances to be running in parallel.
|
||||
*/
|
||||
maxInstances?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Number of requests a function can serve at once.
|
||||
*
|
||||
* @remarks
|
||||
* Can only be applied to functions running on Cloud Functions v2.
|
||||
* A value of null restores the default concurrency (80 when CPU >= 1, 1 otherwise).
|
||||
* Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
|
||||
* The maximum value for concurrency is 1,000.
|
||||
*/
|
||||
concurrency?: number | Expression<number> | ResetValue;
|
||||
/**
|
||||
* Fractional number of CPUs to allocate to a function.
|
||||
*
|
||||
* @remarks
|
||||
* Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
|
||||
* This is different from the defaults when using the gcloud utility and is different from
|
||||
* the fixed amount assigned in Google Cloud Functions generation 1.
|
||||
* To revert to the CPU amounts used in gcloud or in Cloud Functions generation 1, set this
|
||||
* to the value "gcf_gen1"
|
||||
*/
|
||||
cpu?: number | "gcf_gen1";
|
||||
/**
|
||||
* Connect cloud function to specified VPC connector.
|
||||
*/
|
||||
vpcConnector?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Egress settings for VPC connector.
|
||||
*/
|
||||
vpcConnectorEgressSettings?: options.VpcEgressSetting | ResetValue;
|
||||
/**
|
||||
* Specific service account for the function to run as.
|
||||
*/
|
||||
serviceAccount?: string | Expression<string> | ResetValue;
|
||||
/**
|
||||
* Ingress settings which control where this function can be called from.
|
||||
*/
|
||||
ingressSettings?: options.IngressSetting | ResetValue;
|
||||
/**
|
||||
* User labels to set on the function.
|
||||
*/
|
||||
labels?: Record<string, string>;
|
||||
secrets?: (string | SecretParam)[];
|
||||
/** Whether failed executions should be delivered again. */
|
||||
retry?: boolean | Expression<boolean> | ResetValue;
|
||||
}
|
||||
/**
|
||||
* Declares a function that can handle a new fatal issue published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a new fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewFatalIssuePublished(handler: (event: CrashlyticsEvent<NewFatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewFatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new fatal issue published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a new fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewFatalIssuePublished(appId: string, handler: (event: CrashlyticsEvent<NewFatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewFatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new fatal issue published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a new fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewFatalIssuePublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<NewFatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewFatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new non-fatal issue published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a new fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewNonfatalIssuePublished(handler: (event: CrashlyticsEvent<NewNonfatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewNonfatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new non-fatal issue published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a new non-fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewNonfatalIssuePublished(appId: string, handler: (event: CrashlyticsEvent<NewNonfatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewNonfatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new non-fatal issue published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a new non-fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewNonfatalIssuePublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<NewNonfatalIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewNonfatalIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a regression alert published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a regression alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onRegressionAlertPublished(handler: (event: CrashlyticsEvent<RegressionAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<RegressionAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a regression alert published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a regression alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onRegressionAlertPublished(appId: string, handler: (event: CrashlyticsEvent<RegressionAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<RegressionAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a regression alert published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a regression alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onRegressionAlertPublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<RegressionAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<RegressionAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a stability digest published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a stability digest is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onStabilityDigestPublished(handler: (event: CrashlyticsEvent<StabilityDigestPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<StabilityDigestPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a stability digest published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a stability digest is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onStabilityDigestPublished(appId: string, handler: (event: CrashlyticsEvent<StabilityDigestPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<StabilityDigestPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a stability digest published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a stability digest is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onStabilityDigestPublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<StabilityDigestPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<StabilityDigestPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a velocity alert published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a velocity alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onVelocityAlertPublished(handler: (event: CrashlyticsEvent<VelocityAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<VelocityAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a velocity alert published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a velocity alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onVelocityAlertPublished(appId: string, handler: (event: CrashlyticsEvent<VelocityAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<VelocityAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a velocity alert published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a velocity alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onVelocityAlertPublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<VelocityAlertPayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<VelocityAlertPayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new Application Not Responding issue published to Crashlytics.
|
||||
* @param handler - Event handler that is triggered when a new Application Not Responding issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
export declare function onNewAnrIssuePublished(handler: (event: CrashlyticsEvent<NewAnrIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewAnrIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new Application Not Responding issue published to Crashlytics.
|
||||
* @param appId - A specific application the handler will trigger on.
|
||||
* @param handler - Event handler that is triggered when a new Application Not Responding issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onNewAnrIssuePublished(appId: string, handler: (event: CrashlyticsEvent<NewAnrIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewAnrIssuePayload>>;
|
||||
/**
|
||||
* Declares a function that can handle a new Application Not Responding issue published to Crashlytics.
|
||||
* @param opts - Options that can be set on the function.
|
||||
* @param handler - Event handler that is triggered when a new Application Not Responding issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
|
||||
*/
|
||||
export declare function onNewAnrIssuePublished(opts: CrashlyticsOptions, handler: (event: CrashlyticsEvent<NewAnrIssuePayload>) => any | Promise<any>): CloudFunction<CrashlyticsEvent<NewAnrIssuePayload>>;
|
||||
133
node_modules/firebase-functions/lib/v2/providers/alerts/crashlytics.js
generated
vendored
Normal file
133
node_modules/firebase-functions/lib/v2/providers/alerts/crashlytics.js
generated
vendored
Normal file
@@ -0,0 +1,133 @@
|
||||
"use strict";
|
||||
// The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2022 Firebase
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getOptsAndApp = exports.onOperation = exports.onNewAnrIssuePublished = exports.onVelocityAlertPublished = exports.onStabilityDigestPublished = exports.onRegressionAlertPublished = exports.onNewNonfatalIssuePublished = exports.onNewFatalIssuePublished = exports.newAnrIssueAlert = exports.velocityAlert = exports.stabilityDigestAlert = exports.regressionAlert = exports.newNonfatalIssueAlert = exports.newFatalIssueAlert = void 0;
|
||||
const trace_1 = require("../../trace");
|
||||
const alerts_1 = require("./alerts");
|
||||
const onInit_1 = require("../../../common/onInit");
|
||||
/** @internal */
|
||||
exports.newFatalIssueAlert = "crashlytics.newFatalIssue";
|
||||
/** @internal */
|
||||
exports.newNonfatalIssueAlert = "crashlytics.newNonfatalIssue";
|
||||
/** @internal */
|
||||
exports.regressionAlert = "crashlytics.regression";
|
||||
/** @internal */
|
||||
exports.stabilityDigestAlert = "crashlytics.stabilityDigest";
|
||||
/** @internal */
|
||||
exports.velocityAlert = "crashlytics.velocity";
|
||||
/** @internal */
|
||||
exports.newAnrIssueAlert = "crashlytics.newAnrIssue";
|
||||
/**
|
||||
* Declares a function that can handle a new fatal issue published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a new fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onNewFatalIssuePublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.newFatalIssueAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onNewFatalIssuePublished = onNewFatalIssuePublished;
|
||||
/**
|
||||
* Declares a function that can handle a new non-fatal issue published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a new non-fatal issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onNewNonfatalIssuePublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.newNonfatalIssueAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onNewNonfatalIssuePublished = onNewNonfatalIssuePublished;
|
||||
/**
|
||||
* Declares a function that can handle a regression alert published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a regression alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onRegressionAlertPublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.regressionAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onRegressionAlertPublished = onRegressionAlertPublished;
|
||||
/**
|
||||
* Declares a function that can handle a stability digest published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a stability digest is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onStabilityDigestPublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.stabilityDigestAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onStabilityDigestPublished = onStabilityDigestPublished;
|
||||
/**
|
||||
* Declares a function that can handle a velocity alert published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a velocity alert is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onVelocityAlertPublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.velocityAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onVelocityAlertPublished = onVelocityAlertPublished;
|
||||
/**
|
||||
* Declares a function that can handle a new Application Not Responding issue published to Crashlytics.
|
||||
* @param appIdOrOptsOrHandler - A specific application, options, or an event-handling function.
|
||||
* @param handler - Event handler that is triggered when a new Application Not Responding issue is published to Crashlytics.
|
||||
* @returns A function that you can export and deploy.
|
||||
*/
|
||||
function onNewAnrIssuePublished(appIdOrOptsOrHandler, handler) {
|
||||
return onOperation(exports.newAnrIssueAlert, appIdOrOptsOrHandler, handler);
|
||||
}
|
||||
exports.onNewAnrIssuePublished = onNewAnrIssuePublished;
|
||||
/** @internal */
|
||||
function onOperation(alertType, appIdOrOptsOrHandler, handler) {
|
||||
if (typeof appIdOrOptsOrHandler === "function") {
|
||||
handler = appIdOrOptsOrHandler;
|
||||
appIdOrOptsOrHandler = {};
|
||||
}
|
||||
const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
|
||||
const func = (raw) => {
|
||||
return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
|
||||
};
|
||||
func.run = handler;
|
||||
func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, alertType, appId);
|
||||
return func;
|
||||
}
|
||||
exports.onOperation = onOperation;
|
||||
/**
|
||||
* Helper function to parse the function opts and appId.
|
||||
* @internal
|
||||
*/
|
||||
function getOptsAndApp(appIdOrOpts) {
|
||||
let opts;
|
||||
let appId;
|
||||
if (typeof appIdOrOpts === "string") {
|
||||
opts = {};
|
||||
appId = appIdOrOpts;
|
||||
}
|
||||
else {
|
||||
appId = appIdOrOpts.appId;
|
||||
opts = { ...appIdOrOpts };
|
||||
delete opts.appId;
|
||||
}
|
||||
return [opts, appId];
|
||||
}
|
||||
exports.getOptsAndApp = getOptsAndApp;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user