feat(notification_bloc): add base architecture and start impementing firebase messaging data source. Add example too (#33)

This commit is contained in:
AN12345 2022-11-24 15:09:33 -05:00
parent 8bb0dbb6b7
commit 5da1cd0471
4555 changed files with 771416 additions and 156 deletions

View File

@ -1,30 +1,4 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:wyatt_analysis/analysis_options.flutter.yaml
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
analyzer:
exclude: "!example/**"

View File

@ -22,6 +22,9 @@ if (flutterVersionName == null) {
}
apply plugin: 'com.android.application'
// START: FlutterFire Configuration
apply plugin: 'com.google.gms.google-services'
// END: FlutterFire Configuration
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

View File

@ -7,6 +7,9 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
// START: FlutterFire Configuration
classpath 'com.google.gms:google-services:4.3.10'
// END: FlutterFire Configuration
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

View File

@ -1 +1,2 @@
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"

View File

@ -1 +1,2 @@
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"

View File

@ -0,0 +1,41 @@
# Uncomment this line to define a global platform for your project
platform :ios, '13.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end

View File

@ -0,0 +1,104 @@
PODS:
- Firebase/CoreOnly (10.2.0):
- FirebaseCore (= 10.2.0)
- Firebase/Messaging (10.2.0):
- Firebase/CoreOnly
- FirebaseMessaging (~> 10.2.0)
- firebase_core (2.3.0):
- Firebase/CoreOnly (= 10.2.0)
- Flutter
- firebase_messaging (14.1.1):
- Firebase/Messaging (= 10.2.0)
- firebase_core
- Flutter
- FirebaseCore (10.2.0):
- FirebaseCoreInternal (~> 10.0)
- GoogleUtilities/Environment (~> 7.8)
- GoogleUtilities/Logger (~> 7.8)
- FirebaseCoreInternal (10.2.0):
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- FirebaseInstallations (10.2.0):
- FirebaseCore (~> 10.0)
- GoogleUtilities/Environment (~> 7.8)
- GoogleUtilities/UserDefaults (~> 7.8)
- PromisesObjC (~> 2.1)
- FirebaseMessaging (10.2.0):
- FirebaseCore (~> 10.0)
- FirebaseInstallations (~> 10.0)
- GoogleDataTransport (~> 9.2)
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/Environment (~> 7.8)
- GoogleUtilities/Reachability (~> 7.8)
- GoogleUtilities/UserDefaults (~> 7.8)
- nanopb (< 2.30910.0, >= 2.30908.0)
- Flutter (1.0.0)
- GoogleDataTransport (9.2.0):
- GoogleUtilities/Environment (~> 7.7)
- nanopb (< 2.30910.0, >= 2.30908.0)
- PromisesObjC (< 3.0, >= 1.2)
- GoogleUtilities/AppDelegateSwizzler (7.10.0):
- GoogleUtilities/Environment
- GoogleUtilities/Logger
- GoogleUtilities/Network
- GoogleUtilities/Environment (7.10.0):
- PromisesObjC (< 3.0, >= 1.2)
- GoogleUtilities/Logger (7.10.0):
- GoogleUtilities/Environment
- GoogleUtilities/Network (7.10.0):
- GoogleUtilities/Logger
- "GoogleUtilities/NSData+zlib"
- GoogleUtilities/Reachability
- "GoogleUtilities/NSData+zlib (7.10.0)"
- GoogleUtilities/Reachability (7.10.0):
- GoogleUtilities/Logger
- GoogleUtilities/UserDefaults (7.10.0):
- GoogleUtilities/Logger
- nanopb (2.30909.0):
- nanopb/decode (= 2.30909.0)
- nanopb/encode (= 2.30909.0)
- nanopb/decode (2.30909.0)
- nanopb/encode (2.30909.0)
- PromisesObjC (2.1.1)
DEPENDENCIES:
- firebase_core (from `.symlinks/plugins/firebase_core/ios`)
- firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`)
- Flutter (from `Flutter`)
SPEC REPOS:
trunk:
- Firebase
- FirebaseCore
- FirebaseCoreInternal
- FirebaseInstallations
- FirebaseMessaging
- GoogleDataTransport
- GoogleUtilities
- nanopb
- PromisesObjC
EXTERNAL SOURCES:
firebase_core:
:path: ".symlinks/plugins/firebase_core/ios"
firebase_messaging:
:path: ".symlinks/plugins/firebase_messaging/ios"
Flutter:
:path: Flutter
SPEC CHECKSUMS:
Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf
firebase_core: db1432de826785171029b7c1a26e5b22ce1dd477
firebase_messaging: 5babce6fa9ce1e0c63a854dabba227f23dc68b1b
FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1
FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f
FirebaseInstallations: 004915af170935e3a583faefd5f8bc851afc220f
FirebaseMessaging: cc9f40f5b7494680f3844d08e517e92aa4e8d9f7
Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854
GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f
GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95
nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431
PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb
PODFILE CHECKSUM: cc1f88378b4bfcf93a6ce00d2c587857c6008d3b
COCOAPODS: 1.11.3

View File

@ -3,11 +3,12 @@
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objectVersion = 51;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
2B18E3453BA17FB610231460 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F3EE6554D2B040AC98E4B97B /* Pods_Runner.framework */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
@ -32,6 +33,10 @@
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
431CF649C456E9102214DF1B /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
4734890851F5CD8D7662D3A7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
65CA93E1AF53B6CE22140295 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
7416F07B292EF3D9000E6D63 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
@ -42,6 +47,7 @@
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
F3EE6554D2B040AC98E4B97B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -49,12 +55,21 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2B18E3453BA17FB610231460 /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
673258A1CE39C904DEEA90CB /* Frameworks */ = {
isa = PBXGroup;
children = (
F3EE6554D2B040AC98E4B97B /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
@ -72,6 +87,8 @@
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
9D4FFD0723D599C94D20F644 /* Pods */,
673258A1CE39C904DEEA90CB /* Frameworks */,
);
sourceTree = "<group>";
};
@ -86,6 +103,7 @@
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
7416F07B292EF3D9000E6D63 /* Runner.entitlements */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
@ -98,6 +116,16 @@
path = Runner;
sourceTree = "<group>";
};
9D4FFD0723D599C94D20F644 /* Pods */ = {
isa = PBXGroup;
children = (
4734890851F5CD8D7662D3A7 /* Pods-Runner.debug.xcconfig */,
431CF649C456E9102214DF1B /* Pods-Runner.release.xcconfig */,
65CA93E1AF53B6CE22140295 /* Pods-Runner.profile.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@ -105,12 +133,14 @@
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
9374433038A75598AD754534 /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
4BFFB06ADC6A6C0A0D2913CB /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
@ -183,6 +213,45 @@
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
4BFFB06ADC6A6C0A0D2913CB /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
9374433038A75598AD754534 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@ -287,8 +356,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = W6464PZ8CJ;
DEVELOPMENT_TEAM = "";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
@ -297,6 +368,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.notificationBlocExample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
@ -416,8 +488,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = W6464PZ8CJ;
DEVELOPMENT_TEAM = "";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
@ -426,6 +500,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.notificationBlocExample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
@ -439,8 +514,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = W6464PZ8CJ;
DEVELOPMENT_TEAM = "";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
@ -449,6 +526,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.notificationBlocExample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";

View File

@ -4,4 +4,7 @@
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>

View File

@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
@ -24,6 +26,12 @@
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@ -43,9 +51,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>

View File

@ -0,0 +1,7 @@
{
"file_generated_by": "FlutterFire CLI",
"purpose": "FirebaseAppID & ProjectID for this Firebase app in this directory",
"GOOGLE_APP_ID": "1:100151285458:ios:d1f6f7861c3c6fa7c07f0b",
"FIREBASE_PROJECT_ID": "wyatt-notification-example",
"GCM_SENDER_ID": "100151285458"
}

View File

@ -0,0 +1,59 @@
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for web - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyCbccibm2XZqeCIQ2_YQXRDMxUNkEBxCjY',
appId: '1:100151285458:android:a0da0cf8db22caf5c07f0b',
messagingSenderId: '100151285458',
projectId: 'wyatt-notification-example',
storageBucket: 'wyatt-notification-example.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyApVqPAYLHRMNFIDNqbD-GA-gX7bheRs5o',
appId: '1:100151285458:ios:d1f6f7861c3c6fa7c07f0b',
messagingSenderId: '100151285458',
projectId: 'wyatt-notification-example',
storageBucket: 'wyatt-notification-example.appspot.com',
iosClientId: '100151285458-a9notq1k1padf0vk9ove8ll3amjgi7mn.apps.googleusercontent.com',
iosBundleId: 'com.example.notificationBlocExample',
);
}

View File

@ -1,6 +1,15 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:notification_bloc_example/firebase_options.dart';
import 'package:wyatt_notification_bloc/wyatt_notification_bloc.dart';
void main() {
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
print("Runnig App");
runApp(const MyApp());
}
@ -48,21 +57,19 @@ class MyHomePage extends StatefulWidget {
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String _content = 'No content';
void _incrementCounter() {
void _handlerNotif(RemoteNotificationWrapper notif) {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
_content = notif.data.toString();
});
}
@override
Widget build(BuildContext context) {
final notificationFirebaseDataSource = FirebaseMessagingDataSourceImpl();
final notificationRepository = NotificationRepositoryImpl(
notificationRemoteDataSource: notificationFirebaseDataSource);
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
@ -75,7 +82,22 @@ class _MyHomePageState extends State<MyHomePage> {
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
body: BlocProvider<NotificationCubit>(
lazy: false,
create: (context) => NotificationCubit(
register: Register(notificationRepository: notificationRepository),
getInitialMessage: GetInitialMessage(
notificationRepository: notificationRepository),
listenNotification: ListenNotification(
notificationRepository: notificationRepository),
subscribe:
Subscribe(notificationRepository: notificationRepository),
unsubscribe:
Unsubscribe(notificationRepository: notificationRepository),
handleNotification: _handlerNotif)
..register()
..listenNotification(),
child: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
@ -96,20 +118,16 @@ class _MyHomePageState extends State<MyHomePage> {
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
'content of notification :',
),
Text(
'$_counter',
_content,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}

View File

@ -32,14 +32,24 @@ dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.1.1
wyatt_notification_bloc:
path: ../
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_core: ^2.3.0
dev_dependencies:
flutter_test:
sdk: flutter
wyatt_analysis:
git:
url: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages
ref: wyatt_analysis-v2.2.2
path: packages/wyatt_analysis
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is

View File

@ -0,0 +1,9 @@
{
"aps": {
"alert": {
"title": "Wyatt Studio raised 1M$",
"subtitle": "Letz goo",
"body": "They can afford a mac"
}
}
}

View File

@ -0,0 +1 @@
../acorn/bin/acorn

View File

@ -0,0 +1 @@
../google-gax/build/tools/compileProtos.js

View File

@ -0,0 +1 @@
../escodegen/bin/escodegen.js

View File

@ -0,0 +1 @@
../escodegen/bin/esgenerate.js

View File

@ -0,0 +1 @@
../esprima/bin/esparse.js

View File

@ -0,0 +1 @@
../esprima/bin/esvalidate.js

View File

@ -0,0 +1 @@
../google-p12-pem/build/src/bin/gp12-pem.js

View File

@ -0,0 +1 @@
../jsdoc/jsdoc.js

View File

@ -0,0 +1 @@
../markdown-it/bin/markdown-it.js

View File

@ -0,0 +1 @@
../marked/bin/marked.js

View File

@ -0,0 +1 @@
../mime/cli.js

View File

@ -0,0 +1 @@
../google-gax/build/tools/minify.js

View File

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

View File

@ -0,0 +1 @@
../@babel/parser/bin/babel-parser.js

View File

@ -0,0 +1 @@
../protobufjs-cli/bin/pbjs

View File

@ -0,0 +1 @@
../protobufjs-cli/bin/pbts

View File

@ -0,0 +1 @@
../@grpc/proto-loader/build/bin/proto-loader-gen-types.js

View File

@ -0,0 +1 @@
../rimraf/bin.js

View File

@ -0,0 +1 @@
../semver/bin/semver

View File

@ -0,0 +1 @@
../uglify-js/bin/uglifyjs

View File

@ -0,0 +1 @@
../uuid/dist/bin/uuid

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
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.

View File

@ -0,0 +1,19 @@
# @babel/parser
> A JavaScript parser
See our website [@babel/parser](https://babeljs.io/docs/en/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%20(babylon)%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/parser
```
or using yarn:
```sh
yarn add @babel/parser --dev
```

View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
/* eslint no-var: 0 */
var parser = require("..");
var fs = require("fs");
var filename = process.argv[2];
if (!filename) {
console.error("no filename specified");
} else {
var file = fs.readFileSync(filename, "utf8");
var ast = parser.parse(file);
console.log(JSON.stringify(ast, null, " "));
}

View File

@ -0,0 +1,5 @@
try {
module.exports = require("./lib/index.cjs");
} catch {
module.exports = require("./lib/index.js");
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,46 @@
{
"name": "@babel/parser",
"version": "7.20.3",
"description": "A JavaScript parser",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-parser",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A+parser+%28babylon%29%22+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"keywords": [
"babel",
"javascript",
"parser",
"tc39",
"ecmascript",
"@babel/parser"
],
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-parser"
},
"main": "./lib/index.js",
"types": "./typings/babel-parser.d.ts",
"files": [
"bin",
"lib",
"typings",
"index.cjs"
],
"engines": {
"node": ">=6.0.0"
},
"devDependencies": {
"@babel/code-frame": "^7.18.6",
"@babel/helper-check-duplicate-nodes": "^7.18.6",
"@babel/helper-fixtures": "^7.19.4",
"@babel/helper-string-parser": "^7.19.4",
"@babel/helper-validator-identifier": "^7.19.1",
"charcodes": "^0.2.0"
},
"bin": "./bin/babel-parser.js",
"type": "commonjs"
}

View File

@ -0,0 +1,227 @@
// This file is auto-generated! Do not modify it directly.
/* eslint-disable import/no-extraneous-dependencies, @typescript-eslint/consistent-type-imports, prettier/prettier */
import * as _babel_types from '@babel/types';
type Plugin =
| "asyncDoExpressions"
| "asyncGenerators"
| "bigInt"
| "classPrivateMethods"
| "classPrivateProperties"
| "classProperties"
| "classStaticBlock" // Enabled by default
| "decimal"
| "decorators-legacy"
| "decoratorAutoAccessors"
| "destructuringPrivate"
| "doExpressions"
| "dynamicImport"
| "explicitResourceManagement"
| "exportDefaultFrom"
| "exportNamespaceFrom" // deprecated
| "flow"
| "flowComments"
| "functionBind"
| "functionSent"
| "importMeta"
| "jsx"
| "logicalAssignment"
| "importAssertions"
| "importReflection"
| "moduleBlocks"
| "moduleStringNames"
| "nullishCoalescingOperator"
| "numericSeparator"
| "objectRestSpread"
| "optionalCatchBinding"
| "optionalChaining"
| "partialApplication"
| "placeholders"
| "privateIn" // Enabled by default
| "regexpUnicodeSets"
| "throwExpressions"
| "topLevelAwait"
| "v8intrinsic"
| ParserPluginWithOptions[0];
type ParserPluginWithOptions =
| ["decorators", DecoratorsPluginOptions]
| ["estree", { classFeatures?: boolean }]
// @deprecated
| ["moduleAttributes", { version: "may-2020" }]
| ["pipelineOperator", PipelineOperatorPluginOptions]
| ["recordAndTuple", RecordAndTuplePluginOptions]
| ["flow", FlowPluginOptions]
| ["typescript", TypeScriptPluginOptions];
type PluginConfig = Plugin | ParserPluginWithOptions;
interface DecoratorsPluginOptions {
decoratorsBeforeExport?: boolean;
allowCallParenthesized?: boolean;
}
interface PipelineOperatorPluginOptions {
proposal: "minimal" | "fsharp" | "hack" | "smart";
topicToken?: "%" | "#" | "@@" | "^^" | "^";
}
interface RecordAndTuplePluginOptions {
syntaxType: "bar" | "hash";
}
interface FlowPluginOptions {
all?: boolean;
enums?: boolean;
}
interface TypeScriptPluginOptions {
dts?: boolean;
disallowAmbiguousJSXLike?: boolean;
}
// Type definitions for @babel/parser
// Project: https://github.com/babel/babel/tree/main/packages/babel-parser
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Marvin Hagemeister <https://github.com/marvinhagemeister>
// Avi Vahl <https://github.com/AviVahl>
// TypeScript Version: 2.9
/**
* Parse the provided code as an entire ECMAScript program.
*/
declare function parse(
input: string,
options?: ParserOptions
): ParseResult<_babel_types.File>;
/**
* Parse the provided code as a single expression.
*/
declare function parseExpression(
input: string,
options?: ParserOptions
): ParseResult<_babel_types.Expression>;
interface ParserOptions {
/**
* By default, import and export declarations can only appear at a program's top level.
* Setting this option to true allows them anywhere where a statement is allowed.
*/
allowImportExportEverywhere?: boolean;
/**
* By default, await use is not allowed outside of an async function.
* Set this to true to accept such code.
*/
allowAwaitOutsideFunction?: boolean;
/**
* By default, a return statement at the top level raises an error.
* Set this to true to accept such code.
*/
allowReturnOutsideFunction?: boolean;
allowSuperOutsideMethod?: boolean;
/**
* By default, exported identifiers must refer to a declared variable.
* Set this to true to allow export statements to reference undeclared variables.
*/
allowUndeclaredExports?: boolean;
/**
* By default, Babel attaches comments to adjacent AST nodes.
* When this option is set to false, comments are not attached.
* It can provide up to 30% performance improvement when the input code has many comments.
* @babel/eslint-parser will set it for you.
* It is not recommended to use attachComment: false with Babel transform,
* as doing so removes all the comments in output code, and renders annotations such as
* /* istanbul ignore next *\/ nonfunctional.
*/
attachComment?: boolean;
/**
* By default, Babel always throws an error when it finds some invalid code.
* When this option is set to true, it will store the parsing error and
* try to continue parsing the invalid input file.
*/
errorRecovery?: boolean;
/**
* Indicate the mode the code should be parsed in.
* Can be one of "script", "module", or "unambiguous". Defaults to "script".
* "unambiguous" will make @babel/parser attempt to guess, based on the presence
* of ES6 import or export statements.
* Files with ES6 imports and exports are considered "module" and are otherwise "script".
*/
sourceType?: "script" | "module" | "unambiguous";
/**
* Correlate output AST nodes with their source filename.
* Useful when generating code and source maps from the ASTs of multiple input files.
*/
sourceFilename?: string;
/**
* By default, the first line of code parsed is treated as line 1.
* You can provide a line number to alternatively start with.
* Useful for integration with other source tools.
*/
startLine?: number;
/**
* By default, the parsed code is treated as if it starts from line 1, column 0.
* You can provide a column number to alternatively start with.
* Useful for integration with other source tools.
*/
startColumn?: number;
/**
* Array containing the plugins that you want to enable.
*/
plugins?: ParserPlugin[];
/**
* Should the parser work in strict mode.
* Defaults to true if sourceType === 'module'. Otherwise, false.
*/
strictMode?: boolean;
/**
* Adds a ranges property to each node: [node.start, node.end]
*/
ranges?: boolean;
/**
* Adds all parsed tokens to a tokens property on the File node.
*/
tokens?: boolean;
/**
* By default, the parser adds information about parentheses by setting
* `extra.parenthesized` to `true` as needed.
* When this option is `true` the parser creates `ParenthesizedExpression`
* AST nodes instead of using the `extra` property.
*/
createParenthesizedExpressions?: boolean;
}
type ParserPlugin = PluginConfig;
declare const tokTypes: {
// todo(flow->ts) real token type
[name: string]: any;
};
interface ParseError {
code: string;
reasonCode: string;
}
type ParseResult<Result> = Result & {
errors: ParseError[];
};
export { DecoratorsPluginOptions, FlowPluginOptions, ParseError, ParserOptions, ParserPlugin, ParserPluginWithOptions, PipelineOperatorPluginOptions, RecordAndTuplePluginOptions, TypeScriptPluginOptions, parse, parseExpression, tokTypes };

View File

@ -0,0 +1,151 @@
// Type definitions for @babel/parser
// Project: https://github.com/babel/babel/tree/main/packages/babel-parser
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Marvin Hagemeister <https://github.com/marvinhagemeister>
// Avi Vahl <https://github.com/AviVahl>
// TypeScript Version: 2.9
/**
* Parse the provided code as an entire ECMAScript program.
*/
export function parse(
input: string,
options?: ParserOptions
): ParseResult<import("@babel/types").File>;
/**
* Parse the provided code as a single expression.
*/
export function parseExpression(
input: string,
options?: ParserOptions
): ParseResult<import("@babel/types").Expression>;
export interface ParserOptions {
/**
* By default, import and export declarations can only appear at a program's top level.
* Setting this option to true allows them anywhere where a statement is allowed.
*/
allowImportExportEverywhere?: boolean;
/**
* By default, await use is not allowed outside of an async function.
* Set this to true to accept such code.
*/
allowAwaitOutsideFunction?: boolean;
/**
* By default, a return statement at the top level raises an error.
* Set this to true to accept such code.
*/
allowReturnOutsideFunction?: boolean;
allowSuperOutsideMethod?: boolean;
/**
* By default, exported identifiers must refer to a declared variable.
* Set this to true to allow export statements to reference undeclared variables.
*/
allowUndeclaredExports?: boolean;
/**
* By default, Babel attaches comments to adjacent AST nodes.
* When this option is set to false, comments are not attached.
* It can provide up to 30% performance improvement when the input code has many comments.
* @babel/eslint-parser will set it for you.
* It is not recommended to use attachComment: false with Babel transform,
* as doing so removes all the comments in output code, and renders annotations such as
* /* istanbul ignore next *\/ nonfunctional.
*/
attachComment?: boolean;
/**
* By default, Babel always throws an error when it finds some invalid code.
* When this option is set to true, it will store the parsing error and
* try to continue parsing the invalid input file.
*/
errorRecovery?: boolean;
/**
* Indicate the mode the code should be parsed in.
* Can be one of "script", "module", or "unambiguous". Defaults to "script".
* "unambiguous" will make @babel/parser attempt to guess, based on the presence
* of ES6 import or export statements.
* Files with ES6 imports and exports are considered "module" and are otherwise "script".
*/
sourceType?: "script" | "module" | "unambiguous";
/**
* Correlate output AST nodes with their source filename.
* Useful when generating code and source maps from the ASTs of multiple input files.
*/
sourceFilename?: string;
/**
* By default, the first line of code parsed is treated as line 1.
* You can provide a line number to alternatively start with.
* Useful for integration with other source tools.
*/
startLine?: number;
/**
* By default, the parsed code is treated as if it starts from line 1, column 0.
* You can provide a column number to alternatively start with.
* Useful for integration with other source tools.
*/
startColumn?: number;
/**
* Array containing the plugins that you want to enable.
*/
plugins?: ParserPlugin[];
/**
* Should the parser work in strict mode.
* Defaults to true if sourceType === 'module'. Otherwise, false.
*/
strictMode?: boolean;
/**
* Adds a ranges property to each node: [node.start, node.end]
*/
ranges?: boolean;
/**
* Adds all parsed tokens to a tokens property on the File node.
*/
tokens?: boolean;
/**
* By default, the parser adds information about parentheses by setting
* `extra.parenthesized` to `true` as needed.
* When this option is `true` the parser creates `ParenthesizedExpression`
* AST nodes instead of using the `extra` property.
*/
createParenthesizedExpressions?: boolean;
}
export type ParserPlugin = import("../src/typings").PluginConfig;
export type {
ParserPluginWithOptions,
DecoratorsPluginOptions,
PipelineOperatorPluginOptions,
RecordAndTuplePluginOptions,
FlowPluginOptions,
TypeScriptPluginOptions,
} from "../src/typings";
export const tokTypes: {
// todo(flow->ts) real token type
[name: string]: any;
};
export interface ParseError {
code: string;
reasonCode: string;
}
type ParseResult<Result> = Result & {
errors: ParseError[];
};

View File

@ -0,0 +1,19 @@
Copyright Brian White. All rights reserved.
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.

View File

@ -0,0 +1,271 @@
# busboy
<div align="center">
[![Build Status](https://github.com/fastify/busboy/workflows/ci/badge.svg)](https://github.com/fastify/busboy/actions)
[![Coverage Status](https://coveralls.io/repos/fastify/busboy/badge.svg?branch=master)](https://coveralls.io/r/fastify/busboy?branch=master)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
[![Security Responsible Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/nodejs/security-wg/blob/HEAD/processes/responsible_disclosure_template.md)
</div>
<div align="center">
[![NPM version](https://img.shields.io/npm/v/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy)
[![NPM downloads](https://img.shields.io/npm/dm/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy)
</div>
Description
===========
A Node.js module for parsing incoming HTML form data.
This is an officially supported fork by [fastify](https://github.com/fastify/) organization of the amazing library [originally created](https://github.com/mscdex/busboy) by Brian White,
aimed at addressing long-standing issues with it.
Benchmark (Mean time for 500 Kb payload, 2000 cycles, 1000 cycle warmup):
| Library | Version | Mean time in nanoseconds (less is better) |
|-----------------------|---------|-------------------------------------------|
| busboy | 0.3.1 | `340114` |
| @fastify/busboy | 1.0.0 | `270984` |
[Changelog](https://github.com/fastify/busboy/blob/master/CHANGELOG.md) since busboy 0.31.
Requirements
============
* [Node.js](http://nodejs.org/) 10+
Install
=======
npm install @fastify/busboy
Examples
========
* Parsing (multipart) with default options:
```javascript
const http = require('http');
const { inspect } = require('util');
const Busboy = require('busboy');
http.createServer((req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
file.on('data', data => {
console.log(`File [${fieldname}] got ${data.length} bytes`);
});
file.on('end', () => {
console.log(`File [${fieldname}] Finished`);
});
});
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
console.log(`Field [${fieldname}]: value: ${inspect(val)}`);
});
busboy.on('finish', () => {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end(`<html><head></head><body>
<form method="POST" enctype="multipart/form-data">
<input type="text" name="textfield"><br>
<input type="file" name="filefield"><br>
<input type="submit">
</form>
</body></html>`);
}
}).listen(8000, () => {
console.log('Listening for requests');
});
// Example output, using http://nodejs.org/images/ryan-speaker.jpg as the file:
//
// Listening for requests
// File [filefield]: filename: ryan-speaker.jpg, encoding: binary
// File [filefield] got 11971 bytes
// Field [textfield]: value: 'testing! :-)'
// File [filefield] Finished
// Done parsing form!
```
* Save all incoming files to disk:
```javascript
const http = require('http');
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var saveTo = path.join(os.tmpdir(), path.basename(fieldname));
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
return req.pipe(busboy);
}
res.writeHead(404);
res.end();
}).listen(8000, function() {
console.log('Listening for requests');
});
```
* Parsing (urlencoded) with default options:
```javascript
const http = require('http');
const { inspect } = require('util');
const Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST">\
<input type="text" name="textfield"><br />\
<select name="selectfield">\
<option value="1">1</option>\
<option value="10">10</option>\
<option value="100">100</option>\
<option value="9001">9001</option>\
</select><br />\
<input type="checkbox" name="checkfield">Node.js rules!<br />\
<input type="submit">\
</form>\
</body></html>');
}
}).listen(8000, function() {
console.log('Listening for requests');
});
// Example output:
//
// Listening for requests
// Field [textfield]: value: 'testing! :-)'
// Field [selectfield]: value: '9001'
// Field [checkfield]: value: 'on'
// Done parsing form!
```
API
===
_Busboy_ is a _Writable_ stream
Busboy (special) events
-----------------------
* **file**(< _string_ >fieldname, < _ReadableStream_ >stream, < _string_ >filename, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new file form field found. `transferEncoding` contains the 'Content-Transfer-Encoding' value for the file stream. `mimeType` contains the 'Content-Type' value for the file stream.
* Note: if you listen for this event, you should always handle the `stream` no matter if you care about the file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards `files` and `parts` limits).
* If a configured file size limit was reached, `stream` will both have a boolean property `truncated` (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens.
* The property `bytesRead` informs about the number of bytes that have been read so far.
* **field**(< _string_ >fieldname, < _string_ >value, < _boolean_ >fieldnameTruncated, < _boolean_ >valueTruncated, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new non-file field found.
* **partsLimit**() - Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted.
* **filesLimit**() - Emitted when specified `files` limit has been reached. No more 'file' events will be emitted.
* **fieldsLimit**() - Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted.
Busboy methods
--------------
* **(constructor)**(< _object_ >config) - Creates and returns a new Busboy instance.
* The constructor takes the following valid `config` settings:
* **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers.
* **autoDestroy** - _boolean_ - Whether this stream should automatically call .destroy() on itself after ending. (Default: false).
* **highWaterMark** - _integer_ - highWaterMark to use for this Busboy instance (Default: WritableStream default).
* **fileHwm** - _integer_ - highWaterMark to use for file streams (Default: ReadableStream default).
* **defCharset** - _string_ - Default character set to use when one isn't defined (Default: 'utf8').
* **preservePath** - _boolean_ - If paths in the multipart 'filename' field shall be preserved. (Default: false).
* **isPartAFile** - __function__ - Use this function to override the default file detection functionality. It has following parameters:
* fieldName - __string__ The name of the field.
* contentType - __string__ The content-type of the part, e.g. `text/plain`, `image/jpeg`, `application/octet-stream`
* fileName - __string__ The name of a file supplied by the part.
(Default: `(fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)`)
* **limits** - _object_ - Various limits on incoming data. Valid properties are:
* **fieldNameSize** - _integer_ - Max field name size (in bytes) (Default: 100 bytes).
* **fieldSize** - _integer_ - Max field value size (in bytes) (Default: 1 MiB, which is 1024 x 1024 bytes).
* **fields** - _integer_ - Max number of non-file fields (Default: Infinity).
* **fileSize** - _integer_ - For multipart forms, the max file size (in bytes) (Default: Infinity).
* **files** - _integer_ - For multipart forms, the max number of file fields (Default: Infinity).
* **parts** - _integer_ - For multipart forms, the max number of parts (fields + files) (Default: Infinity).
* **headerPairs** - _integer_ - For multipart forms, the max number of header key=>value pairs to parse **Default:** 2000
* **headerSize** - _integer_ - For multipart forms, the max size of a multipart header **Default:** 81920.
* The constructor can throw errors:
* **Busboy expected an options-Object.** - Busboy expected an Object as first parameters.
* **Busboy expected an options-Object with headers-attribute.** - The first parameter is lacking of a headers-attribute.
* **Limit $limit is not a valid number** - Busboy expected the desired limit to be of type number. Busboy throws this Error to prevent a potential security issue by falling silently back to the Busboy-defaults. Potential source for this Error can be the direct use of environment variables without transforming them to the type number.
* **Unsupported Content-Type.** - The `Content-Type` isn't one Busboy can parse.
* **Missing Content-Type-header.** - The provided headers don't include `Content-Type` at all.

View File

@ -0,0 +1,19 @@
Copyright Brian White. All rights reserved.
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.

View File

@ -0,0 +1,205 @@
const WritableStream = require('stream').Writable
const inherits = require('util').inherits
const StreamSearch = require('../../streamsearch/sbmh')
const PartStream = require('./PartStream')
const HeaderParser = require('./HeaderParser')
const DASH = 45
const B_ONEDASH = Buffer.from('-')
const B_CRLF = Buffer.from('\r\n')
const EMPTY_FN = function () {}
function Dicer (cfg) {
if (!(this instanceof Dicer)) { return new Dicer(cfg) }
WritableStream.call(this, cfg)
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
this._headerFirst = cfg.headerFirst
this._dashes = 0
this._parts = 0
this._finished = false
this._realFinish = false
this._isPreamble = true
this._justMatched = false
this._firstWrite = true
this._inHeader = true
this._part = undefined
this._cb = undefined
this._ignoreData = false
this._partOpts = { highWaterMark: cfg.partHwm }
this._pause = false
const self = this
this._hparser = new HeaderParser(cfg)
this._hparser.on('header', function (header) {
self._inHeader = false
self._part.emit('header', header)
})
}
inherits(Dicer, WritableStream)
Dicer.prototype.emit = function (ev) {
if (ev === 'finish' && !this._realFinish) {
if (!this._finished) {
const self = this
process.nextTick(function () {
self.emit('error', new Error('Unexpected end of multipart data'))
if (self._part && !self._ignoreData) {
const type = (self._isPreamble ? 'Preamble' : 'Part')
self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
self._part.push(null)
process.nextTick(function () {
self._realFinish = true
self.emit('finish')
self._realFinish = false
})
return
}
self._realFinish = true
self.emit('finish')
self._realFinish = false
})
}
} else { WritableStream.prototype.emit.apply(this, arguments) }
}
Dicer.prototype._write = function (data, encoding, cb) {
// ignore unexpected data (e.g. extra trailer data after finished)
if (!this._hparser && !this._bparser) { return cb() }
if (this._headerFirst && this._isPreamble) {
if (!this._part) {
this._part = new PartStream(this._partOpts)
if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }
}
const r = this._hparser.push(data)
if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
}
// allows for "easier" testing
if (this._firstWrite) {
this._bparser.push(B_CRLF)
this._firstWrite = false
}
this._bparser.push(data)
if (this._pause) { this._cb = cb } else { cb() }
}
Dicer.prototype.reset = function () {
this._part = undefined
this._bparser = undefined
this._hparser = undefined
}
Dicer.prototype.setBoundary = function (boundary) {
const self = this
this._bparser = new StreamSearch('\r\n--' + boundary)
this._bparser.on('info', function (isMatch, data, start, end) {
self._oninfo(isMatch, data, start, end)
})
}
Dicer.prototype._ignore = function () {
if (this._part && !this._ignoreData) {
this._ignoreData = true
this._part.on('error', EMPTY_FN)
// we must perform some kind of read on the stream even though we are
// ignoring the data, otherwise node's Readable stream will not emit 'end'
// after pushing null to the stream
this._part.resume()
}
}
Dicer.prototype._oninfo = function (isMatch, data, start, end) {
let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
if (!this._part && this._justMatched && data) {
while (this._dashes < 2 && (start + i) < end) {
if (data[start + i] === DASH) {
++i
++this._dashes
} else {
if (this._dashes) { buf = B_ONEDASH }
this._dashes = 0
break
}
}
if (this._dashes === 2) {
if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }
this.reset()
this._finished = true
// no more parts will be added
if (self._parts === 0) {
self._realFinish = true
self.emit('finish')
self._realFinish = false
}
}
if (this._dashes) { return }
}
if (this._justMatched) { this._justMatched = false }
if (!this._part) {
this._part = new PartStream(this._partOpts)
this._part._read = function (n) {
self._unpause()
}
if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part) } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part) } else { this._ignore() }
if (!this._isPreamble) { this._inHeader = true }
}
if (data && start < end && !this._ignoreData) {
if (this._isPreamble || !this._inHeader) {
if (buf) { shouldWriteMore = this._part.push(buf) }
shouldWriteMore = this._part.push(data.slice(start, end))
if (!shouldWriteMore) { this._pause = true }
} else if (!this._isPreamble && this._inHeader) {
if (buf) { this._hparser.push(buf) }
r = this._hparser.push(data.slice(start, end))
if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
}
}
if (isMatch) {
this._hparser.reset()
if (this._isPreamble) { this._isPreamble = false } else {
if (start !== end) {
++this._parts
this._part.on('end', function () {
if (--self._parts === 0) {
if (self._finished) {
self._realFinish = true
self.emit('finish')
self._realFinish = false
} else {
self._unpause()
}
}
})
}
}
this._part.push(null)
this._part = undefined
this._ignoreData = false
this._justMatched = true
this._dashes = 0
}
}
Dicer.prototype._unpause = function () {
if (!this._pause) { return }
this._pause = false
if (this._cb) {
const cb = this._cb
this._cb = undefined
cb()
}
}
module.exports = Dicer

View File

@ -0,0 +1,98 @@
const EventEmitter = require('events').EventEmitter
const inherits = require('util').inherits
const getLimit = require('../../../lib/utils').getLimit
const StreamSearch = require('../../streamsearch/sbmh')
const B_DCRLF = Buffer.from('\r\n\r\n')
const RE_CRLF = /\r\n/g
const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
function HeaderParser (cfg) {
EventEmitter.call(this)
cfg = cfg || {}
const self = this
this.nread = 0
this.maxed = false
this.npairs = 0
this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
this.buffer = ''
this.header = {}
this.finished = false
this.ss = new StreamSearch(B_DCRLF)
this.ss.on('info', function (isMatch, data, start, end) {
if (data && !self.maxed) {
if (self.nread + end - start >= self.maxHeaderSize) {
end = self.maxHeaderSize - self.nread + start
self.nread = self.maxHeaderSize
self.maxed = true
} else { self.nread += (end - start) }
self.buffer += data.toString('binary', start, end)
}
if (isMatch) { self._finish() }
})
}
inherits(HeaderParser, EventEmitter)
HeaderParser.prototype.push = function (data) {
const r = this.ss.push(data)
if (this.finished) { return r }
}
HeaderParser.prototype.reset = function () {
this.finished = false
this.buffer = ''
this.header = {}
this.ss.reset()
}
HeaderParser.prototype._finish = function () {
if (this.buffer) { this._parseHeader() }
this.ss.matches = this.ss.maxMatches
const header = this.header
this.header = {}
this.buffer = ''
this.finished = true
this.nread = this.npairs = 0
this.maxed = false
this.emit('header', header)
}
HeaderParser.prototype._parseHeader = function () {
if (this.npairs === this.maxHeaderPairs) { return }
const lines = this.buffer.split(RE_CRLF)
const len = lines.length
let m, h
for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
if (lines[i].length === 0) { continue }
if (lines[i][0] === '\t' || lines[i][0] === ' ') {
// folded header content
// RFC2822 says to just remove the CRLF and not the whitespace following
// it, so we follow the RFC and include the leading whitespace ...
if (h) {
this.header[h][this.header[h].length - 1] += lines[i]
continue
}
}
const posColon = lines[i].indexOf(':')
if (
posColon === -1 ||
posColon === 0
) {
return
}
m = RE_HDR.exec(lines[i])
h = m[1].toLowerCase()
this.header[h] = this.header[h] || []
this.header[h].push((m[2] || ''))
if (++this.npairs === this.maxHeaderPairs) { break }
}
}
module.exports = HeaderParser

View File

@ -0,0 +1,11 @@
const inherits = require('util').inherits
const ReadableStream = require('stream').Readable
function PartStream (opts) {
ReadableStream.call(this, opts)
}
inherits(PartStream, ReadableStream)
PartStream.prototype._read = function (n) {}
module.exports = PartStream

View File

@ -0,0 +1,164 @@
// Type definitions for dicer 0.2
// Project: https://github.com/mscdex/dicer
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import stream = require("stream");
// tslint:disable:unified-signatures
/**
* A very fast streaming multipart parser for node.js.
* Dicer is a WritableStream
*
* Dicer (special) events:
* - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended.
* - on('part', (stream: PartStream)) - Emitted when a new part has been found.
* - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored).
* - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too).
*/
export class Dicer extends stream.Writable {
/**
* Creates and returns a new Dicer instance with the following valid config settings:
*
* @param config The configuration to use
*/
constructor(config: Dicer.Config);
/**
* Sets the boundary to use for parsing and performs some initialization needed for parsing.
* You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header.
*
* @param boundary The boundary to use
*/
setBoundary(boundary: string): void;
addListener(event: "finish", listener: () => void): this;
addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this;
addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
addListener(event: "trailer", listener: (data: Buffer) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
addListener(event: string, listener: (...args: any[]) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "part", listener: (stream: Dicer.PartStream) => void): this;
on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
on(event: "trailer", listener: (data: Buffer) => void): this;
on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "pipe", listener: (src: stream.Readable) => void): this;
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "part", listener: (stream: Dicer.PartStream) => void): this;
once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
once(event: "trailer", listener: (data: Buffer) => void): this;
once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "pipe", listener: (src: stream.Readable) => void): this;
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "finish", listener: () => void): this;
prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this;
prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
prependListener(event: "trailer", listener: (data: Buffer) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "finish", listener: () => void): this;
prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this;
prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
removeListener(event: "finish", listener: () => void): this;
removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this;
removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this;
removeListener(event: "trailer", listener: (data: Buffer) => void): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "drain", listener: () => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "pipe", listener: (src: stream.Readable) => void): this;
removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
removeListener(event: string, listener: (...args: any[]) => void): this;
}
declare namespace Dicer {
interface Config {
/**
* This is the boundary used to detect the beginning of a new part.
*/
boundary?: string | undefined;
/**
* If true, preamble header parsing will be performed first.
*/
headerFirst?: boolean | undefined;
/**
* The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http).
*/
maxHeaderPairs?: number | undefined;
}
/**
* PartStream is a _ReadableStream_
*
* PartStream (special) events:
* - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values.
*/
interface PartStream extends stream.Readable {
addListener(event: "header", listener: (header: object) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListener(event: "end", listener: () => void): this;
addListener(event: "readable", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: string, listener: (...args: any[]) => void): this;
on(event: "header", listener: (header: object) => void): this;
on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "end", listener: () => void): this;
on(event: "readable", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
once(event: "header", listener: (header: object) => void): this;
once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "end", listener: () => void): this;
once(event: "readable", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "header", listener: (header: object) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "readable", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "header", listener: (header: object) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "readable", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
removeListener(event: "header", listener: (header: object) => void): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "data", listener: (chunk: Buffer | string) => void): this;
removeListener(event: "end", listener: () => void): this;
removeListener(event: "readable", listener: () => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: string, listener: (...args: any[]) => void): this;
}
}

View File

@ -0,0 +1,226 @@
/**
* Copyright Brian White. All rights reserved.
*
* @see https://github.com/mscdex/streamsearch
*
* 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.
*
* Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
* by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
const EventEmitter = require('events').EventEmitter
const inherits = require('util').inherits
function SBMH (needle) {
if (typeof needle === 'string') {
needle = Buffer.from(needle)
}
if (!Buffer.isBuffer(needle)) {
throw new TypeError('The needle has to be a String or a Buffer.')
}
const needleLength = needle.length
if (needleLength === 0) {
throw new Error('The needle cannot be an empty String/Buffer.')
}
if (needleLength > 256) {
throw new Error('The needle cannot have a length bigger than 256.')
}
this.maxMatches = Infinity
this.matches = 0
this._occ = new Array(256)
.fill(needleLength) // Initialize occurrence table.
this._lookbehind_size = 0
this._needle = needle
this._bufpos = 0
this._lookbehind = Buffer.alloc(needleLength)
// Populate occurrence table with analysis of the needle,
// ignoring last letter.
for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
this._occ[needle[i]] = needleLength - 1 - i
}
}
inherits(SBMH, EventEmitter)
SBMH.prototype.reset = function () {
this._lookbehind_size = 0
this.matches = 0
this._bufpos = 0
}
SBMH.prototype.push = function (chunk, pos) {
if (!Buffer.isBuffer(chunk)) {
chunk = Buffer.from(chunk, 'binary')
}
const chlen = chunk.length
this._bufpos = pos || 0
let r
while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
return r
}
SBMH.prototype._sbmh_feed = function (data) {
const len = data.length
const needle = this._needle
const needleLength = needle.length
const lastNeedleChar = needle[needleLength - 1]
// Positive: points to a position in `data`
// pos == 3 points to data[3]
// Negative: points to a position in the lookbehind buffer
// pos == -2 points to lookbehind[lookbehind_size - 2]
let pos = -this._lookbehind_size
let ch
if (pos < 0) {
// Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
// search with character lookup code that considers both the
// lookbehind buffer and the current round's haystack data.
//
// Loop until
// there is a match.
// or until
// we've moved past the position that requires the
// lookbehind buffer. In this case we switch to the
// optimized loop.
// or until
// the character to look at lies outside the haystack.
while (pos < 0 && pos <= len - needleLength) {
ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
if (
ch === lastNeedleChar &&
this._sbmh_memcmp(data, pos, needleLength - 1)
) {
this._lookbehind_size = 0
++this.matches
this.emit('info', true)
return (this._bufpos = pos + needleLength)
}
pos += this._occ[ch]
}
// No match.
if (pos < 0) {
// There's too few data for Boyer-Moore-Horspool to run,
// so let's use a different algorithm to skip as much as
// we can.
// Forward pos until
// the trailing part of lookbehind + data
// looks like the beginning of the needle
// or until
// pos == 0
while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
if (pos >= 0) {
// Discard lookbehind buffer.
this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
this._lookbehind_size = 0
} else {
// Cut off part of the lookbehind buffer that has
// been processed and append the entire haystack
// into it.
const bytesToCutOff = this._lookbehind_size + pos
if (bytesToCutOff > 0) {
// The cut off data is guaranteed not to contain the needle.
this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
}
this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
this._lookbehind_size - bytesToCutOff)
this._lookbehind_size -= bytesToCutOff
data.copy(this._lookbehind, this._lookbehind_size)
this._lookbehind_size += len
this._bufpos = len
return len
}
}
pos += (pos >= 0) * this._bufpos
// Lookbehind buffer is now empty. We only need to check if the
// needle is in the haystack.
if (data.indexOf(needle, pos) !== -1) {
pos = data.indexOf(needle, pos)
++this.matches
if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
return (this._bufpos = pos + needleLength)
} else {
pos = len - needleLength
}
// There was no match. If there's trailing haystack data that we cannot
// match yet using the Boyer-Moore-Horspool algorithm (because the trailing
// data is less than the needle size) then match using a modified
// algorithm that starts matching from the beginning instead of the end.
// Whatever trailing data is left after running this algorithm is added to
// the lookbehind buffer.
while (
pos < len &&
(
data[pos] !== needle[0] ||
(
(Buffer.compare(
data.subarray(pos, pos + len - pos),
needle.subarray(0, len - pos)
) !== 0)
)
)
) {
++pos
}
if (pos < len) {
data.copy(this._lookbehind, 0, pos, pos + (len - pos))
this._lookbehind_size = len - pos
}
// Everything until pos is guaranteed not to contain needle data.
if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
this._bufpos = len
return len
}
SBMH.prototype._sbmh_lookup_char = function (data, pos) {
return (pos < 0)
? this._lookbehind[this._lookbehind_size + pos]
: data[pos]
}
SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
}
return true
}
module.exports = SBMH

View File

@ -0,0 +1,196 @@
// Definitions by: Jacob Baskin <https://github.com/jacobbaskin>
// BendingBender <https://github.com/BendingBender>
// Igor Savin <https://github.com/kibertoad>
/// <reference types="node" />
import * as http from 'http';
import { Readable, Writable } from 'stream';
export { Dicer } from "../deps/dicer/lib/dicer";
export const Busboy: BusboyConstructor;
export default Busboy;
export interface BusboyConfig {
/**
* These are the HTTP headers of the incoming request, which are used by individual parsers.
*/
headers: BusboyHeaders;
/**
* `highWaterMark` to use for this Busboy instance.
* @default WritableStream default.
*/
highWaterMark?: number | undefined;
/**
* highWaterMark to use for file streams.
* @default ReadableStream default.
*/
fileHwm?: number | undefined;
/**
* Default character set to use when one isn't defined.
* @default 'utf8'
*/
defCharset?: string | undefined;
/**
* Detect if a Part is a file.
*
* By default a file is detected if contentType
* is application/octet-stream or fileName is not
* undefined.
*
* Modify this to handle e.g. Blobs.
*/
isPartAFile?: (fieldName: string | undefined, contentType: string | undefined, fileName: string | undefined) => boolean;
/**
* If paths in the multipart 'filename' field shall be preserved.
* @default false
*/
preservePath?: boolean | undefined;
/**
* Various limits on incoming data.
*/
limits?:
| {
/**
* Max field name size (in bytes)
* @default 100 bytes
*/
fieldNameSize?: number | undefined;
/**
* Max field value size (in bytes)
* @default 1MB
*/
fieldSize?: number | undefined;
/**
* Max number of non-file fields
* @default Infinity
*/
fields?: number | undefined;
/**
* For multipart forms, the max file size (in bytes)
* @default Infinity
*/
fileSize?: number | undefined;
/**
* For multipart forms, the max number of file fields
* @default Infinity
*/
files?: number | undefined;
/**
* For multipart forms, the max number of parts (fields + files)
* @default Infinity
*/
parts?: number | undefined;
/**
* For multipart forms, the max number of header key=>value pairs to parse
* @default 2000
*/
headerPairs?: number | undefined;
/**
* For multipart forms, the max size of a header part
* @default 81920
*/
headerSize?: number | undefined;
}
| undefined;
}
export type BusboyHeaders = { 'content-type': string } & http.IncomingHttpHeaders;
export interface BusboyFileStream extends
Readable {
truncated: boolean;
/**
* The number of bytes that have been read so far.
*/
bytesRead: number;
}
export interface Busboy extends Writable {
addListener<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener<Event extends keyof BusboyEvents>(event: Event, listener: BusboyEvents[Event]): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface BusboyEvents {
/**
* Emitted for each new file form field found.
*
* * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the
* file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents),
* otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any**
* incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically
* and safely discarded (these discarded files do still count towards `files` and `parts` limits).
* * If a configured file size limit was reached, `stream` will both have a boolean property `truncated`
* (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens.
*
* @param listener.transferEncoding Contains the 'Content-Transfer-Encoding' value for the file stream.
* @param listener.mimeType Contains the 'Content-Type' value for the file stream.
*/
file: (
fieldname: string,
stream: BusboyFileStream,
filename: string,
transferEncoding: string,
mimeType: string,
) => void;
/**
* Emitted for each new non-file field found.
*/
field: (
fieldname: string,
value: string,
fieldnameTruncated: boolean,
valueTruncated: boolean,
transferEncoding: string,
mimeType: string,
) => void;
finish: () => void;
/**
* Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted.
*/
partsLimit: () => void;
/**
* Emitted when specified `files` limit has been reached. No more 'file' events will be emitted.
*/
filesLimit: () => void;
/**
* Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted.
*/
fieldsLimit: () => void;
error: (error: unknown) => void;
}
export interface BusboyConstructor {
(options: BusboyConfig): Busboy;
new(options: BusboyConfig): Busboy;
}

View File

@ -0,0 +1,83 @@
const WritableStream = require('stream').Writable
const { inherits } = require('util')
const Dicer = require('../deps/dicer/lib/Dicer')
const MultipartParser = require('./types/multipart')
const UrlencodedParser = require('./types/urlencoded')
const parseParams = require('./utils').parseParams
function Busboy (opts) {
if (!(this instanceof Busboy)) { return new Busboy(opts) }
if (typeof opts !== 'object') {
throw new TypeError('Busboy expected an options-Object.')
}
if (typeof opts.headers !== 'object') {
throw new TypeError('Busboy expected an options-Object with headers-attribute.')
}
if (typeof opts.headers['content-type'] !== 'string') {
throw new TypeError('Missing Content-Type-header.')
}
const {
headers,
...streamOptions
} = opts
this.opts = {
autoDestroy: false,
...streamOptions
}
WritableStream.call(this, this.opts)
this._done = false
this._parser = this.getParserByHeaders(headers)
this._finished = false
}
inherits(Busboy, WritableStream)
Busboy.prototype.emit = function (ev) {
if (ev === 'finish') {
if (!this._done) {
this._parser && this._parser.end()
return
} else if (this._finished) {
return
}
this._finished = true
}
WritableStream.prototype.emit.apply(this, arguments)
}
Busboy.prototype.getParserByHeaders = function (headers) {
const parsed = parseParams(headers['content-type'])
const cfg = {
defCharset: this.opts.defCharset,
fileHwm: this.opts.fileHwm,
headers,
highWaterMark: this.opts.highWaterMark,
isPartAFile: this.opts.isPartAFile,
limits: this.opts.limits,
parsedConType: parsed,
preservePath: this.opts.preservePath
}
if (MultipartParser.detect.test(parsed[0])) {
return new MultipartParser(this, cfg)
}
if (UrlencodedParser.detect.test(parsed[0])) {
return new UrlencodedParser(this, cfg)
}
throw new Error('Unsupported Content-Type.')
}
Busboy.prototype._write = function (chunk, encoding, cb) {
this._parser.write(chunk, cb)
}
module.exports = Busboy
module.exports.default = Busboy
module.exports.Busboy = Busboy
module.exports.Dicer = Dicer

View File

@ -0,0 +1,301 @@
// TODO:
// * support 1 nested multipart level
// (see second multipart example here:
// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
// * support limits.fieldNameSize
// -- this will require modifications to utils.parseParams
const ReadableStream = require('stream').Readable
const inherits = require('util').inherits
const Dicer = require('../../deps/dicer/lib/Dicer')
const parseParams = require('../utils').parseParams
const decodeText = require('../utils').decodeText
const basename = require('../utils').basename
const getLimit = require('../utils').getLimit
const RE_BOUNDARY = /^boundary$/i
const RE_FIELD = /^form-data$/i
const RE_CHARSET = /^charset$/i
const RE_FILENAME = /^filename$/i
const RE_NAME = /^name$/i
Multipart.detect = /^multipart\/form-data/i
function Multipart (boy, cfg) {
let i
let len
const self = this
let boundary
const limits = cfg.limits
const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
const parsedConType = cfg.parsedConType || []
const defCharset = cfg.defCharset || 'utf8'
const preservePath = cfg.preservePath
const fileOpts = { highWaterMark: cfg.fileHwm }
for (i = 0, len = parsedConType.length; i < len; ++i) {
if (Array.isArray(parsedConType[i]) &&
RE_BOUNDARY.test(parsedConType[i][0])) {
boundary = parsedConType[i][1]
break
}
}
function checkFinished () {
if (nends === 0 && finished && !boy._done) {
finished = false
process.nextTick(function () {
boy._done = true
boy.emit('finish')
})
}
}
if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
const filesLimit = getLimit(limits, 'files', Infinity)
const fieldsLimit = getLimit(limits, 'fields', Infinity)
const partsLimit = getLimit(limits, 'parts', Infinity)
const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
let nfiles = 0
let nfields = 0
let nends = 0
let curFile
let curField
let finished = false
this._needDrain = false
this._pause = false
this._cb = undefined
this._nparts = 0
this._boy = boy
const parserCfg = {
boundary,
maxHeaderPairs: headerPairsLimit,
maxHeaderSize: headerSizeLimit,
partHwm: fileOpts.highWaterMark,
highWaterMark: cfg.highWaterMark
}
this.parser = new Dicer(parserCfg)
this.parser.on('drain', function () {
self._needDrain = false
if (self._cb && !self._pause) {
const cb = self._cb
self._cb = undefined
cb()
}
}).on('part', function onPart (part) {
if (++self._nparts > partsLimit) {
self.parser.removeListener('part', onPart)
self.parser.on('part', skipPart)
boy.hitPartsLimit = true
boy.emit('partsLimit')
return skipPart(part)
}
// hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
// us emit 'end' early since we know the part has ended if we are already
// seeing the next part
if (curField) {
const field = curField
field.emit('end')
field.removeAllListeners('end')
}
part.on('header', function (header) {
let contype
let fieldname
let parsed
let charset
let encoding
let filename
let nsize = 0
if (header['content-type']) {
parsed = parseParams(header['content-type'][0])
if (parsed[0]) {
contype = parsed[0].toLowerCase()
for (i = 0, len = parsed.length; i < len; ++i) {
if (RE_CHARSET.test(parsed[i][0])) {
charset = parsed[i][1].toLowerCase()
break
}
}
}
}
if (contype === undefined) { contype = 'text/plain' }
if (charset === undefined) { charset = defCharset }
if (header['content-disposition']) {
parsed = parseParams(header['content-disposition'][0])
if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
for (i = 0, len = parsed.length; i < len; ++i) {
if (RE_NAME.test(parsed[i][0])) {
fieldname = parsed[i][1]
} else if (RE_FILENAME.test(parsed[i][0])) {
filename = parsed[i][1]
if (!preservePath) { filename = basename(filename) }
}
}
} else { return skipPart(part) }
if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
let onData,
onEnd
if (isPartAFile(fieldname, contype, filename)) {
// file/binary field
if (nfiles === filesLimit) {
if (!boy.hitFilesLimit) {
boy.hitFilesLimit = true
boy.emit('filesLimit')
}
return skipPart(part)
}
++nfiles
if (!boy._events.file) {
self.parser._ignore()
return
}
++nends
const file = new FileStream(fileOpts)
curFile = file
file.on('end', function () {
--nends
self._pause = false
checkFinished()
if (self._cb && !self._needDrain) {
const cb = self._cb
self._cb = undefined
cb()
}
})
file._read = function (n) {
if (!self._pause) { return }
self._pause = false
if (self._cb && !self._needDrain) {
const cb = self._cb
self._cb = undefined
cb()
}
}
boy.emit('file', fieldname, file, filename, encoding, contype)
onData = function (data) {
if ((nsize += data.length) > fileSizeLimit) {
const extralen = fileSizeLimit - nsize + data.length
if (extralen > 0) { file.push(data.slice(0, extralen)) }
file.truncated = true
file.bytesRead = fileSizeLimit
part.removeAllListeners('data')
file.emit('limit')
return
} else if (!file.push(data)) { self._pause = true }
file.bytesRead = nsize
}
onEnd = function () {
curFile = undefined
file.push(null)
}
} else {
// non-file field
if (nfields === fieldsLimit) {
if (!boy.hitFieldsLimit) {
boy.hitFieldsLimit = true
boy.emit('fieldsLimit')
}
return skipPart(part)
}
++nfields
++nends
let buffer = ''
let truncated = false
curField = part
onData = function (data) {
if ((nsize += data.length) > fieldSizeLimit) {
const extralen = (fieldSizeLimit - (nsize - data.length))
buffer += data.toString('binary', 0, extralen)
truncated = true
part.removeAllListeners('data')
} else { buffer += data.toString('binary') }
}
onEnd = function () {
curField = undefined
if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
--nends
checkFinished()
}
}
/* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
broken. Streams2/streams3 is a huge black box of confusion, but
somehow overriding the sync state seems to fix things again (and still
seems to work for previous node versions).
*/
part._readableState.sync = false
part.on('data', onData)
part.on('end', onEnd)
}).on('error', function (err) {
if (curFile) { curFile.emit('error', err) }
})
}).on('error', function (err) {
boy.emit('error', err)
}).on('finish', function () {
finished = true
checkFinished()
})
}
Multipart.prototype.write = function (chunk, cb) {
let r
if ((r = this.parser.write(chunk)) && !this._pause) { cb() } else {
this._needDrain = !r
this._cb = cb
}
}
Multipart.prototype.end = function () {
const self = this
if (this._nparts === 0 && !self._boy._done) {
process.nextTick(function () {
self._boy._done = true
self._boy.emit('finish')
})
} else if (this.parser.writable) { this.parser.end() }
}
function skipPart (part) {
part.resume()
}
function FileStream (opts) {
ReadableStream.call(this, opts)
this.bytesRead = 0
this.truncated = false
}
inherits(FileStream, ReadableStream)
FileStream.prototype._read = function (n) { }
module.exports = Multipart

View File

@ -0,0 +1,188 @@
const Decoder = require('../utils').Decoder
const decodeText = require('../utils').decodeText
const getLimit = require('../utils').getLimit
const RE_CHARSET = /^charset$/i
UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
function UrlEncoded (boy, cfg) {
const limits = cfg.limits
const parsedConType = cfg.parsedConType
this.boy = boy
this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
this.fieldsLimit = getLimit(limits, 'fields', Infinity)
let charset
for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
if (Array.isArray(parsedConType[i]) &&
RE_CHARSET.test(parsedConType[i][0])) {
charset = parsedConType[i][1].toLowerCase()
break
}
}
if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
this.decoder = new Decoder()
this.charset = charset
this._fields = 0
this._state = 'key'
this._checkingBytes = true
this._bytesKey = 0
this._bytesVal = 0
this._key = ''
this._val = ''
this._keyTrunc = false
this._valTrunc = false
this._hitLimit = false
}
UrlEncoded.prototype.write = function (data, cb) {
if (this._fields === this.fieldsLimit) {
if (!this.boy.hitFieldsLimit) {
this.boy.hitFieldsLimit = true
this.boy.emit('fieldsLimit')
}
return cb()
}
let idxeq; let idxamp; let i; let p = 0; const len = data.length
while (p < len) {
if (this._state === 'key') {
idxeq = idxamp = undefined
for (i = p; i < len; ++i) {
if (!this._checkingBytes) { ++p }
if (data[i] === 0x3D/* = */) {
idxeq = i
break
} else if (data[i] === 0x26/* & */) {
idxamp = i
break
}
if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
this._hitLimit = true
break
} else if (this._checkingBytes) { ++this._bytesKey }
}
if (idxeq !== undefined) {
// key with assignment
if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
this._state = 'val'
this._hitLimit = false
this._checkingBytes = true
this._val = ''
this._bytesVal = 0
this._valTrunc = false
this.decoder.reset()
p = idxeq + 1
} else if (idxamp !== undefined) {
// key with no assignment
++this._fields
let key; const keyTrunc = this._keyTrunc
if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
this._hitLimit = false
this._checkingBytes = true
this._key = ''
this._bytesKey = 0
this._keyTrunc = false
this.decoder.reset()
if (key.length) {
this.boy.emit('field', decodeText(key, 'binary', this.charset),
'',
keyTrunc,
false)
}
p = idxamp + 1
if (this._fields === this.fieldsLimit) { return cb() }
} else if (this._hitLimit) {
// we may not have hit the actual limit if there are encoded bytes...
if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
p = i
if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
// yep, we actually did hit the limit
this._checkingBytes = false
this._keyTrunc = true
}
} else {
if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
p = len
}
} else {
idxamp = undefined
for (i = p; i < len; ++i) {
if (!this._checkingBytes) { ++p }
if (data[i] === 0x26/* & */) {
idxamp = i
break
}
if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
this._hitLimit = true
break
} else if (this._checkingBytes) { ++this._bytesVal }
}
if (idxamp !== undefined) {
++this._fields
if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
decodeText(this._val, 'binary', this.charset),
this._keyTrunc,
this._valTrunc)
this._state = 'key'
this._hitLimit = false
this._checkingBytes = true
this._key = ''
this._bytesKey = 0
this._keyTrunc = false
this.decoder.reset()
p = idxamp + 1
if (this._fields === this.fieldsLimit) { return cb() }
} else if (this._hitLimit) {
// we may not have hit the actual limit if there are encoded bytes...
if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
p = i
if ((this._val === '' && this.fieldSizeLimit === 0) ||
(this._bytesVal = this._val.length) === this.fieldSizeLimit) {
// yep, we actually did hit the limit
this._checkingBytes = false
this._valTrunc = true
}
} else {
if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
p = len
}
}
}
cb()
}
UrlEncoded.prototype.end = function () {
if (this.boy._done) { return }
if (this._state === 'key' && this._key.length > 0) {
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
'',
this._keyTrunc,
false)
} else if (this._state === 'val') {
this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
decodeText(this._val, 'binary', this.charset),
this._keyTrunc,
this._valTrunc)
}
this.boy._done = true
this.boy.emit('finish')
}
module.exports = UrlEncoded

View File

@ -0,0 +1,198 @@
const { TextDecoder } = require('util')
const { TextDecoder: PolyfillTextDecoder, getEncoding } = require('text-decoding')
const RE_ENCODED = /%([a-fA-F0-9]{2})/g
const RE_PLUS = /\+/g
const HEX = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]
// Node has always utf-8
const textDecoders = new Map()
textDecoders.set('utf-8', new TextDecoder('utf-8'))
textDecoders.set('utf8', textDecoders.get('utf-8'))
function encodedReplacer (match, byte) {
return String.fromCharCode(parseInt(byte, 16))
}
function parseParams (str) {
const res = []
let state = 'key'
let charset = ''
let inquote = false
let escaping = false
let p = 0
let tmp = ''
for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var
const char = str[i]
if (char === '\\' && inquote) {
if (escaping) { escaping = false } else {
escaping = true
continue
}
} else if (char === '"') {
if (!escaping) {
if (inquote) {
inquote = false
state = 'key'
} else { inquote = true }
continue
} else { escaping = false }
} else {
if (escaping && inquote) { tmp += '\\' }
escaping = false
if ((state === 'charset' || state === 'lang') && char === "'") {
if (state === 'charset') {
state = 'lang'
charset = tmp.substring(1)
} else { state = 'value' }
tmp = ''
continue
} else if (state === 'key' &&
(char === '*' || char === '=') &&
res.length) {
if (char === '*') { state = 'charset' } else { state = 'value' }
res[p] = [tmp, undefined]
tmp = ''
continue
} else if (!inquote && char === ';') {
state = 'key'
if (charset) {
if (tmp.length) {
tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
'binary',
charset)
}
charset = ''
} else if (tmp.length) {
tmp = decodeText(tmp, 'binary', 'utf8')
}
if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
tmp = ''
++p
continue
} else if (!inquote && (char === ' ' || char === '\t')) { continue }
}
tmp += char
}
if (charset && tmp.length) {
tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
'binary',
charset)
} else if (tmp) {
tmp = decodeText(tmp, 'binary', 'utf8')
}
if (res[p] === undefined) {
if (tmp) { res[p] = tmp }
} else { res[p][1] = tmp }
return res
}
function decodeText (text, textEncoding, destEncoding) {
if (text) {
if (textDecoders.has(destEncoding)) {
try {
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
} else {
try {
textDecoders.set(destEncoding, new TextDecoder(destEncoding))
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) {
if (getEncoding(destEncoding)) {
try {
textDecoders.set(destEncoding, new PolyfillTextDecoder(destEncoding))
return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
} catch (e) { }
}
}
}
}
return text
}
function Decoder () {
this.buffer = undefined
}
Decoder.prototype.write = function (str) {
// Replace '+' with ' ' before decoding
str = str.replace(RE_PLUS, ' ')
let res = ''
let i = 0; let p = 0; const len = str.length
for (; i < len; ++i) {
if (this.buffer !== undefined) {
if (!HEX[str.charCodeAt(i)]) {
res += '%' + this.buffer
this.buffer = undefined
--i // retry character
} else {
this.buffer += str[i]
++p
if (this.buffer.length === 2) {
res += String.fromCharCode(parseInt(this.buffer, 16))
this.buffer = undefined
}
}
} else if (str[i] === '%') {
if (i > p) {
res += str.substring(p, i)
p = i
}
this.buffer = ''
++p
}
}
if (p < len && this.buffer === undefined) { res += str.substring(p) }
return res
}
Decoder.prototype.reset = function () {
this.buffer = undefined
}
function basename (path) {
if (typeof path !== 'string') { return '' }
for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
switch (path.charCodeAt(i)) {
case 0x2F: // '/'
case 0x5C: // '\'
path = path.slice(i + 1)
return (path === '..' || path === '.' ? '' : path)
}
}
return (path === '..' || path === '.' ? '' : path)
}
function getLimit (limits, name, defaultLimit) {
if (
!limits ||
limits[name] === undefined ||
limits[name] === null
) { return defaultLimit }
if (
typeof limits[name] !== 'number' ||
isNaN(limits[name])
) { throw new TypeError('Limit ' + name + ' is not a valid number') }
return limits[name]
}
module.exports = {
Decoder,
basename,
getLimit,
parseParams,
decodeText
}

View File

@ -0,0 +1,92 @@
{
"name": "@fastify/busboy",
"version": "1.1.0",
"private": false,
"author": "Brian White <mscdex@mscdex.net>",
"contributors": [
{
"name": "Igor Savin",
"email": "kibertoad@gmail.com",
"url": "https://github.com/kibertoad"
},
{
"name": "Aras Abbasi",
"email": "aras.abbasi@gmail.com",
"url": "https://github.com/uzlopak"
}
],
"description": "A streaming parser for HTML form data for node.js",
"main": "lib/main",
"types": "lib/main.d.ts",
"scripts": {
"bench:busboy": "cd benchmarks && npm install && npm run benchmark-fastify",
"bench:dicer": "node bench/dicer/dicer-bench-multipart-parser.js",
"coveralls": "nyc report --reporter=lcov",
"lint": "npm run lint:standard",
"lint:everything": "npm run lint && npm run test:types",
"lint:fix": "standard --fix",
"lint:standard": "standard --verbose | snazzy",
"test:mocha": "mocha test",
"test:types": "tsd",
"test:coverage": "nyc npm run test",
"test": "npm run test:mocha"
},
"engines": {
"node": ">=10.17.0"
},
"dependencies": {
"text-decoding": "^1.0.0"
},
"devDependencies": {
"@types/node": "^17.0.0",
"busboy": "^1.0.0",
"chai": "^4.3.4",
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-node": "^11.1.0",
"mocha": "^10.0.0",
"nyc": "^15.1.0",
"photofinish": "^1.8.0",
"snazzy": "^9.0.0",
"standard": "^17.0.0",
"tsd": "^0.20.0",
"typescript": "^4.5.2"
},
"keywords": [
"uploads",
"forms",
"multipart",
"form-data"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/fastify/busboy.git"
},
"tsd": {
"directory": "test/types",
"compilerOptions": {
"esModuleInterop": false,
"module": "commonjs",
"target": "ES2017"
}
},
"standard": {
"globals": [
"describe",
"it"
],
"ignore": [
"bench"
]
},
"files": [
"README.md",
"LICENSE",
"lib/*",
"deps/encoding/*",
"deps/dicer/lib",
"deps/streamsearch/",
"deps/dicer/LICENSE"
]
}

View File

@ -0,0 +1,31 @@
# @firebase/app-types
## 0.8.1
### Patch Changes
- [`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5) [#6682](https://github.com/firebase/firebase-js-sdk/pull/6682) - Upgrade TypeScript to 4.7.4.
## 0.8.0
### Minor Changes
- [`fdd4ab464`](https://github.com/firebase/firebase-js-sdk/commit/fdd4ab464b59a107bdcc195df3f01e32efd89ed4) [#6526](https://github.com/firebase/firebase-js-sdk/pull/6526) - Add functionality to auto-initialize project config and emulator settings from global defaults provided by framework tooling.
## 0.7.0
### Minor Changes
- [`cdada6c68`](https://github.com/firebase/firebase-js-sdk/commit/cdada6c68f9740d13dd6674bcb658e28e68253b6) [#5345](https://github.com/firebase/firebase-js-sdk/pull/5345) (fixes [#5015](https://github.com/firebase/firebase-js-sdk/issues/5015)) - Release modularized SDKs
## 0.6.3
### Patch Changes
- [`3d10d33bc`](https://github.com/firebase/firebase-js-sdk/commit/3d10d33bc167177fecbf86d2a6574af2e4e210f9) [#5144](https://github.com/firebase/firebase-js-sdk/pull/5144) - Add @firebase/logger as a dependency to @firebase/app-types to ensure that it can be resolved when compiling the package in a strict yarn PnP environment.
## 0.6.2
### Patch Changes
- [`f24d8961b`](https://github.com/firebase/firebase-js-sdk/commit/f24d8961b3b87821413297688803fc85113086b3) [#4714](https://github.com/firebase/firebase-js-sdk/pull/4714) - Internal typing changes

View File

@ -0,0 +1,3 @@
# @firebase/app-types
**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.**

View File

@ -0,0 +1,129 @@
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { LogCallback, LogLevelString, LogOptions } from '@firebase/logger';
export type FirebaseOptions = {
apiKey?: string;
authDomain?: string;
databaseURL?: string;
projectId?: string;
storageBucket?: string;
messagingSenderId?: string;
appId?: string;
measurementId?: string;
};
export interface FirebaseAppConfig {
name?: string;
automaticDataCollectionEnabled?: boolean;
}
export class FirebaseApp {
/**
* The (read-only) name (identifier) for this App. '[DEFAULT]' is the default
* App.
*/
name: string;
/**
* The (read-only) configuration options from the app initialization.
*/
options: FirebaseOptions;
/**
* The settable config flag for GDPR opt-in/opt-out
*/
automaticDataCollectionEnabled: boolean;
/**
* Make the given App unusable and free resources.
*/
delete(): Promise<void>;
}
export interface FirebaseNamespace {
/**
* Create (and initialize) a FirebaseApp.
*
* @param options Options to configure the services used in the App.
* @param config The optional config for your firebase app
*/
initializeApp(
options: FirebaseOptions,
config?: FirebaseAppConfig
): FirebaseApp;
/**
* Create (and initialize) a FirebaseApp.
*
* @param options Options to configure the services used in the App.
* @param name The optional name of the app to initialize ('[DEFAULT]' if
* omitted)
*/
initializeApp(options: FirebaseOptions, name?: string): FirebaseApp;
app: {
/**
* Retrieve an instance of a FirebaseApp.
*
* Usage: firebase.app()
*
* @param name The optional name of the app to return ('[DEFAULT]' if omitted)
*/
(name?: string): FirebaseApp;
/**
* For testing FirebaseApp instances:
* app() instanceof firebase.app.App
*
* DO NOT call this constuctor directly (use firebase.app() instead).
*/
App: typeof FirebaseApp;
};
/**
* A (read-only) array of all the initialized Apps.
*/
apps: FirebaseApp[];
/**
* Registers a library's name and version for platform logging purposes.
* @param library Name of 1p or 3p library (e.g. firestore, angularfire)
* @param version Current version of that library.
*/
registerVersion(library: string, version: string, variant?: string): void;
// Sets log level for all Firebase components.
setLogLevel(logLevel: LogLevelString): void;
// Sets log handler for all Firebase components.
onLog(logCallback: LogCallback, options?: LogOptions): void;
// The current SDK version.
SDK_VERSION: string;
}
export interface VersionService {
library: string;
version: string;
}
declare module '@firebase/component' {
interface NameServiceMapping {
'app-version': VersionService;
'platform-identifier': VersionService;
}
}

View File

@ -0,0 +1,29 @@
{
"name": "@firebase/app-types",
"version": "0.8.1",
"description": "@firebase/app Types",
"author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)",
"license": "Apache-2.0",
"scripts": {
"test": "tsc",
"test:ci": "node ../../scripts/run_tests_in_ci.js"
},
"files": [
"index.d.ts",
"private.d.ts"
],
"repository": {
"directory": "packages/app-types",
"type": "git",
"url": "https://github.com/firebase/firebase-js-sdk.git"
},
"bugs": {
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"dependency": {
"@firebase/logger": "0.2.6"
},
"devDependencies": {
"typescript": "4.2.2"
}
}

View File

@ -0,0 +1,165 @@
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* THIS FILE IS FOR INTERNAL USAGE ONLY, IF YOU ARE NOT DEVELOPING THE FIREBASE
* SDKs, PLEASE DO NOT REFERENCE THIS FILE AS IT MAY CHANGE WITHOUT WARNING
*/
import { FirebaseApp, FirebaseNamespace } from '@firebase/app-types';
import { Observer, Subscribe } from '@firebase/util';
import { FirebaseError, ErrorFactory } from '@firebase/util';
import { Component, ComponentContainer, Name } from '@firebase/component';
export interface FirebaseServiceInternals {
/**
* Delete the service and free it's resources - called from
* app.delete().
*/
delete(): Promise<void>;
}
// Services are exposed through instances - each of which is associated with a
// FirebaseApp.
export interface FirebaseService {
app: FirebaseApp;
INTERNAL?: FirebaseServiceInternals;
}
export type AppHook = (event: string, app: FirebaseApp) => void;
/**
* Firebase Services create instances given a Firebase App instance and can
* optionally add properties and methods to each FirebaseApp via the extendApp()
* function.
*/
export interface FirebaseServiceFactory {
(
app: FirebaseApp,
extendApp?: (props: { [prop: string]: any }) => void,
instanceString?: string
): FirebaseService;
}
export interface PlatformLoggerService {
getPlatformInfoString(): string;
}
/**
* All ServiceNamespaces extend from FirebaseServiceNamespace
*/
export interface FirebaseServiceNamespace<T extends FirebaseService> {
(app?: FirebaseApp): T;
}
export interface FirebaseAuthTokenData {
accessToken: string;
}
export interface FirebaseAppInternals {
getToken(refreshToken?: boolean): Promise<FirebaseAuthTokenData | null>;
getUid(): string | null;
addAuthTokenListener(fn: (token: string | null) => void): void;
removeAuthTokenListener(fn: (token: string | null) => void): void;
analytics: {
logEvent: (
eventName: string,
eventParams: { [key: string]: any },
options?: { global: boolean }
) => void;
};
}
export interface _FirebaseApp extends FirebaseApp {
container: ComponentContainer;
_addComponent<T extends Name>(component: Component<T>): void;
_addOrOverwriteComponent<T extends Name>(component: Component<T>): void;
_removeServiceInstance(name: string, instanceIdentifier?: string): void;
}
export interface _FirebaseNamespace extends FirebaseNamespace {
INTERNAL: {
/**
* Internal API to register a Firebase Service into the firebase namespace.
*
* Each service will create a child namespace (firebase.<name>) which acts as
* both a namespace for service specific properties, and also as a service
* accessor function (firebase.<name>() or firebase.<name>(app)).
*
* @param name The Firebase Service being registered.
* @param createService Factory function to create a service instance.
* @param serviceProperties Properties to copy to the service's namespace.
* @param appHook All appHooks called before initializeApp returns to caller.
* @param allowMultipleInstances Whether the registered service supports
* multiple instances per app. If not specified, the default is false.
*/
registerComponent<T extends Name>(
component: Component<T>
): FirebaseServiceNamespace<FirebaseService> | null;
/**
* Just used for testing to start from a fresh namespace.
*/
createFirebaseNamespace(): FirebaseNamespace;
/**
* Internal API to install properties on the top-level firebase namespace.
* @prop props The top level properties of this object are copied to the
* namespace.
*/
extendNamespace(props: { [prop: string]: any }): void;
/**
* Create a Subscribe function. A proxy Observer is created so that
* events can be sent to single Observer to be fanned out automatically.
*/
createSubscribe<T>(
executor: (observer: Observer<T>) => void,
onNoObservers?: (observer: Observer<T>) => void
): Subscribe<T>;
/**
* Utility exposed for internal testing.
*/
deepExtend(target: any, source: any): any;
/**
* Internal API to remove an app from the list of registered apps.
*/
removeApp(name: string): void;
/**
* registered components.
*/
components: Map<string, Component>;
/*
* Convert service name to factory name to use.
*/
useAsService(app: FirebaseApp, serviceName: string): string | null;
/**
* Use to construct all thrown FirebaseError's.
*/
ErrorFactory: typeof ErrorFactory;
};
}
declare module '@firebase/component' {
interface NameServiceMapping {
'platform-logger': PlatformLoggerService;
}
}

View File

@ -0,0 +1,13 @@
# @firebase/auth-interop-types
## 0.1.7
### Patch Changes
- [`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5) [#6682](https://github.com/firebase/firebase-js-sdk/pull/6682) - Upgrade TypeScript to 4.7.4.
## 0.1.6
### Patch Changes
- [`3f370215a`](https://github.com/firebase/firebase-js-sdk/commit/3f370215aa571db6b41b92a7d8a9aaad2ea0ecd0) [#4808](https://github.com/firebase/firebase-js-sdk/pull/4808) (fixes [#4789](https://github.com/firebase/firebase-js-sdk/issues/4789)) - Update peerDependencies

View File

@ -0,0 +1,3 @@
# @firebase/auth-interop-types
**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.**

View File

@ -0,0 +1,35 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface FirebaseAuthTokenData {
accessToken: string;
}
export interface FirebaseAuthInternal {
getToken(refreshToken?: boolean): Promise<FirebaseAuthTokenData | null>;
getUid(): string | null;
addAuthTokenListener(fn: (token: string | null) => void): void;
removeAuthTokenListener(fn: (token: string | null) => void): void;
}
export type FirebaseAuthInternalName = 'auth-internal';
declare module '@firebase/component' {
interface NameServiceMapping {
'auth-internal': FirebaseAuthInternal;
}
}

View File

@ -0,0 +1,29 @@
{
"name": "@firebase/auth-interop-types",
"version": "0.1.7",
"description": "@firebase/auth interop Types",
"author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)",
"license": "Apache-2.0",
"scripts": {
"test": "tsc",
"test:ci": "node ../../scripts/run_tests_in_ci.js"
},
"files": [
"index.d.ts"
],
"peerDependencies": {
"@firebase/app-types": "0.x",
"@firebase/util": "1.x"
},
"repository": {
"directory": "packages/auth-types",
"type": "git",
"url": "https://github.com/firebase/firebase-js-sdk.git"
},
"bugs": {
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"devDependencies": {
"typescript": "4.2.2"
}
}

View File

@ -0,0 +1,261 @@
# @firebase/component
## 0.5.21
### Patch Changes
- [`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5) [#6682](https://github.com/firebase/firebase-js-sdk/pull/6682) - Upgrade TypeScript to 4.7.4.
- Updated dependencies [[`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5)]:
- @firebase/util@1.7.3
## 0.5.20
### Patch Changes
- Updated dependencies [[`807f06aa2`](https://github.com/firebase/firebase-js-sdk/commit/807f06aa26438a91aaea08fd38efb6c706bb8a5d)]:
- @firebase/util@1.7.2
## 0.5.19
### Patch Changes
- Updated dependencies [[`171b78b76`](https://github.com/firebase/firebase-js-sdk/commit/171b78b762826a640d267dd4dd172ad9459c4561), [`29d034072`](https://github.com/firebase/firebase-js-sdk/commit/29d034072c20af394ce384e42aa10a37d5dfcb18)]:
- @firebase/util@1.7.1
## 0.5.18
### Patch Changes
- Updated dependencies [[`fdd4ab464`](https://github.com/firebase/firebase-js-sdk/commit/fdd4ab464b59a107bdcc195df3f01e32efd89ed4)]:
- @firebase/util@1.7.0
## 0.5.17
### Patch Changes
- Updated dependencies [[`b12af44a5`](https://github.com/firebase/firebase-js-sdk/commit/b12af44a5c7500e1192d6cc1a4afc4d77efadbaf)]:
- @firebase/util@1.6.3
## 0.5.16
### Patch Changes
- Updated dependencies [[`efe2000fc`](https://github.com/firebase/firebase-js-sdk/commit/efe2000fc499e2c85c4e5e0fef6741ff3bad2eb0)]:
- @firebase/util@1.6.2
## 0.5.15
### Patch Changes
- [`2cd1cc76f`](https://github.com/firebase/firebase-js-sdk/commit/2cd1cc76f2a308135cd60f424fe09084a34b5cb5) [#6307](https://github.com/firebase/firebase-js-sdk/pull/6307) (fixes [#6300](https://github.com/firebase/firebase-js-sdk/issues/6300)) - fix: add type declarations to exports field
- Updated dependencies [[`2cd1cc76f`](https://github.com/firebase/firebase-js-sdk/commit/2cd1cc76f2a308135cd60f424fe09084a34b5cb5)]:
- @firebase/util@1.6.1
## 0.5.14
### Patch Changes
- Updated dependencies [[`9c5c9c36d`](https://github.com/firebase/firebase-js-sdk/commit/9c5c9c36da80b98b73cfd60ef2e2965087e9f801)]:
- @firebase/util@1.6.0
## 0.5.13
### Patch Changes
- Updated dependencies [[`e9e5f6b3c`](https://github.com/firebase/firebase-js-sdk/commit/e9e5f6b3ca9d61323b22f87986d9959f5297ec59)]:
- @firebase/util@1.5.2
## 0.5.12
### Patch Changes
- Updated dependencies [[`3198d58dc`](https://github.com/firebase/firebase-js-sdk/commit/3198d58dcedbf7583914dbcc76984f6f7df8d2ef)]:
- @firebase/util@1.5.1
## 0.5.11
### Patch Changes
- Updated dependencies [[`2d672cead`](https://github.com/firebase/firebase-js-sdk/commit/2d672cead167187cb714cd89b638c0884ba58f03)]:
- @firebase/util@1.5.0
## 0.5.10
### Patch Changes
- Updated dependencies [[`3b481f572`](https://github.com/firebase/firebase-js-sdk/commit/3b481f572456e1eab3435bfc25717770d95a8c49)]:
- @firebase/util@1.4.3
## 0.5.9
### Patch Changes
- [`3281315fa`](https://github.com/firebase/firebase-js-sdk/commit/3281315fae9c6f535f9d5052ee17d60861ea569a) [#5708](https://github.com/firebase/firebase-js-sdk/pull/5708) (fixes [#1487](https://github.com/firebase/firebase-js-sdk/issues/1487)) - Update build scripts to work with the exports field
- Updated dependencies [[`3281315fa`](https://github.com/firebase/firebase-js-sdk/commit/3281315fae9c6f535f9d5052ee17d60861ea569a)]:
- @firebase/util@1.4.2
## 0.5.8
### Patch Changes
- [`2322b6023`](https://github.com/firebase/firebase-js-sdk/commit/2322b6023c628cd9f4f4172767c17d215dd91684) [#5693](https://github.com/firebase/firebase-js-sdk/pull/5693) - Add exports field to all packages
- Updated dependencies [[`2322b6023`](https://github.com/firebase/firebase-js-sdk/commit/2322b6023c628cd9f4f4172767c17d215dd91684)]:
- @firebase/util@1.4.1
## 0.5.7
### Patch Changes
- Updated dependencies [[`a99943fe3`](https://github.com/firebase/firebase-js-sdk/commit/a99943fe3bd5279761aa29d138ec91272b06df39), [`b835b4cba`](https://github.com/firebase/firebase-js-sdk/commit/b835b4cbabc4b7b180ae38b908c49205ce31a422)]:
- @firebase/util@1.4.0
## 0.5.6
### Patch Changes
- [`bb6b5abff`](https://github.com/firebase/firebase-js-sdk/commit/bb6b5abff6f89ce9ec1bd66ff4e795a059a98eec) [#5272](https://github.com/firebase/firebase-js-sdk/pull/5272) - Store instance initialization options on the Provider.
- Updated dependencies [[`3c6a11c8d`](https://github.com/firebase/firebase-js-sdk/commit/3c6a11c8d0b35afddb50e9c3e0c4d2e30f642131)]:
- @firebase/util@1.3.0
## 0.5.5
### Patch Changes
- Updated dependencies [[`a3cbe719b`](https://github.com/firebase/firebase-js-sdk/commit/a3cbe719b1bd733a5c4c15ee0d0e6388d512054c)]:
- @firebase/util@1.2.0
## 0.5.4
### Patch Changes
- [`56a6a9d4a`](https://github.com/firebase/firebase-js-sdk/commit/56a6a9d4af2766154584a0f66d3c4d8024d74ba5) [#5071](https://github.com/firebase/firebase-js-sdk/pull/5071) (fixes [#4932](https://github.com/firebase/firebase-js-sdk/issues/4932)) - Auto initialize `auth-internal` after `auth` has been initialized.
## 0.5.3
### Patch Changes
- [`725ab4684`](https://github.com/firebase/firebase-js-sdk/commit/725ab4684ef0999a12f71e704c204a00fb030e5d) [#5023](https://github.com/firebase/firebase-js-sdk/pull/5023) (fixes [#5018](https://github.com/firebase/firebase-js-sdk/issues/5018)) - Pass the instance to onInit callback
## 0.5.2
### Patch Changes
- [`4c4b6aed9`](https://github.com/firebase/firebase-js-sdk/commit/4c4b6aed9757c9a7e75fb698a15e53274f93880b) [#4971](https://github.com/firebase/firebase-js-sdk/pull/4971) - Fixes a regression that prevented Firestore from detecting Auth during its initial initialization, which could cause some writes to not be send.
## 0.5.1
### Patch Changes
- [`5fbc5fb01`](https://github.com/firebase/firebase-js-sdk/commit/5fbc5fb0140d7da980fd7ebbfbae810f8c64ae19) [#4911](https://github.com/firebase/firebase-js-sdk/pull/4911) - handle `undefined` correctly from input.
## 0.5.0
### Minor Changes
- [`c34ac7a92`](https://github.com/firebase/firebase-js-sdk/commit/c34ac7a92a616915f38d192654db7770d81747ae) [#4866](https://github.com/firebase/firebase-js-sdk/pull/4866) - Support onInit callback in provider
### Patch Changes
- Updated dependencies [[`ac4ad08a2`](https://github.com/firebase/firebase-js-sdk/commit/ac4ad08a284397ec966e991dd388bb1fba857467)]:
- @firebase/util@1.1.0
## 0.4.1
### Patch Changes
- Updated dependencies [[`7354a0ed4`](https://github.com/firebase/firebase-js-sdk/commit/7354a0ed438f4e3df6577e4927e8c8f8f1fbbfda)]:
- @firebase/util@1.0.0
## 0.4.0
### Minor Changes
- [`f24d8961b`](https://github.com/firebase/firebase-js-sdk/commit/f24d8961b3b87821413297688803fc85113086b3) [#4714](https://github.com/firebase/firebase-js-sdk/pull/4714) - Support new instantiation mode `EXPLICIT`
## 0.3.1
### Patch Changes
- Updated dependencies [[`de5f90501`](https://github.com/firebase/firebase-js-sdk/commit/de5f9050137acc9ed1490082e5aa429b5de3cb2a)]:
- @firebase/util@0.4.1
## 0.3.0
### Minor Changes
- [`5c1a83ed7`](https://github.com/firebase/firebase-js-sdk/commit/5c1a83ed70bae979322bd8751c0885d683ce4bf3) [#4595](https://github.com/firebase/firebase-js-sdk/pull/4595) - Component facotry now takes an options object. And added `Provider.initialize()` that can be used to pass an options object to the component factory.
## 0.2.1
### Patch Changes
- Updated dependencies [[`ec95df3d0`](https://github.com/firebase/firebase-js-sdk/commit/ec95df3d07e5f091f2a7f7327e46417f64d04b4e)]:
- @firebase/util@0.4.0
## 0.2.0
### Minor Changes
- [`6afe42613`](https://github.com/firebase/firebase-js-sdk/commit/6afe42613ed3d7a842d378dc1a09a795811db2ac) [#4495](https://github.com/firebase/firebase-js-sdk/pull/4495) - Added isInitialized() method to Provider
## 0.1.21
### Patch Changes
- Updated dependencies [[`9cf727fcc`](https://github.com/firebase/firebase-js-sdk/commit/9cf727fcc3d049551b16ae0698ac33dc2fe45ada)]:
- @firebase/util@0.3.4
## 0.1.20
### Patch Changes
- [`a5768b0aa`](https://github.com/firebase/firebase-js-sdk/commit/a5768b0aa7d7ce732279931aa436e988c9f36487) [#3932](https://github.com/firebase/firebase-js-sdk/pull/3932) - Point browser field to esm build. Now you need to use default import instead of namespace import to import firebase.
Before this change
```
import * as firebase from 'firebase/app';
```
After this change
```
import firebase from 'firebase/app';
```
- Updated dependencies [[`a5768b0aa`](https://github.com/firebase/firebase-js-sdk/commit/a5768b0aa7d7ce732279931aa436e988c9f36487), [`7d916d905`](https://github.com/firebase/firebase-js-sdk/commit/7d916d905ba16816ac8ac7c8748c83831ff614ce)]:
- @firebase/util@0.3.3
## 0.1.19
### Patch Changes
- [`da1c7df79`](https://github.com/firebase/firebase-js-sdk/commit/da1c7df7982b08bbef82fcc8d93255f3e2d23cca) [#3601](https://github.com/firebase/firebase-js-sdk/pull/3601) - Correctly delete services created by modular SDKs when calling provider.delete()
- Updated dependencies [[`fb3b095e4`](https://github.com/firebase/firebase-js-sdk/commit/fb3b095e4b7c8f57fdb3172bc039c84576abf290)]:
- @firebase/util@0.3.2
## 0.1.18
### Patch Changes
- Updated dependencies [[`d4ca3da0`](https://github.com/firebase/firebase-js-sdk/commit/d4ca3da0a59fcea1261ba69d7eb663bba38d3089)]:
- @firebase/util@0.3.1
## 0.1.17
### Patch Changes
- Updated dependencies [[`a87676b8`](https://github.com/firebase/firebase-js-sdk/commit/a87676b84b78ccc2f057a22eb947a5d13402949c)]:
- @firebase/util@0.3.0
## 0.1.16
### Patch Changes
- [`a754645e`](https://github.com/firebase/firebase-js-sdk/commit/a754645ec2be1b8c205f25f510196eee298b0d6e) [#3297](https://github.com/firebase/firebase-js-sdk/pull/3297) Thanks [@renovate](https://github.com/apps/renovate)! - Update dependency typescript to v3.9.5

View File

@ -0,0 +1,12 @@
# @firebase/component
_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a
member of the Firebase team, please avoid using this package_
## Usage
**ES Modules**
```javascript
import { Component } from '@firebase/component';
```

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Component } from './src/component';
export { ComponentContainer } from './src/component_container';
export { Provider } from './src/provider';
export { ComponentType, InstanceFactory, InstantiationMode, NameServiceMapping, Name, InstanceFactoryOptions } from './src/types';

View File

@ -0,0 +1,409 @@
import { Deferred } from '@firebase/util';
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
class Component {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = "LAZY" /* LAZY */;
this.onInstanceCreated = null;
}
setInstantiationMode(mode) {
this.instantiationMode = mode;
return this;
}
setMultipleInstances(multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
}
setServiceProps(props) {
this.serviceProps = props;
return this;
}
setInstanceCreatedCallback(callback) {
this.onInstanceCreated = callback;
return this;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DEFAULT_ENTRY_NAME = '[DEFAULT]';
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
class Provider {
constructor(name, container) {
this.name = name;
this.container = container;
this.component = null;
this.instances = new Map();
this.instancesDeferred = new Map();
this.instancesOptions = new Map();
this.onInitCallbacks = new Map();
}
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
get(identifier) {
// if multipleInstances is not supported, use the default name
const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
if (!this.instancesDeferred.has(normalizedIdentifier)) {
const deferred = new Deferred();
this.instancesDeferred.set(normalizedIdentifier, deferred);
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
// initialize the service if it can be auto-initialized
try {
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
if (instance) {
deferred.resolve(instance);
}
}
catch (e) {
// when the instance factory throws an exception during get(), it should not cause
// a fatal error. We just return the unresolved promise in this case.
}
}
}
return this.instancesDeferred.get(normalizedIdentifier).promise;
}
getImmediate(options) {
var _a;
// if multipleInstances is not supported, use the default name
const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
try {
return this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
}
catch (e) {
if (optional) {
return null;
}
else {
throw e;
}
}
}
else {
// In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw
if (optional) {
return null;
}
else {
throw Error(`Service ${this.name} is not available`);
}
}
}
getComponent() {
return this.component;
}
setComponent(component) {
if (component.name !== this.name) {
throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
}
if (this.component) {
throw Error(`Component for ${this.name} has already been provided`);
}
this.component = component;
// return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
if (!this.shouldAutoInitialize()) {
return;
}
// if the service is eager, initialize the default instance
if (isComponentEager(component)) {
try {
this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });
}
catch (e) {
// when the instance factory for an eager Component throws an exception during the eager
// initialization, it should not cause a fatal error.
// TODO: Investigate if we need to make it configurable, because some component may want to cause
// a fatal error in this case?
}
}
// Create service instances for the pending promises and resolve them
// NOTE: if this.multipleInstances is false, only the default instance will be created
// and all promises with resolve with it regardless of the identifier.
for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
try {
// `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
instanceDeferred.resolve(instance);
}
catch (e) {
// when the instance factory throws an exception, it should not cause
// a fatal error. We just leave the promise unresolved.
}
}
}
clearInstance(identifier = DEFAULT_ENTRY_NAME) {
this.instancesDeferred.delete(identifier);
this.instancesOptions.delete(identifier);
this.instances.delete(identifier);
}
// app.delete() will call this method on every provider to delete the services
// TODO: should we mark the provider as deleted?
async delete() {
const services = Array.from(this.instances.values());
await Promise.all([
...services
.filter(service => 'INTERNAL' in service) // legacy services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(service => service.INTERNAL.delete()),
...services
.filter(service => '_delete' in service) // modularized services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(service => service._delete())
]);
}
isComponentSet() {
return this.component != null;
}
isInitialized(identifier = DEFAULT_ENTRY_NAME) {
return this.instances.has(identifier);
}
getOptions(identifier = DEFAULT_ENTRY_NAME) {
return this.instancesOptions.get(identifier) || {};
}
initialize(opts = {}) {
const { options = {} } = opts;
const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
if (this.isInitialized(normalizedIdentifier)) {
throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
}
if (!this.isComponentSet()) {
throw Error(`Component ${this.name} has not been registered yet`);
}
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
options
});
// resolve any pending promise waiting for the service instance
for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
if (normalizedIdentifier === normalizedDeferredIdentifier) {
instanceDeferred.resolve(instance);
}
}
return instance;
}
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
onInit(callback, identifier) {
var _a;
const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();
existingCallbacks.add(callback);
this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
const existingInstance = this.instances.get(normalizedIdentifier);
if (existingInstance) {
callback(existingInstance, normalizedIdentifier);
}
return () => {
existingCallbacks.delete(callback);
};
}
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
invokeOnInitCallbacks(instance, identifier) {
const callbacks = this.onInitCallbacks.get(identifier);
if (!callbacks) {
return;
}
for (const callback of callbacks) {
try {
callback(instance, identifier);
}
catch (_a) {
// ignore errors in the onInit callback
}
}
}
getOrInitializeService({ instanceIdentifier, options = {} }) {
let instance = this.instances.get(instanceIdentifier);
if (!instance && this.component) {
instance = this.component.instanceFactory(this.container, {
instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
options
});
this.instances.set(instanceIdentifier, instance);
this.instancesOptions.set(instanceIdentifier, options);
/**
* Invoke onInit listeners.
* Note this.component.onInstanceCreated is different, which is used by the component creator,
* while onInit listeners are registered by consumers of the provider.
*/
this.invokeOnInitCallbacks(instance, instanceIdentifier);
/**
* Order is important
* onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
* makes `isInitialized()` return true.
*/
if (this.component.onInstanceCreated) {
try {
this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
}
catch (_a) {
// ignore errors in the onInstanceCreatedCallback
}
}
}
return instance || null;
}
normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {
if (this.component) {
return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;
}
else {
return identifier; // assume multiple instances are supported before the component is provided.
}
}
shouldAutoInitialize() {
return (!!this.component &&
this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */);
}
}
// undefined should be passed to the service factory for the default instance
function normalizeIdentifierForFactory(identifier) {
return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;
}
function isComponentEager(component) {
return component.instantiationMode === "EAGER" /* EAGER */;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
class ComponentContainer {
constructor(name) {
this.name = name;
this.providers = new Map();
}
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
addComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
}
provider.setComponent(component);
}
addOrOverwriteComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
// delete the existing provider from the container, so we can register the new component
this.providers.delete(component.name);
}
this.addComponent(component);
}
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
getProvider(name) {
if (this.providers.has(name)) {
return this.providers.get(name);
}
// create a Provider for a service that hasn't registered with Firebase
const provider = new Provider(name, this);
this.providers.set(name, provider);
return provider;
}
getProviders() {
return Array.from(this.providers.values());
}
}
export { Component, ComponentContainer, Provider };
//# sourceMappingURL=index.esm2017.js.map

View File

@ -0,0 +1,460 @@
import { __values, __read, __awaiter, __generator, __spreadArray } from 'tslib';
import { Deferred } from '@firebase/util';
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
var Component = /** @class */ (function () {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
function Component(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = "LAZY" /* LAZY */;
this.onInstanceCreated = null;
}
Component.prototype.setInstantiationMode = function (mode) {
this.instantiationMode = mode;
return this;
};
Component.prototype.setMultipleInstances = function (multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
};
Component.prototype.setServiceProps = function (props) {
this.serviceProps = props;
return this;
};
Component.prototype.setInstanceCreatedCallback = function (callback) {
this.onInstanceCreated = callback;
return this;
};
return Component;
}());
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_ENTRY_NAME = '[DEFAULT]';
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
var Provider = /** @class */ (function () {
function Provider(name, container) {
this.name = name;
this.container = container;
this.component = null;
this.instances = new Map();
this.instancesDeferred = new Map();
this.instancesOptions = new Map();
this.onInitCallbacks = new Map();
}
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
Provider.prototype.get = function (identifier) {
// if multipleInstances is not supported, use the default name
var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
if (!this.instancesDeferred.has(normalizedIdentifier)) {
var deferred = new Deferred();
this.instancesDeferred.set(normalizedIdentifier, deferred);
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
// initialize the service if it can be auto-initialized
try {
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
if (instance) {
deferred.resolve(instance);
}
}
catch (e) {
// when the instance factory throws an exception during get(), it should not cause
// a fatal error. We just return the unresolved promise in this case.
}
}
}
return this.instancesDeferred.get(normalizedIdentifier).promise;
};
Provider.prototype.getImmediate = function (options) {
var _a;
// if multipleInstances is not supported, use the default name
var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
var optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
try {
return this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
}
catch (e) {
if (optional) {
return null;
}
else {
throw e;
}
}
}
else {
// In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw
if (optional) {
return null;
}
else {
throw Error("Service " + this.name + " is not available");
}
}
};
Provider.prototype.getComponent = function () {
return this.component;
};
Provider.prototype.setComponent = function (component) {
var e_1, _a;
if (component.name !== this.name) {
throw Error("Mismatching Component " + component.name + " for Provider " + this.name + ".");
}
if (this.component) {
throw Error("Component for " + this.name + " has already been provided");
}
this.component = component;
// return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
if (!this.shouldAutoInitialize()) {
return;
}
// if the service is eager, initialize the default instance
if (isComponentEager(component)) {
try {
this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });
}
catch (e) {
// when the instance factory for an eager Component throws an exception during the eager
// initialization, it should not cause a fatal error.
// TODO: Investigate if we need to make it configurable, because some component may want to cause
// a fatal error in this case?
}
}
try {
// Create service instances for the pending promises and resolve them
// NOTE: if this.multipleInstances is false, only the default instance will be created
// and all promises with resolve with it regardless of the identifier.
for (var _b = __values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1];
var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
try {
// `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
instanceDeferred.resolve(instance);
}
catch (e) {
// when the instance factory throws an exception, it should not cause
// a fatal error. We just leave the promise unresolved.
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
Provider.prototype.clearInstance = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
this.instancesDeferred.delete(identifier);
this.instancesOptions.delete(identifier);
this.instances.delete(identifier);
};
// app.delete() will call this method on every provider to delete the services
// TODO: should we mark the provider as deleted?
Provider.prototype.delete = function () {
return __awaiter(this, void 0, void 0, function () {
var services;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
services = Array.from(this.instances.values());
return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], __read(services
.filter(function (service) { return 'INTERNAL' in service; }) // legacy services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(function (service) { return service.INTERNAL.delete(); }))), __read(services
.filter(function (service) { return '_delete' in service; }) // modularized services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(function (service) { return service._delete(); }))))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
Provider.prototype.isComponentSet = function () {
return this.component != null;
};
Provider.prototype.isInitialized = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
return this.instances.has(identifier);
};
Provider.prototype.getOptions = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
return this.instancesOptions.get(identifier) || {};
};
Provider.prototype.initialize = function (opts) {
var e_2, _a;
if (opts === void 0) { opts = {}; }
var _b = opts.options, options = _b === void 0 ? {} : _b;
var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
if (this.isInitialized(normalizedIdentifier)) {
throw Error(this.name + "(" + normalizedIdentifier + ") has already been initialized");
}
if (!this.isComponentSet()) {
throw Error("Component " + this.name + " has not been registered yet");
}
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
options: options
});
try {
// resolve any pending promise waiting for the service instance
for (var _c = __values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1];
var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
if (normalizedIdentifier === normalizedDeferredIdentifier) {
instanceDeferred.resolve(instance);
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_2) throw e_2.error; }
}
return instance;
};
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
Provider.prototype.onInit = function (callback, identifier) {
var _a;
var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();
existingCallbacks.add(callback);
this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
var existingInstance = this.instances.get(normalizedIdentifier);
if (existingInstance) {
callback(existingInstance, normalizedIdentifier);
}
return function () {
existingCallbacks.delete(callback);
};
};
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) {
var e_3, _a;
var callbacks = this.onInitCallbacks.get(identifier);
if (!callbacks) {
return;
}
try {
for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
var callback = callbacks_1_1.value;
try {
callback(instance, identifier);
}
catch (_b) {
// ignore errors in the onInit callback
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
}
finally { if (e_3) throw e_3.error; }
}
};
Provider.prototype.getOrInitializeService = function (_a) {
var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b;
var instance = this.instances.get(instanceIdentifier);
if (!instance && this.component) {
instance = this.component.instanceFactory(this.container, {
instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
options: options
});
this.instances.set(instanceIdentifier, instance);
this.instancesOptions.set(instanceIdentifier, options);
/**
* Invoke onInit listeners.
* Note this.component.onInstanceCreated is different, which is used by the component creator,
* while onInit listeners are registered by consumers of the provider.
*/
this.invokeOnInitCallbacks(instance, instanceIdentifier);
/**
* Order is important
* onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
* makes `isInitialized()` return true.
*/
if (this.component.onInstanceCreated) {
try {
this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
}
catch (_c) {
// ignore errors in the onInstanceCreatedCallback
}
}
}
return instance || null;
};
Provider.prototype.normalizeInstanceIdentifier = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
if (this.component) {
return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;
}
else {
return identifier; // assume multiple instances are supported before the component is provided.
}
};
Provider.prototype.shouldAutoInitialize = function () {
return (!!this.component &&
this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */);
};
return Provider;
}());
// undefined should be passed to the service factory for the default instance
function normalizeIdentifierForFactory(identifier) {
return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;
}
function isComponentEager(component) {
return component.instantiationMode === "EAGER" /* EAGER */;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
var ComponentContainer = /** @class */ (function () {
function ComponentContainer(name) {
this.name = name;
this.providers = new Map();
}
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
ComponentContainer.prototype.addComponent = function (component) {
var provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
throw new Error("Component " + component.name + " has already been registered with " + this.name);
}
provider.setComponent(component);
};
ComponentContainer.prototype.addOrOverwriteComponent = function (component) {
var provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
// delete the existing provider from the container, so we can register the new component
this.providers.delete(component.name);
}
this.addComponent(component);
};
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
ComponentContainer.prototype.getProvider = function (name) {
if (this.providers.has(name)) {
return this.providers.get(name);
}
// create a Provider for a service that hasn't registered with Firebase
var provider = new Provider(name, this);
this.providers.set(name, provider);
return provider;
};
ComponentContainer.prototype.getProviders = function () {
return Array.from(this.providers.values());
};
return ComponentContainer;
}());
export { Component, ComponentContainer, Provider };
//# sourceMappingURL=index.esm5.js.map

View File

@ -0,0 +1 @@
{"type":"module"}

View File

@ -0,0 +1,43 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstantiationMode, InstanceFactory, ComponentType, Dictionary, Name, onInstanceCreatedCallback } from './types';
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
export declare class Component<T extends Name = Name> {
readonly name: T;
readonly instanceFactory: InstanceFactory<T>;
readonly type: ComponentType;
multipleInstances: boolean;
/**
* Properties to be added to the service namespace
*/
serviceProps: Dictionary;
instantiationMode: InstantiationMode;
onInstanceCreated: onInstanceCreatedCallback<T> | null;
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name: T, instanceFactory: InstanceFactory<T>, type: ComponentType);
setInstantiationMode(mode: InstantiationMode): this;
setMultipleInstances(multipleInstances: boolean): this;
setServiceProps(props: Dictionary): this;
setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this;
}

View File

@ -0,0 +1,47 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Provider } from './provider';
import { Component } from './component';
import { Name } from './types';
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
export declare class ComponentContainer {
private readonly name;
private readonly providers;
constructor(name: string);
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
addComponent<T extends Name>(component: Component<T>): void;
addOrOverwriteComponent<T extends Name>(component: Component<T>): void;
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
getProvider<T extends Name>(name: T): Provider<T>;
getProviders(): Array<Provider<Name>>;
}

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../test/setup';
declare module './types' {
interface NameServiceMapping {
rocket: {};
ship: {};
fireball: {};
}
}

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export declare const DEFAULT_ENTRY_NAME = "[DEFAULT]";

View File

@ -0,0 +1,79 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ComponentContainer } from './component_container';
import { InitializeOptions, Name, NameServiceMapping, OnInitCallBack } from './types';
import { Component } from './component';
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
export declare class Provider<T extends Name> {
private readonly name;
private readonly container;
private component;
private readonly instances;
private readonly instancesDeferred;
private readonly instancesOptions;
private onInitCallbacks;
constructor(name: T, container: ComponentContainer);
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
get(identifier?: string): Promise<NameServiceMapping[T]>;
/**
*
* @param options.identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
* @param options.optional If optional is false or not provided, the method throws an error when
* the service is not immediately available.
* If optional is true, the method returns null if the service is not immediately available.
*/
getImmediate(options: {
identifier?: string;
optional: true;
}): NameServiceMapping[T] | null;
getImmediate(options?: {
identifier?: string;
optional?: false;
}): NameServiceMapping[T];
getComponent(): Component<T> | null;
setComponent(component: Component<T>): void;
clearInstance(identifier?: string): void;
delete(): Promise<void>;
isComponentSet(): boolean;
isInitialized(identifier?: string): boolean;
getOptions(identifier?: string): Record<string, unknown>;
initialize(opts?: InitializeOptions): NameServiceMapping[T];
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
onInit(callback: OnInitCallBack<T>, identifier?: string): () => void;
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
private invokeOnInitCallbacks;
private getOrInitializeService;
private normalizeInstanceIdentifier;
private shouldAutoInitialize;
}

View File

@ -0,0 +1,23 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../test/setup';
declare module './types' {
interface NameServiceMapping {
test: {};
badtest: {};
}
}

View File

@ -0,0 +1,62 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ComponentContainer } from './component_container';
export declare const enum InstantiationMode {
LAZY = "LAZY",
EAGER = "EAGER",
EXPLICIT = "EXPLICIT"
}
/**
* PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched
* onto `firebase` namespace. Assume the component name is `test`, customers will be able
* to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance.
*
* PRIVATE: A private component provides a set of private APIs that are used internally by other
* Firebase SDKs. No serivce namespace is created in `firebase` namespace and customers have no way to get them.
*/
export declare const enum ComponentType {
PUBLIC = "PUBLIC",
PRIVATE = "PRIVATE",
VERSION = "VERSION"
}
export interface InstanceFactoryOptions {
instanceIdentifier?: string;
options?: {};
}
export declare type InitializeOptions = InstanceFactoryOptions;
/**
* Factory to create an instance of type T, given a ComponentContainer.
* ComponentContainer is the IOC container that provides {@link Provider}
* for dependencies.
*
* NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies.
* It is useful for lazily loaded dependencies and optional dependencies.
*/
export declare type InstanceFactory<T extends Name> = (container: ComponentContainer, options: InstanceFactoryOptions) => NameServiceMapping[T];
export declare type onInstanceCreatedCallback<T extends Name> = (container: ComponentContainer, instanceIdentifier: string, instance: NameServiceMapping[T]) => void;
export interface Dictionary {
[key: string]: unknown;
}
/**
* This interface will be extended by Firebase SDKs to provide service name and service type mapping.
* It is used as a generic constraint to ensure type safety.
*/
export interface NameServiceMapping {
}
export declare type Name = keyof NameServiceMapping;
export declare type Service = NameServiceMapping[Name];
export declare type OnInitCallBack<T extends Name> = (instance: NameServiceMapping[T], identifier: string) => void;

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};

View File

@ -0,0 +1,5 @@
import { FirebaseApp } from '@firebase/app-types';
import { InstanceFactory, InstantiationMode, Name } from '../src/types';
import { Component } from '../src/component';
export declare function getFakeApp(appName?: string): FirebaseApp;
export declare function getFakeComponent<T extends Name>(name: T, factory: InstanceFactory<T>, multipleInstance?: boolean, instantiationMode?: InstantiationMode): Component<T>;

View File

@ -0,0 +1,466 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var util = require('@firebase/util');
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
var Component = /** @class */ (function () {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
function Component(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = "LAZY" /* LAZY */;
this.onInstanceCreated = null;
}
Component.prototype.setInstantiationMode = function (mode) {
this.instantiationMode = mode;
return this;
};
Component.prototype.setMultipleInstances = function (multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
};
Component.prototype.setServiceProps = function (props) {
this.serviceProps = props;
return this;
};
Component.prototype.setInstanceCreatedCallback = function (callback) {
this.onInstanceCreated = callback;
return this;
};
return Component;
}());
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_ENTRY_NAME = '[DEFAULT]';
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
var Provider = /** @class */ (function () {
function Provider(name, container) {
this.name = name;
this.container = container;
this.component = null;
this.instances = new Map();
this.instancesDeferred = new Map();
this.instancesOptions = new Map();
this.onInitCallbacks = new Map();
}
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
Provider.prototype.get = function (identifier) {
// if multipleInstances is not supported, use the default name
var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
if (!this.instancesDeferred.has(normalizedIdentifier)) {
var deferred = new util.Deferred();
this.instancesDeferred.set(normalizedIdentifier, deferred);
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
// initialize the service if it can be auto-initialized
try {
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
if (instance) {
deferred.resolve(instance);
}
}
catch (e) {
// when the instance factory throws an exception during get(), it should not cause
// a fatal error. We just return the unresolved promise in this case.
}
}
}
return this.instancesDeferred.get(normalizedIdentifier).promise;
};
Provider.prototype.getImmediate = function (options) {
var _a;
// if multipleInstances is not supported, use the default name
var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
var optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
try {
return this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
}
catch (e) {
if (optional) {
return null;
}
else {
throw e;
}
}
}
else {
// In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw
if (optional) {
return null;
}
else {
throw Error("Service " + this.name + " is not available");
}
}
};
Provider.prototype.getComponent = function () {
return this.component;
};
Provider.prototype.setComponent = function (component) {
var e_1, _a;
if (component.name !== this.name) {
throw Error("Mismatching Component " + component.name + " for Provider " + this.name + ".");
}
if (this.component) {
throw Error("Component for " + this.name + " has already been provided");
}
this.component = component;
// return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
if (!this.shouldAutoInitialize()) {
return;
}
// if the service is eager, initialize the default instance
if (isComponentEager(component)) {
try {
this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });
}
catch (e) {
// when the instance factory for an eager Component throws an exception during the eager
// initialization, it should not cause a fatal error.
// TODO: Investigate if we need to make it configurable, because some component may want to cause
// a fatal error in this case?
}
}
try {
// Create service instances for the pending promises and resolve them
// NOTE: if this.multipleInstances is false, only the default instance will be created
// and all promises with resolve with it regardless of the identifier.
for (var _b = tslib.__values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = tslib.__read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1];
var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
try {
// `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
instanceDeferred.resolve(instance);
}
catch (e) {
// when the instance factory throws an exception, it should not cause
// a fatal error. We just leave the promise unresolved.
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
Provider.prototype.clearInstance = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
this.instancesDeferred.delete(identifier);
this.instancesOptions.delete(identifier);
this.instances.delete(identifier);
};
// app.delete() will call this method on every provider to delete the services
// TODO: should we mark the provider as deleted?
Provider.prototype.delete = function () {
return tslib.__awaiter(this, void 0, void 0, function () {
var services;
return tslib.__generator(this, function (_a) {
switch (_a.label) {
case 0:
services = Array.from(this.instances.values());
return [4 /*yield*/, Promise.all(tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(services
.filter(function (service) { return 'INTERNAL' in service; }) // legacy services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(function (service) { return service.INTERNAL.delete(); }))), tslib.__read(services
.filter(function (service) { return '_delete' in service; }) // modularized services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(function (service) { return service._delete(); }))))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
Provider.prototype.isComponentSet = function () {
return this.component != null;
};
Provider.prototype.isInitialized = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
return this.instances.has(identifier);
};
Provider.prototype.getOptions = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
return this.instancesOptions.get(identifier) || {};
};
Provider.prototype.initialize = function (opts) {
var e_2, _a;
if (opts === void 0) { opts = {}; }
var _b = opts.options, options = _b === void 0 ? {} : _b;
var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
if (this.isInitialized(normalizedIdentifier)) {
throw Error(this.name + "(" + normalizedIdentifier + ") has already been initialized");
}
if (!this.isComponentSet()) {
throw Error("Component " + this.name + " has not been registered yet");
}
var instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
options: options
});
try {
// resolve any pending promise waiting for the service instance
for (var _c = tslib.__values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = tslib.__read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1];
var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
if (normalizedIdentifier === normalizedDeferredIdentifier) {
instanceDeferred.resolve(instance);
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_2) throw e_2.error; }
}
return instance;
};
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
Provider.prototype.onInit = function (callback, identifier) {
var _a;
var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();
existingCallbacks.add(callback);
this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
var existingInstance = this.instances.get(normalizedIdentifier);
if (existingInstance) {
callback(existingInstance, normalizedIdentifier);
}
return function () {
existingCallbacks.delete(callback);
};
};
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) {
var e_3, _a;
var callbacks = this.onInitCallbacks.get(identifier);
if (!callbacks) {
return;
}
try {
for (var callbacks_1 = tslib.__values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
var callback = callbacks_1_1.value;
try {
callback(instance, identifier);
}
catch (_b) {
// ignore errors in the onInit callback
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
}
finally { if (e_3) throw e_3.error; }
}
};
Provider.prototype.getOrInitializeService = function (_a) {
var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b;
var instance = this.instances.get(instanceIdentifier);
if (!instance && this.component) {
instance = this.component.instanceFactory(this.container, {
instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
options: options
});
this.instances.set(instanceIdentifier, instance);
this.instancesOptions.set(instanceIdentifier, options);
/**
* Invoke onInit listeners.
* Note this.component.onInstanceCreated is different, which is used by the component creator,
* while onInit listeners are registered by consumers of the provider.
*/
this.invokeOnInitCallbacks(instance, instanceIdentifier);
/**
* Order is important
* onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
* makes `isInitialized()` return true.
*/
if (this.component.onInstanceCreated) {
try {
this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
}
catch (_c) {
// ignore errors in the onInstanceCreatedCallback
}
}
}
return instance || null;
};
Provider.prototype.normalizeInstanceIdentifier = function (identifier) {
if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }
if (this.component) {
return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;
}
else {
return identifier; // assume multiple instances are supported before the component is provided.
}
};
Provider.prototype.shouldAutoInitialize = function () {
return (!!this.component &&
this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */);
};
return Provider;
}());
// undefined should be passed to the service factory for the default instance
function normalizeIdentifierForFactory(identifier) {
return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;
}
function isComponentEager(component) {
return component.instantiationMode === "EAGER" /* EAGER */;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
var ComponentContainer = /** @class */ (function () {
function ComponentContainer(name) {
this.name = name;
this.providers = new Map();
}
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
ComponentContainer.prototype.addComponent = function (component) {
var provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
throw new Error("Component " + component.name + " has already been registered with " + this.name);
}
provider.setComponent(component);
};
ComponentContainer.prototype.addOrOverwriteComponent = function (component) {
var provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
// delete the existing provider from the container, so we can register the new component
this.providers.delete(component.name);
}
this.addComponent(component);
};
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
ComponentContainer.prototype.getProvider = function (name) {
if (this.providers.has(name)) {
return this.providers.get(name);
}
// create a Provider for a service that hasn't registered with Firebase
var provider = new Provider(name, this);
this.providers.set(name, provider);
return provider;
};
ComponentContainer.prototype.getProviders = function () {
return Array.from(this.providers.values());
};
return ComponentContainer;
}());
exports.Component = Component;
exports.ComponentContainer = ComponentContainer;
exports.Provider = Provider;
//# sourceMappingURL=index.cjs.js.map

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { Component } from './src/component';
export { ComponentContainer } from './src/component_container';
export { Provider } from './src/provider';
export { ComponentType, InstanceFactory, InstantiationMode, NameServiceMapping, Name, InstanceFactoryOptions } from './src/types';

View File

@ -0,0 +1,43 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstantiationMode, InstanceFactory, ComponentType, Dictionary, Name, onInstanceCreatedCallback } from './types';
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
export declare class Component<T extends Name = Name> {
readonly name: T;
readonly instanceFactory: InstanceFactory<T>;
readonly type: ComponentType;
multipleInstances: boolean;
/**
* Properties to be added to the service namespace
*/
serviceProps: Dictionary;
instantiationMode: InstantiationMode;
onInstanceCreated: onInstanceCreatedCallback<T> | null;
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name: T, instanceFactory: InstanceFactory<T>, type: ComponentType);
setInstantiationMode(mode: InstantiationMode): this;
setMultipleInstances(multipleInstances: boolean): this;
setServiceProps(props: Dictionary): this;
setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this;
}

View File

@ -0,0 +1,47 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Provider } from './provider';
import { Component } from './component';
import { Name } from './types';
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
export declare class ComponentContainer {
private readonly name;
private readonly providers;
constructor(name: string);
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
addComponent<T extends Name>(component: Component<T>): void;
addOrOverwriteComponent<T extends Name>(component: Component<T>): void;
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
getProvider<T extends Name>(name: T): Provider<T>;
getProviders(): Array<Provider<Name>>;
}

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../test/setup';
declare module './types' {
interface NameServiceMapping {
rocket: {};
ship: {};
fireball: {};
}
}

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export declare const DEFAULT_ENTRY_NAME = "[DEFAULT]";

View File

@ -0,0 +1,79 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ComponentContainer } from './component_container';
import { InitializeOptions, Name, NameServiceMapping, OnInitCallBack } from './types';
import { Component } from './component';
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
export declare class Provider<T extends Name> {
private readonly name;
private readonly container;
private component;
private readonly instances;
private readonly instancesDeferred;
private readonly instancesOptions;
private onInitCallbacks;
constructor(name: T, container: ComponentContainer);
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
get(identifier?: string): Promise<NameServiceMapping[T]>;
/**
*
* @param options.identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
* @param options.optional If optional is false or not provided, the method throws an error when
* the service is not immediately available.
* If optional is true, the method returns null if the service is not immediately available.
*/
getImmediate(options: {
identifier?: string;
optional: true;
}): NameServiceMapping[T] | null;
getImmediate(options?: {
identifier?: string;
optional?: false;
}): NameServiceMapping[T];
getComponent(): Component<T> | null;
setComponent(component: Component<T>): void;
clearInstance(identifier?: string): void;
delete(): Promise<void>;
isComponentSet(): boolean;
isInitialized(identifier?: string): boolean;
getOptions(identifier?: string): Record<string, unknown>;
initialize(opts?: InitializeOptions): NameServiceMapping[T];
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
onInit(callback: OnInitCallBack<T>, identifier?: string): () => void;
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
private invokeOnInitCallbacks;
private getOrInitializeService;
private normalizeInstanceIdentifier;
private shouldAutoInitialize;
}

View File

@ -0,0 +1,23 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../test/setup';
declare module './types' {
interface NameServiceMapping {
test: {};
badtest: {};
}
}

View File

@ -0,0 +1,62 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ComponentContainer } from './component_container';
export declare const enum InstantiationMode {
LAZY = "LAZY",
EAGER = "EAGER",
EXPLICIT = "EXPLICIT"
}
/**
* PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched
* onto `firebase` namespace. Assume the component name is `test`, customers will be able
* to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance.
*
* PRIVATE: A private component provides a set of private APIs that are used internally by other
* Firebase SDKs. No serivce namespace is created in `firebase` namespace and customers have no way to get them.
*/
export declare const enum ComponentType {
PUBLIC = "PUBLIC",
PRIVATE = "PRIVATE",
VERSION = "VERSION"
}
export interface InstanceFactoryOptions {
instanceIdentifier?: string;
options?: {};
}
export declare type InitializeOptions = InstanceFactoryOptions;
/**
* Factory to create an instance of type T, given a ComponentContainer.
* ComponentContainer is the IOC container that provides {@link Provider}
* for dependencies.
*
* NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies.
* It is useful for lazily loaded dependencies and optional dependencies.
*/
export declare type InstanceFactory<T extends Name> = (container: ComponentContainer, options: InstanceFactoryOptions) => NameServiceMapping[T];
export declare type onInstanceCreatedCallback<T extends Name> = (container: ComponentContainer, instanceIdentifier: string, instance: NameServiceMapping[T]) => void;
export interface Dictionary {
[key: string]: unknown;
}
/**
* This interface will be extended by Firebase SDKs to provide service name and service type mapping.
* It is used as a generic constraint to ensure type safety.
*/
export interface NameServiceMapping {
}
export declare type Name = keyof NameServiceMapping;
export declare type Service = NameServiceMapping[Name];
export declare type OnInitCallBack<T extends Name> = (instance: NameServiceMapping[T], identifier: string) => void;

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};

View File

@ -0,0 +1,5 @@
import { FirebaseApp } from '@firebase/app-types';
import { InstanceFactory, InstantiationMode, Name } from '../src/types';
import { Component } from '../src/component';
export declare function getFakeApp(appName?: string): FirebaseApp;
export declare function getFakeComponent<T extends Name>(name: T, factory: InstanceFactory<T>, multipleInstance?: boolean, instantiationMode?: InstantiationMode): Component<T>;

View File

@ -0,0 +1,59 @@
{
"name": "@firebase/component",
"version": "0.5.21",
"description": "Firebase Component Platform",
"author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)",
"main": "dist/index.cjs.js",
"browser": "dist/esm/index.esm2017.js",
"module": "dist/esm/index.esm2017.js",
"esm5": "dist/esm/index.esm5.js",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs.js",
"esm5": "./dist/esm/index.esm5.js",
"default": "./dist/esm/index.esm2017.js"
},
"./package.json": "./package.json"
},
"files": [
"dist"
],
"scripts": {
"lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'",
"lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'",
"build": "rollup -c",
"build:deps": "lerna run --scope @firebase/component --include-dependencies build",
"dev": "rollup -c -w",
"test": "run-p lint test:all",
"test:all": "run-p test:browser test:node",
"test:ci": "node ../../scripts/run_tests_in_ci.js -s test:all",
"test:browser": "karma start --single-run",
"test:node": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha src/**/*.test.ts --config ../../config/mocharc.node.js"
},
"dependencies": {
"@firebase/util": "1.7.3",
"tslib": "^2.1.0"
},
"license": "Apache-2.0",
"devDependencies": {
"rollup": "2.79.1",
"rollup-plugin-typescript2": "0.31.2",
"typescript": "4.2.2"
},
"repository": {
"directory": "packages/component",
"type": "git",
"url": "https://github.com/firebase/firebase-js-sdk.git"
},
"bugs": {
"url": "https://github.com/firebase/firebase-js-sdk/issues"
},
"typings": "dist/index.d.ts",
"nyc": {
"extension": [
".ts"
],
"reportDir": "./coverage/node"
}
}

View File

@ -0,0 +1,224 @@
# @firebase/database-compat
## 0.2.10
### Patch Changes
- [`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5) [#6682](https://github.com/firebase/firebase-js-sdk/pull/6682) - Upgrade TypeScript to 4.7.4.
- Updated dependencies [[`4af28c1a4`](https://github.com/firebase/firebase-js-sdk/commit/4af28c1a42bd25ce2353f694ca1724c6101cbce5)]:
- @firebase/component@0.5.21
- @firebase/database@0.13.10
- @firebase/database-types@0.9.17
- @firebase/logger@0.3.4
- @firebase/util@1.7.3
## 0.2.9
### Patch Changes
- Updated dependencies [[`807f06aa2`](https://github.com/firebase/firebase-js-sdk/commit/807f06aa26438a91aaea08fd38efb6c706bb8a5d)]:
- @firebase/util@1.7.2
- @firebase/component@0.5.20
- @firebase/database@0.13.9
- @firebase/database-types@0.9.16
## 0.2.8
### Patch Changes
- Updated dependencies [[`5aa48d0ab`](https://github.com/firebase/firebase-js-sdk/commit/5aa48d0ab432002ccf49d65bf2ff637e82a2b402), [`171b78b76`](https://github.com/firebase/firebase-js-sdk/commit/171b78b762826a640d267dd4dd172ad9459c4561), [`29d034072`](https://github.com/firebase/firebase-js-sdk/commit/29d034072c20af394ce384e42aa10a37d5dfcb18)]:
- @firebase/database@0.13.8
- @firebase/util@1.7.1
- @firebase/component@0.5.19
- @firebase/database-types@0.9.15
## 0.2.7
### Patch Changes
- Updated dependencies [[`fdd4ab464`](https://github.com/firebase/firebase-js-sdk/commit/fdd4ab464b59a107bdcc195df3f01e32efd89ed4)]:
- @firebase/util@1.7.0
- @firebase/database@0.13.7
- @firebase/database-types@0.9.14
- @firebase/component@0.5.18
## 0.2.6
### Patch Changes
- Updated dependencies [[`f35533594`](https://github.com/firebase/firebase-js-sdk/commit/f355335942b874ba390bcbf3be6de44a3d33dce8)]:
- @firebase/database@0.13.6
## 0.2.5
### Patch Changes
- [`9f1e3c667`](https://github.com/firebase/firebase-js-sdk/commit/9f1e3c66747126c8e24894d73f7fa27480bec08d) [#6536](https://github.com/firebase/firebase-js-sdk/pull/6536) - Revert "Updated type of action parameter for DataSnapshot#forEach"
* [`fcd4b8ac3`](https://github.com/firebase/firebase-js-sdk/commit/fcd4b8ac36636a60d83cd3370969ff9192f9e6ad) [#6508](https://github.com/firebase/firebase-js-sdk/pull/6508) - Fixed faulty transaction bug causing filtered index queries to override default queries.
* Updated dependencies [[`9f1e3c667`](https://github.com/firebase/firebase-js-sdk/commit/9f1e3c66747126c8e24894d73f7fa27480bec08d), [`a5d9e1083`](https://github.com/firebase/firebase-js-sdk/commit/a5d9e10831c2877e9d15c8a33b15557e4251c4de), [`fcd4b8ac3`](https://github.com/firebase/firebase-js-sdk/commit/fcd4b8ac36636a60d83cd3370969ff9192f9e6ad)]:
- @firebase/database-types@0.9.13
- @firebase/database@0.13.5
## 0.2.4
### Patch Changes
- [`65838089d`](https://github.com/firebase/firebase-js-sdk/commit/65838089da47965e5e39e58c76a81a74666b215e) [#6374](https://github.com/firebase/firebase-js-sdk/pull/6374) (fixes [#6368](https://github.com/firebase/firebase-js-sdk/issues/6368)) - Updated type of action parameter for DataSnapshot#forEach
- Updated dependencies [[`65838089d`](https://github.com/firebase/firebase-js-sdk/commit/65838089da47965e5e39e58c76a81a74666b215e)]:
- @firebase/database@0.13.4
- @firebase/database-types@0.9.12
## 0.2.3
### Patch Changes
- Updated dependencies [[`c187446a2`](https://github.com/firebase/firebase-js-sdk/commit/c187446a202d881f55800be167cdb37b4d0e4a13), [`b12af44a5`](https://github.com/firebase/firebase-js-sdk/commit/b12af44a5c7500e1192d6cc1a4afc4d77efadbaf), [`6a8be1337`](https://github.com/firebase/firebase-js-sdk/commit/6a8be1337f19a49db40e0c757f571f42b5b4d494)]:
- @firebase/database@0.13.3
- @firebase/util@1.6.3
- @firebase/component@0.5.17
- @firebase/database-types@0.9.11
## 0.2.2
### Patch Changes
- Updated dependencies [[`578dc5836`](https://github.com/firebase/firebase-js-sdk/commit/578dc58365c6c71d8ad01dd8b9dbe829e76de068), [`efe2000fc`](https://github.com/firebase/firebase-js-sdk/commit/efe2000fc499e2c85c4e5e0fef6741ff3bad2eb0)]:
- @firebase/database@0.13.2
- @firebase/util@1.6.2
- @firebase/component@0.5.16
- @firebase/database-types@0.9.10
## 0.2.1
### Patch Changes
- [`2cd1cc76f`](https://github.com/firebase/firebase-js-sdk/commit/2cd1cc76f2a308135cd60f424fe09084a34b5cb5) [#6307](https://github.com/firebase/firebase-js-sdk/pull/6307) (fixes [#6300](https://github.com/firebase/firebase-js-sdk/issues/6300)) - fix: add type declarations to exports field
* [`497d34c84`](https://github.com/firebase/firebase-js-sdk/commit/497d34c8472a19cb8baca56985c98346e5a4727d) [#6319](https://github.com/firebase/firebase-js-sdk/pull/6319) - Remove app-compat from peerDependencies to avoid npm install warning in firebase-admin.
* Updated dependencies [[`2cd1cc76f`](https://github.com/firebase/firebase-js-sdk/commit/2cd1cc76f2a308135cd60f424fe09084a34b5cb5)]:
- @firebase/component@0.5.15
- @firebase/database@0.13.1
- @firebase/logger@0.3.3
- @firebase/util@1.6.1
- @firebase/database-types@0.9.9
## 0.2.0
### Minor Changes
- [`9c6808fea`](https://github.com/firebase/firebase-js-sdk/commit/9c6808fea231d1ab6de6f6ab548c67b751a12a78) [#6171](https://github.com/firebase/firebase-js-sdk/pull/6171) - Add `forceWebSockets()` and `forceLongPolling()`
### Patch Changes
- Updated dependencies [[`874cdbbcc`](https://github.com/firebase/firebase-js-sdk/commit/874cdbbccbc2bf8f4ee18abe220e87dc52e6a8db), [`9c5c9c36d`](https://github.com/firebase/firebase-js-sdk/commit/9c5c9c36da80b98b73cfd60ef2e2965087e9f801), [`9c6808fea`](https://github.com/firebase/firebase-js-sdk/commit/9c6808fea231d1ab6de6f6ab548c67b751a12a78)]:
- @firebase/database@0.13.0
- @firebase/util@1.6.0
- @firebase/component@0.5.14
- @firebase/database-types@0.9.8
## 0.1.8
### Patch Changes
- Updated dependencies [[`1c37b5e96`](https://github.com/firebase/firebase-js-sdk/commit/1c37b5e965978d796c46ff6b9f52051cf6070751), [`e9e5f6b3c`](https://github.com/firebase/firebase-js-sdk/commit/e9e5f6b3ca9d61323b22f87986d9959f5297ec59), [`7a4e65cef`](https://github.com/firebase/firebase-js-sdk/commit/7a4e65cef9468a20fb32dc112aa7113345bc76c5)]:
- @firebase/database-types@0.9.7
- @firebase/util@1.5.2
- @firebase/database@0.12.8
- @firebase/component@0.5.13
## 0.1.7
### Patch Changes
- Updated dependencies [[`3198d58dc`](https://github.com/firebase/firebase-js-sdk/commit/3198d58dcedbf7583914dbcc76984f6f7df8d2ef)]:
- @firebase/util@1.5.1
- @firebase/component@0.5.12
- @firebase/database@0.12.7
- @firebase/database-types@0.9.6
## 0.1.6
### Patch Changes
- Updated dependencies [[`2d672cead`](https://github.com/firebase/firebase-js-sdk/commit/2d672cead167187cb714cd89b638c0884ba58f03)]:
- @firebase/util@1.5.0
- @firebase/database@0.12.6
- @firebase/component@0.5.11
- @firebase/database-types@0.9.5
## 0.1.5
### Patch Changes
- Updated dependencies [[`3b481f572`](https://github.com/firebase/firebase-js-sdk/commit/3b481f572456e1eab3435bfc25717770d95a8c49)]:
- @firebase/util@1.4.3
- @firebase/component@0.5.10
- @firebase/database@0.12.5
- @firebase/database-types@0.9.4
## 0.1.4
### Patch Changes
- [`3281315fa`](https://github.com/firebase/firebase-js-sdk/commit/3281315fae9c6f535f9d5052ee17d60861ea569a) [#5708](https://github.com/firebase/firebase-js-sdk/pull/5708) (fixes [#1487](https://github.com/firebase/firebase-js-sdk/issues/1487)) - Update build scripts to work with the exports field
- Updated dependencies [[`3281315fa`](https://github.com/firebase/firebase-js-sdk/commit/3281315fae9c6f535f9d5052ee17d60861ea569a)]:
- @firebase/component@0.5.9
- @firebase/database@0.12.4
- @firebase/logger@0.3.2
- @firebase/util@1.4.2
- @firebase/database-types@0.9.3
## 0.1.3
### Patch Changes
- [`2322b6023`](https://github.com/firebase/firebase-js-sdk/commit/2322b6023c628cd9f4f4172767c17d215dd91684) [#5693](https://github.com/firebase/firebase-js-sdk/pull/5693) - Add exports field to all packages
- Updated dependencies [[`2322b6023`](https://github.com/firebase/firebase-js-sdk/commit/2322b6023c628cd9f4f4172767c17d215dd91684)]:
- @firebase/component@0.5.8
- @firebase/database@0.12.3
- @firebase/logger@0.3.1
- @firebase/util@1.4.1
- @firebase/database-types@0.9.2
## 0.1.2
### Patch Changes
- [`352cc2647`](https://github.com/firebase/firebase-js-sdk/commit/352cc26476a0c249f89d19eb371ecdcbbd067e5f) [#5587](https://github.com/firebase/firebase-js-sdk/pull/5587) - Add "repository" field to package.json files that were missing it.
- Updated dependencies [[`93795c780`](https://github.com/firebase/firebase-js-sdk/commit/93795c7801d6b28ccbbe5855fd2f3fc377b1db5f)]:
- @firebase/database@0.12.2
## 0.1.1
### Patch Changes
- [`dfe65ff9b`](https://github.com/firebase/firebase-js-sdk/commit/dfe65ff9bfa66d318d45e2a666e302867ae53a01) [#5537](https://github.com/firebase/firebase-js-sdk/pull/5537) - Added an entry point `@firebase/database-compat/standalone` to share code with Admin SDK properly
* [`b79bd33e4`](https://github.com/firebase/firebase-js-sdk/commit/b79bd33e4d3fe6c051b29a85d5141fcb8dcc8d2d) [#5531](https://github.com/firebase/firebase-js-sdk/pull/5531) - export types from @firebase/database-compat for admin SDK
* Updated dependencies [[`dfe65ff9b`](https://github.com/firebase/firebase-js-sdk/commit/dfe65ff9bfa66d318d45e2a666e302867ae53a01), [`a99943fe3`](https://github.com/firebase/firebase-js-sdk/commit/a99943fe3bd5279761aa29d138ec91272b06df39), [`b835b4cba`](https://github.com/firebase/firebase-js-sdk/commit/b835b4cbabc4b7b180ae38b908c49205ce31a422)]:
- @firebase/database@0.12.1
- @firebase/logger@0.3.0
- @firebase/util@1.4.0
- @firebase/component@0.5.7
- @firebase/database-types@0.9.1
## 0.1.0
### Minor Changes
- [`cdada6c68`](https://github.com/firebase/firebase-js-sdk/commit/cdada6c68f9740d13dd6674bcb658e28e68253b6) [#5345](https://github.com/firebase/firebase-js-sdk/pull/5345) (fixes [#5015](https://github.com/firebase/firebase-js-sdk/issues/5015)) - Release modularized SDKs
### Patch Changes
- Updated dependencies [[`cdada6c68`](https://github.com/firebase/firebase-js-sdk/commit/cdada6c68f9740d13dd6674bcb658e28e68253b6)]:
- @firebase/database@0.12.0
- @firebase/database-types@0.9.0

View File

@ -0,0 +1,5 @@
# @firebase/database-compat
This is the compatibility layer for the Firebase Realtime Database component of the Firebase JS SDK.
**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.**

View File

@ -0,0 +1,74 @@
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FirebaseApp } from '@firebase/app-types';
import { FirebaseService } from '@firebase/app-types/private';
import { forceLongPolling, forceWebSockets, Database as ModularDatabase } from '@firebase/database';
import { Compat, EmulatorMockTokenOptions } from '@firebase/util';
import { Reference } from './Reference';
/**
* Class representing a firebase database.
*/
export declare class Database implements FirebaseService, Compat<ModularDatabase> {
readonly _delegate: ModularDatabase;
readonly app: FirebaseApp;
static readonly ServerValue: {
TIMESTAMP: object;
increment: (delta: number) => object;
};
/**
* The constructor should not be called by users of our public API.
*/
constructor(_delegate: ModularDatabase, app: FirebaseApp);
INTERNAL: {
delete: () => Promise<void>;
forceWebSockets: typeof forceWebSockets;
forceLongPolling: typeof forceLongPolling;
};
/**
* Modify this instance to communicate with the Realtime Database emulator.
*
* <p>Note: This method must be called before performing any other operation.
*
* @param host - the emulator host (ex: localhost)
* @param port - the emulator port (ex: 8080)
* @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
*/
useEmulator(host: string, port: number, options?: {
mockUserToken?: EmulatorMockTokenOptions;
}): void;
/**
* Returns a reference to the root or to the path specified in the provided
* argument.
*
* @param path - The relative string path or an existing Reference to a database
* location.
* @throws If a Reference is provided, throws if it does not belong to the
* same project.
* @returns Firebase reference.
*/
ref(path?: string): Reference;
ref(path?: Reference): Reference;
/**
* Returns a reference to the root or the path specified in url.
* We throw a exception if the url is not in the same domain as the
* current repo.
* @returns Firebase reference.
*/
refFromURL(url: string): Reference;
goOffline(): void;
goOnline(): void;
}

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