repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src/managers/build_target_manager.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:watcher/watcher.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../../data/build_target.dart';
bool _isBlacklistedPath(String filePath, Set<RegExp> blackListedPatterns) =>
blackListedPatterns.any((pattern) => filePath.contains(pattern));
bool _shouldBuild(BuildTarget target, Iterable<WatchEvent> changes) =>
target is DefaultBuildTarget &&
changes.any((change) =>
!_isBlacklistedPath(change.path, target.blackListPatterns.toSet()));
/// Manages the set of build targets, and corresponding listeners, tracked by
/// the Dart Build Daemon.
class BuildTargetManager {
var _buildTargets = <BuildTarget, Set<WebSocketChannel>>{};
bool Function(BuildTarget, Iterable<WatchEvent>) shouldBuild;
BuildTargetManager(
{bool Function(BuildTarget, Iterable<WatchEvent>) shouldBuildOverride})
: shouldBuild = shouldBuildOverride ?? _shouldBuild;
bool get isEmpty => _buildTargets.isEmpty;
Set<BuildTarget> get targets => _buildTargets.keys.toSet();
/// All the tracked channels.
Set<WebSocketChannel> get allChannels =>
_buildTargets.values.expand((s) => s).toSet();
/// Adds a tracked build target with corresponding interested channel.
void addBuildTarget(BuildTarget target, WebSocketChannel channel) {
_buildTargets.putIfAbsent(target, () => <WebSocketChannel>{}).add(channel);
}
/// Returns channels that are interested in the provided target.
Set<WebSocketChannel> channels(BuildTarget target) =>
_buildTargets[target] ?? <WebSocketChannel>{};
void removeChannel(WebSocketChannel channel) =>
_buildTargets = Map.fromEntries(_buildTargets.entries
.map((e) => MapEntry(e.key, e.value..remove(channel)))
.where((e) => e.value.isNotEmpty));
Set<BuildTarget> targetsForChanges(List<WatchEvent> changes) =>
targets.where((target) => shouldBuild(target, changes)).toSet();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/glob.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:path/path.dart' as p;
import 'src/ast.dart';
import 'src/io.dart';
import 'src/list_tree.dart';
import 'src/parser.dart';
import 'src/utils.dart';
/// Regular expression used to quote globs.
final _quoteRegExp = RegExp(r'[*{[?\\}\],\-()]');
/// A glob for matching and listing files and directories.
///
/// A glob matches an entire string as a path. Although the glob pattern uses
/// POSIX syntax, it can match against POSIX, Windows, or URL paths. The format
/// it expects paths to use is based on the `context` parameter to [new Glob];
/// it defaults to the current system's syntax.
///
/// Paths are normalized before being matched against a glob, so for example the
/// glob `foo/bar` matches the path `foo/./bar`. A relative glob can match an
/// absolute path and vice versa; globs and paths are both interpreted as
/// relative to `context.current`, which defaults to the current working
/// directory.
///
/// When used as a [Pattern], a glob will return either one or zero matches for
/// a string depending on whether the entire string matches the glob. These
/// matches don't currently have capture groups, although this may change in the
/// future.
class Glob implements Pattern {
/// The pattern used to create this glob.
final String pattern;
/// The context in which paths matched against this glob are interpreted.
final p.Context context;
/// If true, a path matches if it matches the glob itself or is recursively
/// contained within a directory that matches.
final bool recursive;
/// Whether the glob matches paths case-sensitively.
bool get caseSensitive => _ast.caseSensitive;
/// The parsed AST of the glob.
final AstNode _ast;
ListTree _listTree;
/// Whether [context]'s current directory is absolute.
bool get _contextIsAbsolute {
if (_contextIsAbsoluteCache == null) {
_contextIsAbsoluteCache = context.isAbsolute(context.current);
}
return _contextIsAbsoluteCache;
}
bool _contextIsAbsoluteCache;
/// Whether [pattern] could match absolute paths.
bool get _patternCanMatchAbsolute {
if (_patternCanMatchAbsoluteCache == null) {
_patternCanMatchAbsoluteCache = _ast.canMatchAbsolute;
}
return _patternCanMatchAbsoluteCache;
}
bool _patternCanMatchAbsoluteCache;
/// Whether [pattern] could match relative paths.
bool get _patternCanMatchRelative {
if (_patternCanMatchRelativeCache == null) {
_patternCanMatchRelativeCache = _ast.canMatchRelative;
}
return _patternCanMatchRelativeCache;
}
bool _patternCanMatchRelativeCache;
/// Returns [contents] with characters that are meaningful in globs
/// backslash-escaped.
static String quote(String contents) =>
contents.replaceAllMapped(_quoteRegExp, (match) => '\\${match[0]}');
/// Creates a new glob with [pattern].
///
/// Paths matched against the glob are interpreted according to [context]. It
/// defaults to the system context.
///
/// If [recursive] is true, this glob matches and lists not only the files and
/// directories it explicitly matches, but anything beneath those as well.
///
/// If [caseSensitive] is true, this glob matches and lists only files whose
/// case matches that of the characters in the glob. Otherwise, it matches
/// regardless of case. This defaults to `false` when [context] is Windows and
/// `true` otherwise.
factory Glob(String pattern,
{p.Context context, bool recursive = false, bool caseSensitive}) {
context ??= p.context;
caseSensitive ??= context.style == p.Style.windows ? false : true;
if (recursive) pattern += "{,/**}";
var parser = Parser(pattern, context, caseSensitive: caseSensitive);
return Glob._(pattern, context, parser.parse(), recursive);
}
Glob._(this.pattern, this.context, this._ast, this.recursive);
/// Lists all [FileSystemEntity]s beneath [root] that match the glob.
///
/// This works much like [Directory.list], but it only lists directories that
/// could contain entities that match the glob. It provides no guarantees
/// about the order of the returned entities, although it does guarantee that
/// only one entity with a given path will be returned.
///
/// [root] defaults to the current working directory.
///
/// [followLinks] works the same as for [Directory.list].
Stream<FileSystemEntity> list({String root, bool followLinks = true}) {
if (context.style != p.style) {
throw StateError("Can't list glob \"$this\"; it matches "
"${context.style} paths, but this platform uses ${p.style} paths.");
}
if (_listTree == null) _listTree = ListTree(_ast);
return _listTree.list(root: root, followLinks: followLinks);
}
/// Synchronously lists all [FileSystemEntity]s beneath [root] that match the
/// glob.
///
/// This works much like [Directory.listSync], but it only lists directories
/// that could contain entities that match the glob. It provides no guarantees
/// about the order of the returned entities, although it does guarantee that
/// only one entity with a given path will be returned.
///
/// [root] defaults to the current working directory.
///
/// [followLinks] works the same as for [Directory.list].
List<FileSystemEntity> listSync({String root, bool followLinks = true}) {
if (context.style != p.style) {
throw StateError("Can't list glob \"$this\"; it matches "
"${context.style} paths, but this platform uses ${p.style} paths.");
}
if (_listTree == null) _listTree = ListTree(_ast);
return _listTree.listSync(root: root, followLinks: followLinks);
}
/// Returns whether this glob matches [path].
bool matches(String path) => matchAsPrefix(path) != null;
Match matchAsPrefix(String path, [int start = 0]) {
// Globs are like anchored RegExps in that they only match entire paths, so
// if the match starts anywhere after the first character it can't succeed.
if (start != 0) return null;
if (_patternCanMatchAbsolute &&
(_contextIsAbsolute || context.isAbsolute(path))) {
var absolutePath = context.normalize(context.absolute(path));
if (_ast.matches(toPosixPath(context, absolutePath))) {
return GlobMatch(path, this);
}
}
if (_patternCanMatchRelative) {
var relativePath = context.relative(path);
if (_ast.matches(toPosixPath(context, relativePath))) {
return GlobMatch(path, this);
}
}
return null;
}
Iterable<Match> allMatches(String path, [int start = 0]) {
var match = matchAsPrefix(path, start);
return match == null ? [] : [match];
}
String toString() => pattern;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/ast.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:collection/collection.dart';
import 'package:path/path.dart' as p;
import 'utils.dart';
const _separator = 0x2F; // "/"
/// A node in the abstract syntax tree for a glob.
abstract class AstNode {
/// The cached regular expression that this AST was compiled into.
RegExp _regExp;
/// Whether this node matches case-sensitively or not.
final bool caseSensitive;
/// Whether this glob could match an absolute path.
///
/// Either this or [canMatchRelative] or both will be true.
bool get canMatchAbsolute => false;
/// Whether this glob could match a relative path.
///
/// Either this or [canMatchRelative] or both will be true.
bool get canMatchRelative => true;
AstNode._(this.caseSensitive);
/// Returns a new glob with all the options bubbled to the top level.
///
/// In particular, this returns a glob AST with two guarantees:
///
/// 1. There are no [OptionsNode]s other than the one at the top level.
/// 2. It matches the same set of paths as [this].
///
/// For example, given the glob `{foo,bar}/{click/clack}`, this would return
/// `{foo/click,foo/clack,bar/click,bar/clack}`.
OptionsNode flattenOptions() => OptionsNode([
SequenceNode([this], caseSensitive: caseSensitive)
], caseSensitive: caseSensitive);
/// Returns whether this glob matches [string].
bool matches(String string) {
if (_regExp == null) {
_regExp = RegExp('^${_toRegExp()}\$', caseSensitive: caseSensitive);
}
return _regExp.hasMatch(string);
}
/// Subclasses should override this to return a regular expression component.
String _toRegExp();
}
/// A sequence of adjacent AST nodes.
class SequenceNode extends AstNode {
/// The nodes in the sequence.
final List<AstNode> nodes;
bool get canMatchAbsolute => nodes.first.canMatchAbsolute;
bool get canMatchRelative => nodes.first.canMatchRelative;
SequenceNode(Iterable<AstNode> nodes, {bool caseSensitive = true})
: nodes = nodes.toList(),
super._(caseSensitive);
OptionsNode flattenOptions() {
if (nodes.isEmpty) {
return OptionsNode([this], caseSensitive: caseSensitive);
}
var sequences =
nodes.first.flattenOptions().options.map((sequence) => sequence.nodes);
for (var node in nodes.skip(1)) {
// Concatenate all sequences in the next options node ([nextSequences])
// onto all previous sequences ([sequences]).
var nextSequences = node.flattenOptions().options;
sequences = sequences.expand((sequence) {
return nextSequences.map((nextSequence) {
return sequence.toList()..addAll(nextSequence.nodes);
});
});
}
return OptionsNode(sequences.map((sequence) {
// Combine any adjacent LiteralNodes in [sequence].
return SequenceNode(
sequence.fold<List<AstNode>>([], (combined, node) {
if (combined.isEmpty ||
combined.last is! LiteralNode ||
node is! LiteralNode) {
return combined..add(node);
}
combined[combined.length - 1] = LiteralNode(
// TODO(nweiz): Avoid casting when sdk#25565 is fixed.
(combined.last as LiteralNode).text +
(node as LiteralNode).text,
caseSensitive: caseSensitive);
return combined;
}),
caseSensitive: caseSensitive);
}), caseSensitive: caseSensitive);
}
/// Splits this glob into components along its path separators.
///
/// For example, given the glob `foo/*/*.dart`, this would return three globs:
/// `foo`, `*`, and `*.dart`.
///
/// Path separators within options nodes are not split. For example,
/// `foo/{bar,baz/bang}/qux` will return three globs: `foo`, `{bar,baz/bang}`,
/// and `qux`.
///
/// [context] is used to determine what absolute roots look like for this
/// glob.
List<SequenceNode> split(p.Context context) {
var componentsToReturn = <SequenceNode>[];
List<AstNode> currentComponent;
addNode(AstNode node) {
if (currentComponent == null) currentComponent = [];
currentComponent.add(node);
}
finishComponent() {
if (currentComponent == null) return;
componentsToReturn
.add(SequenceNode(currentComponent, caseSensitive: caseSensitive));
currentComponent = null;
}
for (var node in nodes) {
if (node is! LiteralNode) {
addNode(node);
continue;
}
// TODO(nweiz): Avoid casting when sdk#25565 is fixed.
var literal = node as LiteralNode;
if (!literal.text.contains('/')) {
addNode(literal);
continue;
}
var text = literal.text;
if (context.style == p.Style.windows) text = text.replaceAll("/", "\\");
Iterable<String> components = context.split(text);
// If the first component is absolute, that means it's a separator (on
// Windows some non-separator things are also absolute, but it's invalid
// to have "C:" show up in the middle of a path anyway).
if (context.isAbsolute(components.first)) {
// If this is the first component, it's the root.
if (componentsToReturn.isEmpty && currentComponent == null) {
var root = components.first;
if (context.style == p.Style.windows) {
// Above, we switched to backslashes to make [context.split] handle
// roots properly. That means that if there is a root, it'll still
// have backslashes, where forward slashes are required for globs.
// So we switch it back here.
root = root.replaceAll("\\", "/");
}
addNode(LiteralNode(root, caseSensitive: caseSensitive));
}
finishComponent();
components = components.skip(1);
if (components.isEmpty) continue;
}
// For each component except the last one, add a separate sequence to
// [sequences] containing only that component.
for (var component in components.take(components.length - 1)) {
addNode(LiteralNode(component, caseSensitive: caseSensitive));
finishComponent();
}
// For the final component, only end its sequence (by adding a new empty
// sequence) if it ends with a separator.
addNode(LiteralNode(components.last, caseSensitive: caseSensitive));
if (literal.text.endsWith('/')) finishComponent();
}
finishComponent();
return componentsToReturn;
}
String _toRegExp() => nodes.map((node) => node._toRegExp()).join();
bool operator ==(Object other) =>
other is SequenceNode &&
const IterableEquality().equals(nodes, other.nodes);
int get hashCode => const IterableEquality().hash(nodes);
String toString() => nodes.join();
}
/// A node matching zero or more non-separator characters.
class StarNode extends AstNode {
StarNode({bool caseSensitive = true}) : super._(caseSensitive);
String _toRegExp() => '[^/]*';
bool operator ==(Object other) => other is StarNode;
int get hashCode => 0;
String toString() => '*';
}
/// A node matching zero or more characters that may be separators.
class DoubleStarNode extends AstNode {
/// The path context for the glob.
///
/// This is used to determine what absolute paths look like.
final p.Context _context;
DoubleStarNode(this._context, {bool caseSensitive = true})
: super._(caseSensitive);
String _toRegExp() {
// Double star shouldn't match paths with a leading "../", since these paths
// wouldn't be listed with this glob. We only check for "../" at the
// beginning since the paths are normalized before being checked against the
// glob.
var buffer = StringBuffer()..write(r'(?!^(?:\.\./|');
// A double star at the beginning of the glob also shouldn't match absolute
// paths, since those also wouldn't be listed. Which root patterns we look
// for depends on the style of path we're matching.
if (_context.style == p.Style.posix) {
buffer.write(r'/');
} else if (_context.style == p.Style.windows) {
buffer.write(r'//|[A-Za-z]:/');
} else {
assert(_context.style == p.Style.url);
buffer.write(r'[a-zA-Z][-+.a-zA-Z\d]*://|/');
}
// Use `[^]` rather than `.` so that it matches newlines as well.
buffer.write(r'))[^]*');
return buffer.toString();
}
bool operator ==(Object other) => other is DoubleStarNode;
int get hashCode => 1;
String toString() => '**';
}
/// A node matching a single non-separator character.
class AnyCharNode extends AstNode {
AnyCharNode({bool caseSensitive = true}) : super._(caseSensitive);
String _toRegExp() => '[^/]';
bool operator ==(Object other) => other is AnyCharNode;
int get hashCode => 2;
String toString() => '?';
}
/// A node matching a single character in a range of options.
class RangeNode extends AstNode {
/// The ranges matched by this node.
///
/// The ends of the ranges are unicode code points.
final Set<Range> ranges;
/// Whether this range was negated.
final bool negated;
RangeNode(Iterable<Range> ranges, {this.negated, bool caseSensitive = true})
: ranges = ranges.toSet(),
super._(caseSensitive);
OptionsNode flattenOptions() {
if (negated || ranges.any((range) => !range.isSingleton)) {
return super.flattenOptions();
}
// If a range explicitly lists a set of characters, return each character as
// a separate expansion.
return OptionsNode(ranges.map((range) {
return SequenceNode([
LiteralNode(String.fromCharCodes([range.min]),
caseSensitive: caseSensitive)
], caseSensitive: caseSensitive);
}), caseSensitive: caseSensitive);
}
String _toRegExp() {
var buffer = StringBuffer();
var containsSeparator = ranges.any((range) => range.contains(_separator));
if (!negated && containsSeparator) {
// Add `(?!/)` because ranges are never allowed to match separators.
buffer.write('(?!/)');
}
buffer.write('[');
if (negated) {
buffer.write('^');
// If the range doesn't itself exclude separators, exclude them ourselves,
// since ranges are never allowed to match them.
if (!containsSeparator) buffer.write('/');
}
for (var range in ranges) {
var start = String.fromCharCodes([range.min]);
buffer.write(regExpQuote(start));
if (range.isSingleton) continue;
buffer.write('-');
buffer.write(regExpQuote(String.fromCharCodes([range.max])));
}
buffer.write(']');
return buffer.toString();
}
bool operator ==(Object other) =>
other is RangeNode &&
other.negated == negated &&
SetEquality().equals(ranges, other.ranges);
int get hashCode => (negated ? 1 : 3) * const SetEquality().hash(ranges);
String toString() {
var buffer = StringBuffer()..write('[');
for (var range in ranges) {
buffer.writeCharCode(range.min);
if (range.isSingleton) continue;
buffer.write('-');
buffer.writeCharCode(range.max);
}
buffer.write(']');
return buffer.toString();
}
}
/// A node that matches one of several options.
class OptionsNode extends AstNode {
/// The options to match.
final List<SequenceNode> options;
bool get canMatchAbsolute => options.any((node) => node.canMatchAbsolute);
bool get canMatchRelative => options.any((node) => node.canMatchRelative);
OptionsNode(Iterable<SequenceNode> options, {bool caseSensitive = true})
: options = options.toList(),
super._(caseSensitive);
OptionsNode flattenOptions() =>
OptionsNode(options.expand((option) => option.flattenOptions().options),
caseSensitive: caseSensitive);
String _toRegExp() =>
'(?:${options.map((option) => option._toRegExp()).join("|")})';
bool operator ==(Object other) =>
other is OptionsNode &&
const UnorderedIterableEquality().equals(options, other.options);
int get hashCode => const UnorderedIterableEquality().hash(options);
String toString() => '{${options.join(',')}}';
}
/// A node that matches a literal string.
class LiteralNode extends AstNode {
/// The string to match.
final String text;
/// The path context for the glob.
///
/// This is used to determine whether this could match an absolute path.
final p.Context _context;
bool get canMatchAbsolute {
var nativeText =
_context.style == p.Style.windows ? text.replaceAll('/', '\\') : text;
return _context.isAbsolute(nativeText);
}
bool get canMatchRelative => !canMatchAbsolute;
LiteralNode(this.text, {p.Context context, bool caseSensitive = true})
: _context = context,
super._(caseSensitive);
String _toRegExp() => regExpQuote(text);
bool operator ==(Object other) => other is LiteralNode && other.text == text;
int get hashCode => text.hashCode;
String toString() => text;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/stream_pool.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
/// A pool of streams whose events are unified and emitted through a central
/// stream.
class StreamPool<T> {
/// The stream through which all events from streams in the pool are emitted.
Stream<T> get stream => _controller.stream;
final StreamController<T> _controller;
/// Subscriptions to the streams that make up the pool.
final _subscriptions = Map<Stream<T>, StreamSubscription<T>>();
/// Whether this pool should be closed when it becomes empty.
bool _closeWhenEmpty = false;
/// Creates a new stream pool that only supports a single subscriber.
///
/// Any events from broadcast streams in the pool will be buffered until a
/// listener is subscribed.
StreamPool()
// Create the controller as sync so that any sync input streams will be
// forwarded synchronously. Async input streams will have their asynchrony
// preserved, since _controller.add will be called asynchronously.
: _controller = StreamController<T>(sync: true);
/// Creates a new stream pool where [stream] can be listened to more than
/// once.
///
/// Any events from buffered streams in the pool will be emitted immediately,
/// regardless of whether [stream] has any subscribers.
StreamPool.broadcast()
// Create the controller as sync so that any sync input streams will be
// forwarded synchronously. Async input streams will have their asynchrony
// preserved, since _controller.add will be called asynchronously.
: _controller = StreamController<T>.broadcast(sync: true);
/// Adds [stream] as a member of this pool.
///
/// Any events from [stream] will be emitted through [this.stream]. If
/// [stream] is sync, they'll be emitted synchronously; if [stream] is async,
/// they'll be emitted asynchronously.
void add(Stream<T> stream) {
if (_subscriptions.containsKey(stream)) return;
_subscriptions[stream] = stream.listen(_controller.add,
onError: _controller.addError, onDone: () => remove(stream));
}
/// Removes [stream] as a member of this pool.
void remove(Stream<T> stream) {
var subscription = _subscriptions.remove(stream);
if (subscription != null) subscription.cancel();
if (_closeWhenEmpty && _subscriptions.isEmpty) close();
}
/// Removes all streams from this pool and closes [stream].
void close() {
for (var subscription in _subscriptions.values) {
subscription.cancel();
}
_subscriptions.clear();
_controller.close();
}
/// The next time this pool becomes empty, close it.
void closeWhenEmpty() {
if (_subscriptions.isEmpty) close();
_closeWhenEmpty = true;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/parser.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:path/path.dart' as p;
import 'package:string_scanner/string_scanner.dart';
import 'ast.dart';
import 'utils.dart';
const _hyphen = 0x2D;
const _slash = 0x2F;
/// A parser for globs.
class Parser {
/// The scanner used to scan the source.
final StringScanner _scanner;
/// The path context for the glob.
final p.Context _context;
/// Whether this glob is case-sensitive.
final bool _caseSensitive;
Parser(String component, this._context, {bool caseSensitive = true})
: _scanner = StringScanner(component),
_caseSensitive = caseSensitive;
/// Parses an entire glob.
SequenceNode parse() => _parseSequence();
/// Parses a [SequenceNode].
///
/// If [inOptions] is true, this is parsing within an [OptionsNode].
SequenceNode _parseSequence({bool inOptions = false}) {
var nodes = <AstNode>[];
if (_scanner.isDone) {
_scanner.error('expected a glob.', position: 0, length: 0);
}
while (!_scanner.isDone) {
if (inOptions && (_scanner.matches(',') || _scanner.matches('}'))) break;
nodes.add(_parseNode(inOptions: inOptions));
}
return SequenceNode(nodes, caseSensitive: _caseSensitive);
}
/// Parses an [AstNode].
///
/// If [inOptions] is true, this is parsing within an [OptionsNode].
AstNode _parseNode({bool inOptions = false}) {
var star = _parseStar();
if (star != null) return star;
var anyChar = _parseAnyChar();
if (anyChar != null) return anyChar;
var range = _parseRange();
if (range != null) return range;
var options = _parseOptions();
if (options != null) return options;
return _parseLiteral(inOptions: inOptions);
}
/// Tries to parse a [StarNode] or a [DoubleStarNode].
///
/// Returns `null` if there's not one to parse.
AstNode _parseStar() {
if (!_scanner.scan('*')) return null;
return _scanner.scan('*')
? DoubleStarNode(_context, caseSensitive: _caseSensitive)
: StarNode(caseSensitive: _caseSensitive);
}
/// Tries to parse an [AnyCharNode].
///
/// Returns `null` if there's not one to parse.
AstNode _parseAnyChar() {
if (!_scanner.scan('?')) return null;
return AnyCharNode(caseSensitive: _caseSensitive);
}
/// Tries to parse an [RangeNode].
///
/// Returns `null` if there's not one to parse.
AstNode _parseRange() {
if (!_scanner.scan('[')) return null;
if (_scanner.matches(']')) _scanner.error('unexpected "]".');
var negated = _scanner.scan('!') || _scanner.scan('^');
readRangeChar() {
var char = _scanner.readChar();
if (negated || char != _slash) return char;
_scanner.error('"/" may not be used in a range.',
position: _scanner.position - 1);
}
var ranges = <Range>[];
while (!_scanner.scan(']')) {
var start = _scanner.position;
// Allow a backslash to escape a character.
_scanner.scan('\\');
var char = readRangeChar();
if (_scanner.scan('-')) {
if (_scanner.matches(']')) {
ranges.add(Range.singleton(char));
ranges.add(Range.singleton(_hyphen));
continue;
}
// Allow a backslash to escape a character.
_scanner.scan('\\');
var end = readRangeChar();
if (end < char) {
_scanner.error("Range out of order.",
position: start, length: _scanner.position - start);
}
ranges.add(Range(char, end));
} else {
ranges.add(Range.singleton(char));
}
}
return RangeNode(ranges, negated: negated, caseSensitive: _caseSensitive);
}
/// Tries to parse an [OptionsNode].
///
/// Returns `null` if there's not one to parse.
AstNode _parseOptions() {
if (!_scanner.scan('{')) return null;
if (_scanner.matches('}')) _scanner.error('unexpected "}".');
var options = <SequenceNode>[];
do {
options.add(_parseSequence(inOptions: true));
} while (_scanner.scan(','));
// Don't allow single-option blocks.
if (options.length == 1) _scanner.expect(',');
_scanner.expect('}');
return OptionsNode(options, caseSensitive: _caseSensitive);
}
/// Parses a [LiteralNode].
AstNode _parseLiteral({bool inOptions = false}) {
// If we're in an options block, we want to stop parsing as soon as we hit a
// comma. Otherwise, commas are fair game for literals.
var regExp = RegExp(inOptions ? r'[^*{[?\\}\],()]*' : r'[^*{[?\\}\]()]*');
_scanner.scan(regExp);
var buffer = StringBuffer()..write(_scanner.lastMatch[0]);
while (_scanner.scan('\\')) {
buffer.writeCharCode(_scanner.readChar());
_scanner.scan(regExp);
buffer.write(_scanner.lastMatch[0]);
}
for (var char in const [']', '(', ')']) {
if (_scanner.matches(char)) _scanner.error('unexpected "$char"');
}
if (!inOptions && _scanner.matches('}')) _scanner.error('unexpected "}"');
return LiteralNode(buffer.toString(),
context: _context, caseSensitive: _caseSensitive);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/list_tree.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:async/async.dart';
import 'package:path/path.dart' as p;
import 'package:pedantic/pedantic.dart';
import 'ast.dart';
import 'io.dart';
import 'utils.dart';
/// The errno for a file or directory not existing on Mac and Linux.
const _enoent = 2;
/// Another errno we see on Windows when trying to list a non-existent
/// directory.
const _enoentWin = 3;
/// A structure built from a glob that efficiently lists filesystem entities
/// that match that glob.
///
/// This structure is designed to list the minimal number of physical
/// directories necessary to find everything that matches the glob. For example,
/// for the glob `foo/{bar,baz}/*`, there's no need to list the working
/// directory or even `foo/`; only `foo/bar` and `foo/baz` should be listed.
///
/// This works by creating a tree of [_ListTreeNode]s, each of which corresponds
/// to a single of directory nesting in the source glob. Each node has child
/// nodes associated with globs ([_ListTreeNode.children]), as well as its own
/// glob ([_ListTreeNode._validator]) that indicates which entities within that
/// node's directory should be returned.
///
/// For example, the glob `foo/{*.dart,b*/*.txt}` creates the following tree:
///
/// .
/// '-- "foo" (validator: "*.dart")
/// '-- "b*" (validator: "*.txt"
///
/// If a node doesn't have a validator, we know we don't have to list it
/// explicitly.
///
/// Nodes can also be marked as "recursive", which means they need to be listed
/// recursively (usually to support `**`). In this case, they will have no
/// children; instead, their validator will just encompass the globs that would
/// otherwise be in their children. For example, the glob
/// `foo/{**.dart,bar/*.txt}` creates a recursive node for `foo` with the
/// validator `**.dart,bar/*.txt`.
///
/// If the glob contains multiple filesystem roots (e.g. `{C:/,D:/}*.dart`),
/// each root will have its own tree of nodes. Relative globs use `.` as their
/// root instead.
class ListTree {
/// A map from filesystem roots to the list tree for those roots.
///
/// A relative glob will use `.` as its root.
final _trees = Map<String, _ListTreeNode>();
/// Whether paths listed might overlap.
///
/// If they do, we need to filter out overlapping paths.
bool _canOverlap;
ListTree(AstNode glob) {
// The first step in constructing a tree from the glob is to simplify the
// problem by eliminating options. [glob.flattenOptions] bubbles all options
// (and certain ranges) up to the top level of the glob so we can deal with
// them one at a time.
var options = glob.flattenOptions();
for (var option in options.options) {
// Since each option doesn't include its own options, we can safely split
// it into path components.
var components = option.split(p.context);
var firstNode = components.first.nodes.first;
var root = '.';
// Determine the root for this option, if it's absolute. If it's not, the
// root's just ".".
if (firstNode is LiteralNode) {
var text = firstNode.text;
if (Platform.isWindows) text.replaceAll("/", "\\");
if (p.isAbsolute(text)) {
// If the path is absolute, the root should be the only thing in the
// first component.
assert(components.first.nodes.length == 1);
root = firstNode.text;
components.removeAt(0);
}
}
_addGlob(root, components);
}
_canOverlap = _computeCanOverlap();
}
/// Add the glob represented by [components] to the tree under [root].
void _addGlob(String root, List<SequenceNode> components) {
// The first [parent] represents the root directory itself. It may be null
// here if this is the first option with this particular [root]. If so,
// we'll create it below.
//
// As we iterate through [components], [parent] will be set to
// progressively more nested nodes.
var parent = _trees[root];
for (var i = 0; i < components.length; i++) {
var component = components[i];
var recursive = component.nodes.any((node) => node is DoubleStarNode);
var complete = i == components.length - 1;
// If the parent node for this level of nesting already exists, the new
// option will be added to it as additional validator options and/or
// additional children.
//
// If the parent doesn't exist, we'll create it in one of the else
// clauses below.
if (parent != null) {
if (parent.isRecursive || recursive) {
// If [component] is recursive, mark [parent] as recursive. This
// will cause all of its children to be folded into its validator.
// If [parent] was already recursive, this is a no-op.
parent.makeRecursive();
// Add [component] and everything nested beneath it as an option to
// [parent]. Since [parent] is recursive, it will recursively list
// everything beneath it and filter them with one big glob.
parent.addOption(_join(components.sublist(i)));
return;
} else if (complete) {
// If [component] is the last component, add it to [parent]'s
// validator but not to its children.
parent.addOption(component);
} else {
// On the other hand if there are more components, add [component]
// to [parent]'s children and not its validator. Since we process
// each option's components separately, the same component is never
// both a validator and a child.
if (!parent.children.containsKey(component)) {
parent.children[component] = _ListTreeNode();
}
parent = parent.children[component];
}
} else if (recursive) {
_trees[root] = _ListTreeNode.recursive(_join(components.sublist(i)));
return;
} else if (complete) {
_trees[root] = _ListTreeNode()..addOption(component);
} else {
_trees[root] = _ListTreeNode();
_trees[root].children[component] = _ListTreeNode();
parent = _trees[root].children[component];
}
}
}
/// Computes the value for [_canOverlap].
bool _computeCanOverlap() {
// If this can list a relative path and an absolute path, the former may be
// contained within the latter.
if (_trees.length > 1 && _trees.containsKey('.')) return true;
// Otherwise, this can only overlap if the tree beneath any given root could
// overlap internally.
return _trees.values.any((node) => node.canOverlap);
}
/// List all entities that match this glob beneath [root].
Stream<FileSystemEntity> list({String root, bool followLinks = true}) {
if (root == null) root = '.';
var group = StreamGroup<FileSystemEntity>();
for (var rootDir in _trees.keys) {
var dir = rootDir == '.' ? root : rootDir;
group.add(_trees[rootDir].list(dir, followLinks: followLinks));
}
group.close();
if (!_canOverlap) return group.stream;
// TODO(nweiz): Rather than filtering here, avoid double-listing directories
// in the first place.
var seen = Set();
return group.stream.where((entity) {
if (seen.contains(entity.path)) return false;
seen.add(entity.path);
return true;
});
}
/// Synchronosuly list all entities that match this glob beneath [root].
List<FileSystemEntity> listSync({String root, bool followLinks = true}) {
if (root == null) root = '.';
var result = _trees.keys.expand((rootDir) {
var dir = rootDir == '.' ? root : rootDir;
return _trees[rootDir].listSync(dir, followLinks: followLinks);
});
if (!_canOverlap) return result.toList();
// TODO(nweiz): Rather than filtering here, avoid double-listing directories
// in the first place.
var seen = Set<String>();
return result.where((entity) {
if (seen.contains(entity.path)) return false;
seen.add(entity.path);
return true;
}).toList();
}
}
/// A single node in a [ListTree].
class _ListTreeNode {
/// This node's child nodes, by their corresponding globs.
///
/// Each child node will only be listed on directories that match its glob.
///
/// This may be `null`, indicating that this node should be listed
/// recursively.
Map<SequenceNode, _ListTreeNode> children;
/// This node's validator.
///
/// This determines which entities will ultimately be emitted when [list] is
/// called.
OptionsNode _validator;
/// Whether this node is recursive.
///
/// A recursive node has no children and is listed recursively.
bool get isRecursive => children == null;
bool get _caseSensitive {
if (_validator != null) return _validator.caseSensitive;
if (children == null) return true;
if (children.isEmpty) return true;
return children.keys.first.caseSensitive;
}
/// Whether this node doesn't itself need to be listed.
///
/// If a node has no validator and all of its children are literal filenames,
/// there's no need to list its contents. We can just directly traverse into
/// its children.
bool get _isIntermediate {
if (_validator != null) return false;
return children.keys.every((sequence) =>
sequence.nodes.length == 1 && sequence.nodes.first is LiteralNode);
}
/// Returns whether listing this node might return overlapping results.
bool get canOverlap {
// A recusive node can never overlap with itself, because it will only ever
// involve a single call to [Directory.list] that's then filtered with
// [_validator].
if (isRecursive) return false;
// If there's more than one child node and at least one of the children is
// dynamic (that is, matches more than just a literal string), there may be
// overlap.
if (children.length > 1) {
// Case-insensitivity means that even literals may match multiple entries.
if (!_caseSensitive) return true;
if (children.keys.any((sequence) =>
sequence.nodes.length > 1 || sequence.nodes.single is! LiteralNode)) {
return true;
}
}
return children.values.any((node) => node.canOverlap);
}
/// Creates a node with no children and no validator.
_ListTreeNode()
: children = Map<SequenceNode, _ListTreeNode>(),
_validator = null;
/// Creates a recursive node the given [validator].
_ListTreeNode.recursive(SequenceNode validator)
: children = null,
_validator =
OptionsNode([validator], caseSensitive: validator.caseSensitive);
/// Transforms this into recursive node, folding all its children into its
/// validator.
void makeRecursive() {
if (isRecursive) return;
_validator = OptionsNode(children.keys.map((sequence) {
var child = children[sequence];
child.makeRecursive();
return _join([sequence, child._validator]);
}), caseSensitive: _caseSensitive);
children = null;
}
/// Adds [validator] to this node's existing validator.
void addOption(SequenceNode validator) {
if (_validator == null) {
_validator =
OptionsNode([validator], caseSensitive: validator.caseSensitive);
} else {
_validator.options.add(validator);
}
}
/// Lists all entities within [dir] matching this node or its children.
///
/// This may return duplicate entities. These will be filtered out in
/// [ListTree.list].
Stream<FileSystemEntity> list(String dir, {bool followLinks = true}) {
if (isRecursive) {
return Directory(dir)
.list(recursive: true, followLinks: followLinks)
.where((entity) => _matches(p.relative(entity.path, from: dir)));
}
// Don't spawn extra [Directory.list] calls when we already know exactly
// which subdirectories we're interested in.
if (_isIntermediate && _caseSensitive) {
var resultGroup = StreamGroup<FileSystemEntity>();
children.forEach((sequence, child) {
resultGroup.add(child.list(
p.join(dir, (sequence.nodes.single as LiteralNode).text),
followLinks: followLinks));
});
resultGroup.close();
return resultGroup.stream;
}
return StreamCompleter.fromFuture(() async {
var entities =
await Directory(dir).list(followLinks: followLinks).toList();
await _validateIntermediateChildrenAsync(dir, entities);
var resultGroup = StreamGroup<FileSystemEntity>();
var resultController = StreamController<FileSystemEntity>(sync: true);
unawaited(resultGroup.add(resultController.stream));
for (var entity in entities) {
var basename = p.relative(entity.path, from: dir);
if (_matches(basename)) resultController.add(entity);
children.forEach((sequence, child) {
if (entity is! Directory) return;
if (!sequence.matches(basename)) return;
var stream = child
.list(p.join(dir, basename), followLinks: followLinks)
.handleError((_) {}, test: (error) {
// Ignore errors from directories not existing. We do this here so
// that we only ignore warnings below wild cards. For example, the
// glob "foo/bar/*/baz" should fail if "foo/bar" doesn't exist but
// succeed if "foo/bar/qux/baz" doesn't exist.
return error is FileSystemException &&
(error.osError.errorCode == _enoent ||
error.osError.errorCode == _enoentWin);
});
resultGroup.add(stream);
});
}
unawaited(resultController.close());
unawaited(resultGroup.close());
return resultGroup.stream;
}());
}
/// If this is a case-insensitive list, validates that all intermediate
/// children (according to [_isIntermediate]) match at least one entity in
/// [entities].
///
/// This ensures that listing "foo/bar/*" fails on case-sensitive systems if
/// "foo/bar" doesn't exist.
Future _validateIntermediateChildrenAsync(
String dir, List<FileSystemEntity> entities) async {
if (_caseSensitive) return;
for (var sequence in children.keys) {
var child = children[sequence];
if (!child._isIntermediate) continue;
if (entities.any(
(entity) => sequence.matches(p.relative(entity.path, from: dir)))) {
continue;
}
// We know this will fail, we're just doing it to force dart:io to emit
// the exception it would if we were listing case-sensitively.
await child
.list(p.join(dir, (sequence.nodes.single as LiteralNode).text))
.toList();
}
}
/// Synchronously lists all entities within [dir] matching this node or its
/// children.
///
/// This may return duplicate entities. These will be filtered out in
/// [ListTree.listSync].
Iterable<FileSystemEntity> listSync(String dir, {bool followLinks = true}) {
if (isRecursive) {
return Directory(dir)
.listSync(recursive: true, followLinks: followLinks)
.where((entity) => _matches(p.relative(entity.path, from: dir)));
}
// Don't spawn extra [Directory.listSync] calls when we already know exactly
// which subdirectories we're interested in.
if (_isIntermediate && _caseSensitive) {
return children.keys.expand((sequence) {
return children[sequence].listSync(
p.join(dir, (sequence.nodes.single as LiteralNode).text),
followLinks: followLinks);
});
}
var entities = Directory(dir).listSync(followLinks: followLinks);
_validateIntermediateChildrenSync(dir, entities);
return entities.expand((entity) {
var entities = <FileSystemEntity>[];
var basename = p.relative(entity.path, from: dir);
if (_matches(basename)) entities.add(entity);
if (entity is! Directory) return entities;
entities.addAll(children.keys
.where((sequence) => sequence.matches(basename))
.expand((sequence) {
try {
return children[sequence]
.listSync(p.join(dir, basename), followLinks: followLinks)
.toList();
} on FileSystemException catch (error) {
// Ignore errors from directories not existing. We do this here so
// that we only ignore warnings below wild cards. For example, the
// glob "foo/bar/*/baz" should fail if "foo/bar" doesn't exist but
// succeed if "foo/bar/qux/baz" doesn't exist.
if (error.osError.errorCode == _enoent ||
error.osError.errorCode == _enoentWin) {
return const [];
} else {
rethrow;
}
}
}));
return entities;
});
}
/// If this is a case-insensitive list, validates that all intermediate
/// children (according to [_isIntermediate]) match at least one entity in
/// [entities].
///
/// This ensures that listing "foo/bar/*" fails on case-sensitive systems if
/// "foo/bar" doesn't exist.
void _validateIntermediateChildrenSync(
String dir, List<FileSystemEntity> entities) {
if (_caseSensitive) return;
children.forEach((sequence, child) {
if (!child._isIntermediate) return;
if (entities.any(
(entity) => sequence.matches(p.relative(entity.path, from: dir)))) {
return;
}
// If there are no [entities] that match [sequence], manually list the
// directory to force `dart:io` to throw an error. This allows us to
// ensure that listing "foo/bar/*" fails on case-sensitive systems if
// "foo/bar" doesn't exist.
child.listSync(p.join(dir, (sequence.nodes.single as LiteralNode).text));
});
}
/// Returns whether the native [path] matches [_validator].
bool _matches(String path) {
if (_validator == null) return false;
return _validator.matches(toPosixPath(p.context, path));
}
String toString() => "($_validator) $children";
}
/// Joins each [components] into a new glob where each component is separated by
/// a path separator.
SequenceNode _join(Iterable<AstNode> components) {
var componentsList = components.toList();
var first = componentsList.removeAt(0);
var nodes = [first];
for (var component in componentsList) {
nodes.add(LiteralNode('/', caseSensitive: first.caseSensitive));
nodes.add(component);
}
return SequenceNode(nodes, caseSensitive: first.caseSensitive);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/io_export.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// This library exists only to satisfy build_runner, which doesn't allow
/// sdk libraries to be conditional imported or exported directly.
library glob.src.io_export;
export 'dart:io';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/utils.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:path/path.dart' as p;
/// A range from [min] to [max], inclusive.
class Range {
/// The minimum value included by the range.
final int min;
/// The maximum value included by the range.
final int max;
/// Whether this range covers only a single number.
bool get isSingleton => min == max;
Range(this.min, this.max);
/// Returns a range that covers only [value].
Range.singleton(int value) : this(value, value);
/// Whether [this] contains [value].
bool contains(int value) => value >= min && value <= max;
bool operator ==(Object other) =>
other is Range && other.min == min && other.max == max;
int get hashCode => 3 * min + 7 * max;
}
/// An implementation of [Match] constructed by [Glob]s.
class GlobMatch implements Match {
final String input;
final Pattern pattern;
final int start = 0;
int get end => input.length;
int get groupCount => 0;
GlobMatch(this.input, this.pattern);
String operator [](int group) => this.group(group);
String group(int group) {
if (group != 0) throw RangeError.range(group, 0, 0);
return input;
}
List<String> groups(List<int> groupIndices) =>
groupIndices.map((index) => group(index)).toList();
}
final _quote = RegExp(r"[+*?{}|[\]\\().^$-]");
/// Returns [contents] with characters that are meaningful in regular
/// expressions backslash-escaped.
String regExpQuote(String contents) =>
contents.replaceAllMapped(_quote, (char) => "\\${char[0]}");
/// Returns [path] with all its separators replaced with forward slashes.
///
/// This is useful when converting from Windows paths to globs.
String separatorToForwardSlash(String path) {
if (p.style != p.Style.windows) return path;
return path.replaceAll('\\', '/');
}
/// Returns [path] which follows [context] converted to the POSIX format that
/// globs match against.
String toPosixPath(p.Context context, String path) {
if (context.style == p.Style.windows) return path.replaceAll('\\', '/');
if (context.style == p.Style.url) return Uri.decodeFull(path);
return path;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/glob/src/io.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// These libraries don't expose *exactly* the same API, but they overlap in all
// the cases we care about.
export 'io_export.dart'
// We don't actually support the web - exporting dart:io gives a reasonably
// clear signal to users about that since it doesn't exist.
if (dart.library.html) 'io_export.dart'
if (dart.library.js) 'package:node_io/node_io.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/build_runner_core.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
export 'package:build/build.dart' show PostProcessBuilder, PostProcessBuildStep;
export 'src/asset/file_based.dart';
export 'src/asset/finalized_reader.dart';
export 'src/asset/reader.dart' show RunnerAssetReader;
export 'src/asset/writer.dart';
export 'src/environment/build_environment.dart';
export 'src/environment/io_environment.dart';
export 'src/environment/overridable_environment.dart';
export 'src/generate/build_directory.dart';
export 'src/generate/build_result.dart';
export 'src/generate/build_runner.dart';
export 'src/generate/exceptions.dart'
show
BuildConfigChangedException,
BuildScriptChangedException,
CannotBuildException;
export 'src/generate/finalized_assets_view.dart' show FinalizedAssetsView;
export 'src/generate/options.dart'
show
defaultRootPackageWhitelist,
LogSubscription,
BuildOptions,
BuildFilter;
export 'src/generate/performance_tracker.dart'
show BuildPerformance, BuilderActionPerformance, BuildPhasePerformance;
export 'src/logging/human_readable_duration.dart';
export 'src/logging/logging.dart';
export 'src/package_graph/apply_builders.dart'
show
BuilderApplication,
apply,
applyPostProcess,
applyToRoot,
toAll,
toAllPackages,
toDependentsOf,
toNoneByDefault,
toPackage,
toPackages,
toRoot;
export 'src/package_graph/package_graph.dart';
export 'src/util/constants.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset_graph/exceptions.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
class DuplicateAssetNodeException implements Exception {
final String rootPackage;
final AssetId assetId;
final String initialBuilderLabel;
final String newBuilderLabel;
DuplicateAssetNodeException(this.rootPackage, this.assetId,
this.initialBuilderLabel, this.newBuilderLabel);
@override
String toString() {
final friendlyAsset =
assetId.package == rootPackage ? assetId.path : assetId.uri;
return 'Both $initialBuilderLabel and $newBuilderLabel may output '
'$friendlyAsset. Potential outputs must be unique across all builders. '
'See https://github.com/dart-lang/build/blob/master/docs/faq.md'
'#why-do-builders-need-unique-outputs';
}
}
class AssetGraphCorruptedException implements Exception {}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset_graph/serialization.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of 'graph.dart';
/// Part of the serialized graph, used to ensure versioning constraints.
///
/// This should be incremented any time the serialize/deserialize formats
/// change.
const _version = 23;
/// Deserializes an [AssetGraph] from a [Map].
class _AssetGraphDeserializer {
// Iteration order does not matter
final _idToAssetId = HashMap<int, AssetId>();
final Map _serializedGraph;
_AssetGraphDeserializer._(this._serializedGraph);
factory _AssetGraphDeserializer(List<int> bytes) {
dynamic decoded;
try {
decoded = jsonDecode(utf8.decode(bytes));
} on FormatException {
throw AssetGraphCorruptedException();
}
if (decoded is! Map) throw AssetGraphCorruptedException();
final serializedGraph = decoded as Map;
if (serializedGraph['version'] != _version) {
throw AssetGraphCorruptedException();
}
return _AssetGraphDeserializer._(serializedGraph);
}
/// Perform the deserialization, should only be called once.
AssetGraph deserialize() {
var packageLanguageVersions = {
for (var entry in (_serializedGraph['packageLanguageVersions']
as Map<String, dynamic>)
.entries)
entry.key: entry.value != null
? LanguageVersion.parse(entry.value as String)
: null
};
var graph = AssetGraph._(
_deserializeDigest(_serializedGraph['buildActionsDigest'] as String),
_serializedGraph['dart_version'] as String,
packageLanguageVersions,
);
var packageNames = _serializedGraph['packages'] as List;
// Read in the id => AssetId map from the graph first.
var assetPaths = _serializedGraph['assetPaths'] as List;
for (var i = 0; i < assetPaths.length; i += 2) {
var packageName = packageNames[assetPaths[i + 1] as int] as String;
_idToAssetId[i ~/ 2] = AssetId(packageName, assetPaths[i] as String);
}
// Read in all the nodes and their outputs.
//
// Note that this does not read in the inputs of generated nodes.
for (var serializedItem in _serializedGraph['nodes']) {
graph._add(_deserializeAssetNode(serializedItem as List));
}
// Update the inputs of all generated nodes based on the outputs of the
// current nodes.
for (var node in graph.allNodes) {
// These aren't explicitly added as inputs.
if (node is BuilderOptionsAssetNode) continue;
for (var output in node.outputs) {
if (output == null) {
log.severe('Found a null output from ${node.id} which is a '
'${node.runtimeType}. If you encounter this error please copy '
'the details from this message and add them to '
'https://github.com/dart-lang/build/issues/1804.');
throw AssetGraphCorruptedException();
}
var inputsNode = graph.get(output) as NodeWithInputs;
if (inputsNode == null) {
log.severe('Failed to locate $output referenced from ${node.id} '
'which is a ${node.runtimeType}. If you encounter this error '
'please copy the details from this message and add them to '
'https://github.com/dart-lang/build/issues/1804.');
throw AssetGraphCorruptedException();
}
inputsNode.inputs ??= HashSet<AssetId>();
inputsNode.inputs.add(node.id);
}
if (node is PostProcessAnchorNode) {
graph.get(node.primaryInput).anchorOutputs.add(node.id);
}
}
return graph;
}
AssetNode _deserializeAssetNode(List serializedNode) {
AssetNode node;
var typeId =
_NodeType.values[serializedNode[_AssetField.NodeType.index] as int];
var id = _idToAssetId[serializedNode[_AssetField.Id.index] as int];
var serializedDigest = serializedNode[_AssetField.Digest.index] as String;
var digest = _deserializeDigest(serializedDigest);
switch (typeId) {
case _NodeType.Source:
assert(serializedNode.length == _WrappedAssetNode._length);
node = SourceAssetNode(id, lastKnownDigest: digest);
break;
case _NodeType.SyntheticSource:
assert(serializedNode.length == _WrappedAssetNode._length);
node = SyntheticSourceAssetNode(id);
break;
case _NodeType.Generated:
assert(serializedNode.length == _WrappedGeneratedAssetNode._length);
var offset = _AssetField.values.length;
node = GeneratedAssetNode(
id,
phaseNumber:
serializedNode[_GeneratedField.PhaseNumber.index + offset] as int,
primaryInput: _idToAssetId[
serializedNode[_GeneratedField.PrimaryInput.index + offset]
as int],
state: NodeState.values[
serializedNode[_GeneratedField.State.index + offset] as int],
wasOutput: _deserializeBool(
serializedNode[_GeneratedField.WasOutput.index + offset] as int),
isFailure: _deserializeBool(
serializedNode[_GeneratedField.IsFailure.index + offset] as int),
builderOptionsId: _idToAssetId[
serializedNode[_GeneratedField.BuilderOptions.index + offset]
as int],
lastKnownDigest: digest,
previousInputsDigest: _deserializeDigest(serializedNode[
_GeneratedField.PreviousInputsDigest.index + offset] as String),
isHidden: _deserializeBool(
serializedNode[_GeneratedField.IsHidden.index + offset] as int),
);
break;
case _NodeType.Glob:
assert(serializedNode.length == _WrappedGlobAssetNode._length);
var offset = _AssetField.values.length;
node = GlobAssetNode(
id,
Glob(serializedNode[_GlobField.Glob.index + offset] as String),
serializedNode[_GlobField.PhaseNumber.index + offset] as int,
NodeState
.values[serializedNode[_GlobField.State.index + offset] as int],
lastKnownDigest: digest,
results: _deserializeAssetIds(
serializedNode[_GlobField.Results.index + offset] as List)
?.toList(),
);
break;
case _NodeType.Internal:
assert(serializedNode.length == _WrappedAssetNode._length);
node = InternalAssetNode(id, lastKnownDigest: digest);
break;
case _NodeType.BuilderOptions:
assert(serializedNode.length == _WrappedAssetNode._length);
node = BuilderOptionsAssetNode(id, digest);
break;
case _NodeType.Placeholder:
assert(serializedNode.length == _WrappedAssetNode._length);
node = PlaceHolderAssetNode(id);
break;
case _NodeType.PostProcessAnchor:
assert(serializedNode.length == _WrappedPostProcessAnchorNode._length);
var offset = _AssetField.values.length;
node = PostProcessAnchorNode(
id,
_idToAssetId[
serializedNode[_PostAnchorField.PrimaryInput.index + offset]
as int],
serializedNode[_PostAnchorField.ActionNumber.index + offset] as int,
_idToAssetId[
serializedNode[_PostAnchorField.BuilderOptions.index + offset]
as int],
previousInputsDigest: _deserializeDigest(serializedNode[
_PostAnchorField.PreviousInputsDigest.index + offset]
as String));
break;
}
node.outputs.addAll(_deserializeAssetIds(
serializedNode[_AssetField.Outputs.index] as List));
node.primaryOutputs.addAll(_deserializeAssetIds(
serializedNode[_AssetField.PrimaryOutputs.index] as List));
node.deletedBy.addAll(_deserializeAssetIds(
(serializedNode[_AssetField.DeletedBy.index] as List)?.cast<int>()));
return node;
}
Iterable<AssetId> _deserializeAssetIds(List serializedIds) =>
serializedIds.map((id) => _idToAssetId[id]);
bool _deserializeBool(int value) => value != 0;
}
/// Serializes an [AssetGraph] into a [Map].
class _AssetGraphSerializer {
// Iteration order does not matter
final _assetIdToId = HashMap<AssetId, int>();
final AssetGraph _graph;
_AssetGraphSerializer(this._graph);
/// Perform the serialization, should only be called once.
List<int> serialize() {
var pathId = 0;
// [path0, packageId0, path1, packageId1, ...]
var assetPaths = <dynamic>[];
var packages = _graph._nodesByPackage.keys.toList(growable: false);
for (var node in _graph.allNodes) {
_assetIdToId[node.id] = pathId;
pathId++;
assetPaths..add(node.id.path)..add(packages.indexOf(node.id.package));
}
var result = <String, dynamic>{
'version': _version,
'dart_version': _graph.dartVersion,
'nodes': _graph.allNodes.map(_serializeNode).toList(growable: false),
'buildActionsDigest': _serializeDigest(_graph.buildPhasesDigest),
'packages': packages,
'assetPaths': assetPaths,
'packageLanguageVersions': _graph.packageLanguageVersions
.map((pkg, version) => MapEntry(pkg, version?.toString())),
};
return utf8.encode(json.encode(result));
}
List _serializeNode(AssetNode node) {
if (node is GeneratedAssetNode) {
return _WrappedGeneratedAssetNode(node, this);
} else if (node is PostProcessAnchorNode) {
return _WrappedPostProcessAnchorNode(node, this);
} else if (node is GlobAssetNode) {
return _WrappedGlobAssetNode(node, this);
} else {
return _WrappedAssetNode(node, this);
}
}
int findAssetIndex(AssetId id,
{@required AssetId from, @required String field}) {
final index = _assetIdToId[id];
if (index == null) {
log.severe('The $field field in $from references a non-existent asset '
'$id and will corrupt the asset graph. '
'If you encounter this error please copy '
'the details from this message and add them to '
'https://github.com/dart-lang/build/issues/1804.');
}
return index;
}
}
/// Used to serialize the type of a node using an int.
enum _NodeType {
Source,
SyntheticSource,
Generated,
Internal,
BuilderOptions,
Placeholder,
PostProcessAnchor,
Glob,
}
/// Field indexes for all [AssetNode]s
enum _AssetField {
NodeType,
Id,
Outputs,
PrimaryOutputs,
Digest,
DeletedBy,
}
/// Field indexes for [GeneratedAssetNode]s
enum _GeneratedField {
PrimaryInput,
WasOutput,
IsFailure,
PhaseNumber,
State,
PreviousInputsDigest,
BuilderOptions,
IsHidden,
}
/// Field indexes for [GlobAssetNode]s
enum _GlobField {
PhaseNumber,
State,
Glob,
Results,
}
/// Field indexes for [PostProcessAnchorNode]s.
enum _PostAnchorField {
ActionNumber,
BuilderOptions,
PreviousInputsDigest,
PrimaryInput,
}
/// Wraps an [AssetNode] in a class that implements [List] instead of
/// creating a new list for each one.
class _WrappedAssetNode extends Object with ListMixin implements List {
final AssetNode node;
final _AssetGraphSerializer serializer;
_WrappedAssetNode(this.node, this.serializer);
static final int _length = _AssetField.values.length;
@override
int get length => _length;
@override
set length(void _) => throw UnsupportedError(
'length setter not unsupported for WrappedAssetNode');
@override
Object operator [](int index) {
var fieldId = _AssetField.values[index];
switch (fieldId) {
case _AssetField.NodeType:
if (node is SourceAssetNode) {
return _NodeType.Source.index;
} else if (node is GeneratedAssetNode) {
return _NodeType.Generated.index;
} else if (node is GlobAssetNode) {
return _NodeType.Glob.index;
} else if (node is SyntheticSourceAssetNode) {
return _NodeType.SyntheticSource.index;
} else if (node is InternalAssetNode) {
return _NodeType.Internal.index;
} else if (node is BuilderOptionsAssetNode) {
return _NodeType.BuilderOptions.index;
} else if (node is PlaceHolderAssetNode) {
return _NodeType.Placeholder.index;
} else if (node is PostProcessAnchorNode) {
return _NodeType.PostProcessAnchor.index;
} else {
throw StateError('Unrecognized node type');
}
break;
case _AssetField.Id:
return serializer.findAssetIndex(node.id, from: node.id, field: 'id');
case _AssetField.Outputs:
return node.outputs
.map((id) =>
serializer.findAssetIndex(id, from: node.id, field: 'outputs'))
.toList(growable: false);
case _AssetField.PrimaryOutputs:
return node.primaryOutputs
.map((id) => serializer.findAssetIndex(id,
from: node.id, field: 'primaryOutputs'))
.toList(growable: false);
case _AssetField.Digest:
return _serializeDigest(node.lastKnownDigest);
case _AssetField.DeletedBy:
return node.deletedBy
.map((id) => serializer.findAssetIndex(id,
from: node.id, field: 'deletedBy'))
.toList(growable: false);
default:
throw RangeError.index(index, this);
}
}
@override
operator []=(void _, void __) =>
throw UnsupportedError('[]= not supported for WrappedAssetNode');
}
/// Wraps a [GeneratedAssetNode] in a class that implements [List] instead of
/// creating a new list for each one.
class _WrappedGeneratedAssetNode extends _WrappedAssetNode {
final GeneratedAssetNode generatedNode;
/// Offset in the serialized format for additional fields in this class but
/// not in [_WrappedAssetNode].
///
/// Indexes below this number are forwarded to `super[index]`.
static final int _serializedOffset = _AssetField.values.length;
static final int _length = _serializedOffset + _GeneratedField.values.length;
@override
int get length => _length;
_WrappedGeneratedAssetNode(
this.generatedNode, _AssetGraphSerializer serializer)
: super(generatedNode, serializer);
@override
Object operator [](int index) {
if (index < _serializedOffset) return super[index];
var fieldId = _GeneratedField.values[index - _serializedOffset];
switch (fieldId) {
case _GeneratedField.PrimaryInput:
return generatedNode.primaryInput != null
? serializer.findAssetIndex(generatedNode.primaryInput,
from: generatedNode.id, field: 'primaryInput')
: null;
case _GeneratedField.WasOutput:
return _serializeBool(generatedNode.wasOutput);
case _GeneratedField.IsFailure:
return _serializeBool(generatedNode.isFailure);
case _GeneratedField.PhaseNumber:
return generatedNode.phaseNumber;
case _GeneratedField.State:
return generatedNode.state.index;
case _GeneratedField.PreviousInputsDigest:
return _serializeDigest(generatedNode.previousInputsDigest);
case _GeneratedField.BuilderOptions:
return serializer.findAssetIndex(generatedNode.builderOptionsId,
from: generatedNode.id, field: 'builderOptions');
case _GeneratedField.IsHidden:
return _serializeBool(generatedNode.isHidden);
default:
throw RangeError.index(index, this);
}
}
}
/// Wraps a [GlobAssetNode] in a class that implements [List] instead of
/// creating a new list for each one.
class _WrappedGlobAssetNode extends _WrappedAssetNode {
final GlobAssetNode globNode;
/// Offset in the serialized format for additional fields in this class but
/// not in [_WrappedAssetNode].
///
/// Indexes below this number are forwarded to `super[index]`.
static final int _serializedOffset = _AssetField.values.length;
static final int _length = _serializedOffset + _GlobField.values.length;
@override
int get length => _length;
_WrappedGlobAssetNode(this.globNode, _AssetGraphSerializer serializer)
: super(globNode, serializer);
@override
Object operator [](int index) {
if (index < _serializedOffset) return super[index];
var fieldId = _GlobField.values[index - _serializedOffset];
switch (fieldId) {
case _GlobField.PhaseNumber:
return globNode.phaseNumber;
case _GlobField.State:
return globNode.state.index;
case _GlobField.Glob:
return globNode.glob.pattern;
case _GlobField.Results:
return globNode.results
.map((id) => serializer.findAssetIndex(id,
from: globNode.id, field: 'results'))
.toList(growable: false);
default:
throw RangeError.index(index, this);
}
}
}
/// Wraps a [PostProcessAnchorNode] in a class that implements [List] instead of
/// creating a new list for each one.
class _WrappedPostProcessAnchorNode extends _WrappedAssetNode {
final PostProcessAnchorNode wrappedNode;
/// Offset in the serialized format for additional fields in this class but
/// not in [_WrappedAssetNode].
///
/// Indexes below this number are forwarded to `super[index]`.
static final int _serializedOffset = _AssetField.values.length;
static final int _length = _serializedOffset + _PostAnchorField.values.length;
@override
int get length => _length;
_WrappedPostProcessAnchorNode(
this.wrappedNode, _AssetGraphSerializer serializer)
: super(wrappedNode, serializer);
@override
Object operator [](int index) {
if (index < _serializedOffset) return super[index];
var fieldId = _PostAnchorField.values[index - _serializedOffset];
switch (fieldId) {
case _PostAnchorField.ActionNumber:
return wrappedNode.actionNumber;
case _PostAnchorField.BuilderOptions:
return serializer.findAssetIndex(wrappedNode.builderOptionsId,
from: wrappedNode.id, field: 'builderOptions');
case _PostAnchorField.PreviousInputsDigest:
return _serializeDigest(wrappedNode.previousInputsDigest);
case _PostAnchorField.PrimaryInput:
return wrappedNode.primaryInput != null
? serializer.findAssetIndex(wrappedNode.primaryInput,
from: wrappedNode.id, field: 'primaryInput')
: null;
default:
throw RangeError.index(index, this);
}
}
}
Digest _deserializeDigest(String serializedDigest) =>
serializedDigest == null ? null : Digest(base64.decode(serializedDigest));
String _serializeDigest(Digest digest) =>
digest == null ? null : base64.encode(digest.bytes);
int _serializeBool(bool value) => value ? 1 : 0;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset_graph/optional_output_tracker.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:build_runner_core/build_runner_core.dart';
import '../generate/phase.dart';
import '../util/build_dirs.dart';
import 'graph.dart';
import 'node.dart';
/// A cache of the results of checking whether outputs from optional build steps
/// were required by in the current build.
///
/// An optional output becomes required if:
/// - Any of it's transitive outputs is required (based on the criteria below).
/// - It was output by the same build step as any required output.
///
/// Any outputs from non-optional phases are considered required, unless the
/// following are all true.
/// - [_buildDirs] is non-empty.
/// - The output lives in a non-lib directory.
/// - The outputs path is not prefixed by one of [_buildDirs].
/// - If [_buildFilters] is non-empty and the output doesn't match one of the
/// filters.
///
/// Non-required optional output might still exist in the generated directory
/// and the asset graph but we should avoid serving them, outputting them in
/// the merged directories, or considering a failed output as an overall.
class OptionalOutputTracker {
final _checkedOutputs = <AssetId, bool>{};
final AssetGraph _assetGraph;
final Set<String> _buildDirs;
final Set<BuildFilter> _buildFilters;
final List<BuildPhase> _buildPhases;
OptionalOutputTracker(
this._assetGraph, this._buildDirs, this._buildFilters, this._buildPhases);
/// Returns whether [output] is required.
///
/// If necessary crawls transitive outputs that read [output] or any other
/// assets generated by the same phase until it finds one which is required.
///
/// [currentlyChecking] is used to aovid repeatedly checking the same outputs.
bool isRequired(AssetId output, [Set<AssetId> currentlyChecking]) {
currentlyChecking ??= <AssetId>{};
if (currentlyChecking.contains(output)) return false;
currentlyChecking.add(output);
final node = _assetGraph.get(output);
if (node is! GeneratedAssetNode) return true;
final generatedNode = node as GeneratedAssetNode;
final phase = _buildPhases[generatedNode.phaseNumber];
if (!phase.isOptional &&
shouldBuildForDirs(output, _buildDirs, _buildFilters, phase)) {
return true;
}
return _checkedOutputs.putIfAbsent(
output,
() =>
generatedNode.outputs
.any((o) => isRequired(o, currentlyChecking)) ||
_assetGraph
.outputsForPhase(output.package, generatedNode.phaseNumber)
.where((n) => n.primaryInput == generatedNode.primaryInput)
.map((n) => n.id)
.any((o) => isRequired(o, currentlyChecking)));
}
/// Clears the cache of which assets were required.
///
/// If the tracker is used across multiple builds it must be reset in between
/// each one.
void reset() {
_checkedOutputs.clear();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset_graph/node.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:convert';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import 'package:meta/meta.dart';
import '../generate/phase.dart';
/// A node in the asset graph which may be an input to other assets.
abstract class AssetNode {
final AssetId id;
/// The assets that any [Builder] in the build graph declares it may output
/// when run on this asset.
final Set<AssetId> primaryOutputs = <AssetId>{};
/// The [AssetId]s of all generated assets which are output by a [Builder]
/// which reads this asset.
final Set<AssetId> outputs = <AssetId>{};
/// The [AssetId]s of all [PostProcessAnchorNode] assets for which this node
/// is the primary input.
final Set<AssetId> anchorOutputs = <AssetId>{};
/// The [Digest] for this node in its last known state.
///
/// May be `null` if this asset has no outputs, or if it doesn't actually
/// exist.
Digest lastKnownDigest;
/// Whether or not this node was an output of this build.
bool get isGenerated => false;
/// Whether or not this asset type can be read.
///
/// This does not indicate whether or not this specific node actually exists
/// at this moment in time.
bool get isReadable => true;
/// The IDs of the [PostProcessAnchorNode] for post process builder which
/// requested to delete this asset.
final Set<AssetId> deletedBy = <AssetId>{};
/// Whether the node is deleted.
///
/// Deleted nodes are ignored in the final merge step and watch handlers.
bool get isDeleted => deletedBy.isNotEmpty;
/// Whether or not this node can be read by a builder as a primary or
/// secondary input.
///
/// Some nodes are valid primary inputs but are not readable (see
/// [PlaceHolderAssetNode]), while others are readable in the overall build
/// system but are not valid builder inputs (see [InternalAssetNode]).
bool get isValidInput => true;
/// Whether or not changes to this node will have any effect on other nodes.
///
/// Be default, if we haven't computed a digest for this asset and it has no
/// outputs, then it isn't interesting.
///
/// Checking for a digest alone isn't enough because a file may be deleted
/// and re-added, in which case it won't have a digest.
bool get isInteresting => outputs.isNotEmpty || lastKnownDigest != null;
AssetNode(this.id, {this.lastKnownDigest});
/// Work around issue where you can't mixin classes into a class with optional
/// constructor args.
AssetNode._forMixins(this.id);
/// Work around issue where you can't mixin classes into a class with optional
/// constructor args, this one includes the digest.
AssetNode._forMixinsWithDigest(this.id, this.lastKnownDigest);
@override
String toString() => 'AssetNode: $id';
}
/// A node representing some internal asset.
///
/// These nodes are not used as primary inputs, but they are tracked in the
/// asset graph and are readable.
class InternalAssetNode extends AssetNode {
// These don't have [outputs] but they are interesting regardless.
@override
bool get isInteresting => true;
@override
bool get isValidInput => false;
InternalAssetNode(AssetId id, {Digest lastKnownDigest})
: super(id, lastKnownDigest: lastKnownDigest);
@override
String toString() => 'InternalAssetNode: $id';
}
/// A node which is an original source asset (not generated).
class SourceAssetNode extends AssetNode {
SourceAssetNode(AssetId id, {Digest lastKnownDigest})
: super(id, lastKnownDigest: lastKnownDigest);
@override
String toString() => 'SourceAssetNode: $id';
}
/// States for nodes that can be invalidated.
enum NodeState {
// This node does not need an update, and no checks need to be performed.
upToDate,
// This node may need an update, the inputs hash should be checked for
// changes.
mayNeedUpdate,
// This node definitely needs an update, the inputs hash check can be skipped.
definitelyNeedsUpdate,
}
/// A generated node in the asset graph.
class GeneratedAssetNode extends AssetNode implements NodeWithInputs {
@override
bool get isGenerated => true;
@override
final int phaseNumber;
/// The primary input which generated this node.
final AssetId primaryInput;
@override
NodeState state;
/// Whether the asset was actually output.
bool wasOutput;
/// All the inputs that were read when generating this asset, or deciding not
/// to generate it.
///
/// This needs to be an ordered set because we compute combined input digests
/// using this later on.
@override
HashSet<AssetId> inputs;
/// A digest combining all digests of all previous inputs.
///
/// Used to determine whether all the inputs to a build step are identical to
/// the previous run, indicating that the previous output is still valid.
Digest previousInputsDigest;
/// Whether the action which did or would produce this node failed.
bool isFailure;
/// The [AssetId] of the node representing the [BuilderOptions] used to create
/// this node.
final AssetId builderOptionsId;
/// Whether the asset should be placed in the build cache.
final bool isHidden;
GeneratedAssetNode(
AssetId id, {
Digest lastKnownDigest,
Iterable<AssetId> inputs,
this.previousInputsDigest,
@required this.isHidden,
@required this.state,
@required this.phaseNumber,
@required this.wasOutput,
@required this.isFailure,
@required this.primaryInput,
@required this.builderOptionsId,
}) : inputs = inputs != null ? HashSet.from(inputs) : HashSet(),
super(id, lastKnownDigest: lastKnownDigest);
@override
String toString() =>
'GeneratedAssetNode: $id generated from input $primaryInput.';
}
/// A node which is not a generated or source asset.
///
/// These are typically not readable or valid as inputs.
abstract class _SyntheticAssetNode implements AssetNode {
@override
bool get isReadable => false;
@override
bool get isValidInput => false;
}
/// A [_SyntheticAssetNode] representing a non-existent source.
///
/// Typically these are created as a result of `canRead` calls for assets that
/// don't exist in the graph. We still need to set up proper dependencies so
/// that if that asset gets added later the outputs are properly invalidated.
class SyntheticSourceAssetNode extends AssetNode with _SyntheticAssetNode {
SyntheticSourceAssetNode(AssetId id) : super._forMixins(id);
}
/// A [_SyntheticAssetNode] which represents an individual [BuilderOptions]
/// object.
///
/// These are used to track the state of a [BuilderOptions] object, and all
/// [GeneratedAssetNode]s should depend on one of these nodes, which represents
/// their configuration.
class BuilderOptionsAssetNode extends AssetNode with _SyntheticAssetNode {
BuilderOptionsAssetNode(AssetId id, Digest lastKnownDigest)
: super._forMixinsWithDigest(id, lastKnownDigest);
@override
String toString() => 'BuildOptionsAssetNode: $id';
}
/// Placeholder assets are magic files that are usable as inputs but are not
/// readable.
class PlaceHolderAssetNode extends AssetNode with _SyntheticAssetNode {
@override
bool get isValidInput => true;
PlaceHolderAssetNode(AssetId id) : super._forMixins(id);
@override
String toString() => 'PlaceHolderAssetNode: $id';
}
/// A [_SyntheticAssetNode] which is created for each [primaryInput] to a
/// [PostBuildAction].
///
/// The [outputs] of this node are the individual outputs created for the
/// [primaryInput] during the [PostBuildAction] at index [actionNumber].
class PostProcessAnchorNode extends AssetNode with _SyntheticAssetNode {
final int actionNumber;
final AssetId builderOptionsId;
final AssetId primaryInput;
Digest previousInputsDigest;
PostProcessAnchorNode(
AssetId id, this.primaryInput, this.actionNumber, this.builderOptionsId,
{this.previousInputsDigest})
: super._forMixins(id);
factory PostProcessAnchorNode.forInputAndAction(
AssetId primaryInput, int actionNumber, AssetId builderOptionsId) {
return PostProcessAnchorNode(
primaryInput.addExtension('.post_anchor.$actionNumber'),
primaryInput,
actionNumber,
builderOptionsId);
}
}
/// A node representing a glob ran from a builder.
///
/// The [id] must always be unique to a given package, phase, and glob
/// pattern.
class GlobAssetNode extends InternalAssetNode implements NodeWithInputs {
final Glob glob;
/// All the potential inputs matching this glob.
///
/// This field differs from [results] in that [GeneratedAssetNode] which may
/// have been readable but were not output are included here and not in
/// [results].
@override
HashSet<AssetId> inputs;
@override
bool get isReadable => false;
@override
final int phaseNumber;
/// The actual results of the glob.
List<AssetId> results;
@override
NodeState state;
GlobAssetNode(AssetId id, this.glob, this.phaseNumber, this.state,
{this.inputs, Digest lastKnownDigest, this.results})
: super(id, lastKnownDigest: lastKnownDigest);
static AssetId createId(String package, Glob glob, int phaseNum) => AssetId(
package, 'glob.$phaseNum.${base64.encode(utf8.encode(glob.pattern))}');
}
/// A node which has [inputs], a [NodeState], and a [phaseNumber].
abstract class NodeWithInputs implements AssetNode {
HashSet<AssetId> inputs;
int get phaseNumber;
NodeState state;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset_graph/graph.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'package:build/build.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:watcher/watcher.dart';
import '../generate/phase.dart';
import '../package_graph/package_graph.dart';
import 'exceptions.dart';
import 'node.dart';
part 'serialization.dart';
/// All the [AssetId]s involved in a build, and all of their outputs.
class AssetGraph {
/// All the [AssetNode]s in the graph, indexed by package and then path.
final _nodesByPackage = <String, Map<String, AssetNode>>{};
/// A [Digest] of the build actions this graph was originally created with.
///
/// When an [AssetGraph] is deserialized we check whether or not it matches
/// the new [BuildPhase]s and throw away the graph if it doesn't.
final Digest buildPhasesDigest;
/// The [Platform.version] this graph was created with.
final String dartVersion;
final Map<String, LanguageVersion> packageLanguageVersions;
AssetGraph._(
this.buildPhasesDigest, this.dartVersion, this.packageLanguageVersions);
/// Deserializes this graph.
factory AssetGraph.deserialize(List<int> serializedGraph) =>
_AssetGraphDeserializer(serializedGraph).deserialize();
static Future<AssetGraph> build(
List<BuildPhase> buildPhases,
Set<AssetId> sources,
Set<AssetId> internalSources,
PackageGraph packageGraph,
AssetReader digestReader) async {
var packageLanguageVersions = {
for (var pkg in packageGraph.allPackages.values)
pkg.name: pkg.languageVersion
};
var graph = AssetGraph._(computeBuildPhasesDigest(buildPhases),
Platform.version, packageLanguageVersions);
var placeholders = graph._addPlaceHolderNodes(packageGraph);
var sourceNodes = graph._addSources(sources);
graph
.._addBuilderOptionsNodes(buildPhases)
.._addOutputsForSources(buildPhases, sources, packageGraph.root.name,
placeholders: placeholders);
// Pre-emptively compute digests for the nodes we know have outputs.
await graph._setLastKnownDigests(
sourceNodes.where((node) => node.primaryOutputs.isNotEmpty),
digestReader);
// Always compute digests for all internal nodes.
var internalNodes = graph._addInternalSources(internalSources);
await graph._setLastKnownDigests(internalNodes, digestReader);
return graph;
}
List<int> serialize() => _AssetGraphSerializer(this).serialize();
/// Checks if [id] exists in the graph.
bool contains(AssetId id) =>
_nodesByPackage[id.package]?.containsKey(id.path) ?? false;
/// Gets the [AssetNode] for [id], if one exists.
AssetNode get(AssetId id) {
var pkg = _nodesByPackage[id?.package];
if (pkg == null) return null;
return pkg[id.path];
}
/// Adds [node] to the graph if it doesn't exist.
///
/// Throws a [StateError] if it already exists in the graph.
void _add(AssetNode node) {
var existing = get(node.id);
if (existing != null) {
if (existing is SyntheticSourceAssetNode) {
// Don't call _removeRecursive, that recursively removes all transitive
// primary outputs. We only want to remove this node.
_nodesByPackage[existing.id.package].remove(existing.id.path);
node.outputs.addAll(existing.outputs);
node.primaryOutputs.addAll(existing.primaryOutputs);
} else {
throw StateError(
'Tried to add node ${node.id} to the asset graph but it already '
'exists.');
}
}
_nodesByPackage.putIfAbsent(node.id.package, () => {})[node.id.path] = node;
}
/// Adds [assetIds] as [InternalAssetNode]s to this graph.
Iterable<AssetNode> _addInternalSources(Set<AssetId> assetIds) sync* {
for (var id in assetIds) {
var node = InternalAssetNode(id);
_add(node);
yield node;
}
}
/// Adds [PlaceHolderAssetNode]s for every package in [packageGraph].
Set<AssetId> _addPlaceHolderNodes(PackageGraph packageGraph) {
var placeholders = placeholderIdsFor(packageGraph);
for (var id in placeholders) {
_add(PlaceHolderAssetNode(id));
}
return placeholders;
}
/// Adds [assetIds] as [AssetNode]s to this graph, and returns the newly
/// created nodes.
List<AssetNode> _addSources(Set<AssetId> assetIds) {
return assetIds.map((id) {
var node = SourceAssetNode(id);
_add(node);
return node;
}).toList();
}
/// Adds [BuilderOptionsAssetNode]s for all [buildPhases] to this graph.
void _addBuilderOptionsNodes(List<BuildPhase> buildPhases) {
for (var phaseNum = 0; phaseNum < buildPhases.length; phaseNum++) {
var phase = buildPhases[phaseNum];
if (phase is InBuildPhase) {
add(BuilderOptionsAssetNode(builderOptionsIdForAction(phase, phaseNum),
computeBuilderOptionsDigest(phase.builderOptions)));
} else if (phase is PostBuildPhase) {
var actionNum = 0;
for (var builderAction in phase.builderActions) {
add(BuilderOptionsAssetNode(
builderOptionsIdForAction(builderAction, actionNum),
computeBuilderOptionsDigest(builderAction.builderOptions)));
actionNum++;
}
} else {
throw StateError('Invalid action type $phase');
}
}
}
/// Uses [digestReader] to compute the [Digest] for [nodes] and set the
/// `lastKnownDigest` field.
Future<void> _setLastKnownDigests(
Iterable<AssetNode> nodes, AssetReader digestReader) async {
await Future.wait(nodes.map((node) async {
node.lastKnownDigest = await digestReader.digest(node.id);
}));
}
/// Removes the node representing [id] from the graph, and all of its
/// `primaryOutput`s.
///
/// Also removes all edges between all removed nodes and other nodes.
///
/// Returns a [Set<AssetId>] of all removed nodes.
Set<AssetId> _removeRecursive(AssetId id, {Set<AssetId> removedIds}) {
removedIds ??= <AssetId>{};
var node = get(id);
if (node == null) return removedIds;
removedIds.add(id);
for (var anchor in node.anchorOutputs.toList()) {
_removeRecursive(anchor, removedIds: removedIds);
}
for (var output in node.primaryOutputs.toList()) {
_removeRecursive(output, removedIds: removedIds);
}
for (var output in node.outputs) {
var inputsNode = get(output) as NodeWithInputs;
if (inputsNode != null) {
inputsNode.inputs.remove(id);
if (inputsNode is GlobAssetNode) {
inputsNode.results.remove(id);
}
}
}
if (node is NodeWithInputs) {
for (var input in node.inputs) {
var inputNode = get(input);
// We may have already removed this node entirely.
if (inputNode != null) {
inputNode.outputs.remove(id);
inputNode.primaryOutputs.remove(id);
}
}
if (node is GeneratedAssetNode) {
get(node.builderOptionsId).outputs.remove(id);
}
}
// Synthetic nodes need to be kept to retain dependency tracking.
if (node is! SyntheticSourceAssetNode) {
_nodesByPackage[id.package].remove(id.path);
}
return removedIds;
}
/// All nodes in the graph, whether source files or generated outputs.
Iterable<AssetNode> get allNodes =>
_nodesByPackage.values.expand((pkdIds) => pkdIds.values);
/// All nodes in the graph for `package`.
Iterable<AssetNode> packageNodes(String package) =>
_nodesByPackage[package]?.values ?? [];
/// All the generated outputs in the graph.
Iterable<AssetId> get outputs =>
allNodes.where((n) => n.isGenerated).map((n) => n.id);
/// The outputs which were, or would have been, produced by failing actions.
Iterable<GeneratedAssetNode> get failedOutputs => allNodes
.where((n) =>
n is GeneratedAssetNode &&
n.isFailure &&
n.state == NodeState.upToDate)
.map((n) => n as GeneratedAssetNode);
/// All the generated outputs for a particular phase.
Iterable<GeneratedAssetNode> outputsForPhase(String package, int phase) =>
packageNodes(package)
.whereType<GeneratedAssetNode>()
.where((n) => n.phaseNumber == phase);
/// All the source files in the graph.
Iterable<AssetId> get sources =>
allNodes.whereType<SourceAssetNode>().map((n) => n.id);
/// Updates graph structure, invalidating and deleting any outputs that were
/// affected.
///
/// Returns the list of [AssetId]s that were invalidated.
Future<Set<AssetId>> updateAndInvalidate(
List<BuildPhase> buildPhases,
Map<AssetId, ChangeType> updates,
String rootPackage,
Future Function(AssetId id) delete,
AssetReader digestReader) async {
var newIds = <AssetId>{};
var modifyIds = <AssetId>{};
var removeIds = <AssetId>{};
updates.forEach((id, changeType) {
if (changeType != ChangeType.ADD && get(id) == null) return;
switch (changeType) {
case ChangeType.ADD:
newIds.add(id);
break;
case ChangeType.MODIFY:
modifyIds.add(id);
break;
case ChangeType.REMOVE:
removeIds.add(id);
break;
}
});
var newAndModifiedNodes = modifyIds.map(get).toList()
..addAll(_addSources(newIds));
// Pre-emptively compute digests for the new and modified nodes we know have
// outputs.
await _setLastKnownDigests(
newAndModifiedNodes.where((node) =>
node.isValidInput &&
(node.outputs.isNotEmpty ||
node.primaryOutputs.isNotEmpty ||
node.lastKnownDigest != null)),
digestReader);
// Collects the set of all transitive ids to be removed from the graph,
// based on the removed `SourceAssetNode`s by following the
// `primaryOutputs`.
var transitiveRemovedIds = <AssetId>{};
void addTransitivePrimaryOutputs(AssetId id) {
transitiveRemovedIds.add(id);
get(id).primaryOutputs.forEach(addTransitivePrimaryOutputs);
}
removeIds
.where((id) => get(id) is SourceAssetNode)
.forEach(addTransitivePrimaryOutputs);
// The generated nodes to actually delete from the file system.
var idsToDelete = Set<AssetId>.from(transitiveRemovedIds)
..removeAll(removeIds);
// We definitely need to update manually deleted outputs.
for (var deletedOutput
in removeIds.map(get).whereType<GeneratedAssetNode>()) {
deletedOutput.state = NodeState.definitelyNeedsUpdate;
}
// Transitively invalidates all assets. This needs to happen after the
// structure of the graph has been updated.
var invalidatedIds = <AssetId>{};
var newGeneratedOutputs =
_addOutputsForSources(buildPhases, newIds, rootPackage);
var allNewAndDeletedIds =
Set.of(newGeneratedOutputs.followedBy(transitiveRemovedIds));
void invalidateNodeAndDeps(AssetId id) {
var node = get(id);
if (node == null) return;
if (!invalidatedIds.add(id)) return;
if (node is NodeWithInputs && node.state == NodeState.upToDate) {
node.state = NodeState.mayNeedUpdate;
}
// Update all outputs of this asset as well.
for (var output in node.outputs) {
invalidateNodeAndDeps(output);
}
}
for (var changed in updates.keys.followedBy(newGeneratedOutputs)) {
invalidateNodeAndDeps(changed);
}
// For all new or deleted assets, check if they match any glob nodes and
// invalidate those.
for (var id in allNewAndDeletedIds) {
var samePackageGlobNodes = packageNodes(id.package)
.whereType<GlobAssetNode>()
.where((n) => n.state == NodeState.upToDate);
for (final node in samePackageGlobNodes) {
if (node.glob.matches(id.path)) {
invalidateNodeAndDeps(node.id);
node.state = NodeState.mayNeedUpdate;
}
}
}
// Delete all the invalidated assets, then remove them from the graph. This
// order is important because some `AssetWriter`s throw if the id is not in
// the graph.
await Future.wait(idsToDelete.map(delete));
// Remove all deleted source assets from the graph, which also recursively
// removes all their primary outputs.
for (var id in removeIds.where((id) => get(id) is SourceAssetNode)) {
invalidateNodeAndDeps(id);
_removeRecursive(id);
}
return invalidatedIds;
}
/// Crawl up primary inputs to see if the original Source file matches the
/// glob on [action].
bool _actionMatches(BuildAction action, AssetId input) {
if (input.package != action.package) return false;
if (!action.generateFor.matches(input)) return false;
Iterable<String> inputExtensions;
if (action is InBuildPhase) {
inputExtensions = action.builder.buildExtensions.keys;
} else if (action is PostBuildAction) {
inputExtensions = action.builder.inputExtensions;
} else {
throw StateError('Unrecognized action type $action');
}
if (!inputExtensions.any(input.path.endsWith)) {
return false;
}
var inputNode = get(input);
while (inputNode is GeneratedAssetNode) {
inputNode = get((inputNode as GeneratedAssetNode).primaryInput);
}
return action.targetSources.matches(inputNode.id);
}
/// Returns a set containing [newSources] plus any new generated sources
/// based on [buildPhases], and updates this graph to contain all the
/// new outputs.
///
/// If [placeholders] is supplied they will be added to [newSources] to create
/// the full input set.
Set<AssetId> _addOutputsForSources(
List<BuildPhase> buildPhases, Set<AssetId> newSources, String rootPackage,
{Set<AssetId> placeholders}) {
var allInputs = Set<AssetId>.from(newSources);
if (placeholders != null) allInputs.addAll(placeholders);
for (var phaseNum = 0; phaseNum < buildPhases.length; phaseNum++) {
var phase = buildPhases[phaseNum];
if (phase is InBuildPhase) {
allInputs.addAll(_addInBuildPhaseOutputs(
phase,
phaseNum,
allInputs,
buildPhases,
rootPackage,
));
} else if (phase is PostBuildPhase) {
_addPostBuildPhaseAnchors(phase, allInputs);
} else {
throw StateError('Unrecognized phase type $phase');
}
}
return allInputs;
}
/// Adds all [GeneratedAssetNode]s for [phase] given [allInputs].
///
/// May remove some items from [allInputs], if they are deemed to actually be
/// outputs of this phase and not original sources.
///
/// Returns all newly created asset ids.
Set<AssetId> _addInBuildPhaseOutputs(
InBuildPhase phase,
int phaseNum,
Set<AssetId> allInputs,
List<BuildPhase> buildPhases,
String rootPackage) {
var phaseOutputs = <AssetId>{};
var buildOptionsNodeId = builderOptionsIdForAction(phase, phaseNum);
var builderOptionsNode = get(buildOptionsNodeId) as BuilderOptionsAssetNode;
var inputs =
allInputs.where((input) => _actionMatches(phase, input)).toList();
for (var input in inputs) {
// We might have deleted some inputs during this loop, if they turned
// out to be generated assets.
if (!allInputs.contains(input)) continue;
var node = get(input);
assert(node != null, 'The node from `$input` does not exist.');
var outputs = expectedOutputs(phase.builder, input);
phaseOutputs.addAll(outputs);
node.primaryOutputs.addAll(outputs);
var deleted = _addGeneratedOutputs(
outputs, phaseNum, builderOptionsNode, buildPhases, rootPackage,
primaryInput: input, isHidden: phase.hideOutput);
allInputs.removeAll(deleted);
// We may delete source nodes that were producing outputs previously.
// Detect this by checking for deleted nodes that no longer exist in the
// graph at all, and remove them from `phaseOutputs`.
phaseOutputs.removeAll(deleted.where((id) => !contains(id)));
}
return phaseOutputs;
}
/// Adds all [PostProcessAnchorNode]s for [phase] given [allInputs];
///
/// Does not return anything because [PostProcessAnchorNode]s are synthetic
/// and should not be treated as inputs.
void _addPostBuildPhaseAnchors(PostBuildPhase phase, Set<AssetId> allInputs) {
var actionNum = 0;
for (var action in phase.builderActions) {
var inputs = allInputs.where((input) => _actionMatches(action, input));
for (var input in inputs) {
var buildOptionsNodeId = builderOptionsIdForAction(action, actionNum);
var anchor = PostProcessAnchorNode.forInputAndAction(
input, actionNum, buildOptionsNodeId);
add(anchor);
get(input).anchorOutputs.add(anchor.id);
}
actionNum++;
}
}
/// Adds [outputs] as [GeneratedAssetNode]s to the graph.
///
/// If there are existing [SourceAssetNode]s or [SyntheticSourceAssetNode]s
/// that overlap the [GeneratedAssetNode]s, then they will be replaced with
/// [GeneratedAssetNode]s, and all their `primaryOutputs` will be removed
/// from the graph as well. The return value is the set of assets that were
/// removed from the graph.
Set<AssetId> _addGeneratedOutputs(
Iterable<AssetId> outputs,
int phaseNumber,
BuilderOptionsAssetNode builderOptionsNode,
List<BuildPhase> buildPhases,
String rootPackage,
{AssetId primaryInput,
@required bool isHidden}) {
var removed = <AssetId>{};
for (var output in outputs) {
AssetNode existing;
// When any outputs aren't hidden we can pick up old generated outputs as
// regular `AssetNode`s, we need to delete them and all their primary
// outputs, and replace them with a `GeneratedAssetNode`.
if (contains(output)) {
existing = get(output);
if (existing is GeneratedAssetNode) {
throw DuplicateAssetNodeException(
rootPackage,
existing.id,
(buildPhases[existing.phaseNumber] as InBuildPhase).builderLabel,
(buildPhases[phaseNumber] as InBuildPhase).builderLabel);
}
_removeRecursive(output, removedIds: removed);
}
var newNode = GeneratedAssetNode(output,
phaseNumber: phaseNumber,
primaryInput: primaryInput,
state: NodeState.definitelyNeedsUpdate,
wasOutput: false,
isFailure: false,
builderOptionsId: builderOptionsNode.id,
isHidden: isHidden);
if (existing != null) {
newNode.outputs.addAll(existing.outputs);
}
builderOptionsNode.outputs.add(output);
_add(newNode);
}
return removed;
}
@override
String toString() => allNodes.toList().toString();
// TODO remove once tests are updated
void add(AssetNode node) => _add(node);
Set<AssetId> remove(AssetId id) => _removeRecursive(id);
}
/// Computes a [Digest] for [buildPhases] which can be used to compare one set
/// of [BuildPhase]s against another.
Digest computeBuildPhasesDigest(Iterable<BuildPhase> buildPhases) {
var digestSink = AccumulatorSink<Digest>();
md5.startChunkedConversion(digestSink)
..add(buildPhases.map((phase) => phase.identity).toList())
..close();
assert(digestSink.events.length == 1);
return digestSink.events.first;
}
Digest computeBuilderOptionsDigest(BuilderOptions options) =>
md5.convert(utf8.encode(json.encode(options.config)));
AssetId builderOptionsIdForAction(BuildAction action, int actionNum) {
if (action is InBuildPhase) {
return AssetId(action.package, 'Phase$actionNum.builderOptions');
} else if (action is PostBuildAction) {
return AssetId(action.package, 'PostPhase$actionNum.builderOptions');
} else {
throw StateError('Unsupported action type $action');
}
}
Set<AssetId> placeholderIdsFor(PackageGraph packageGraph) =>
Set<AssetId>.from(packageGraph.allPackages.keys.expand((package) => [
AssetId(package, r'lib/$lib$'),
AssetId(package, r'test/$test$'),
AssetId(package, r'web/$web$'),
AssetId(package, r'$package$'),
]));
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/performance_tracking/performance_tracking_resolvers.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import '../generate/performance_tracker.dart';
class PerformanceTrackingResolvers implements Resolvers {
final Resolvers _delegate;
final BuilderActionTracker _tracker;
PerformanceTrackingResolvers(this._delegate, this._tracker);
@override
Future<ReleasableResolver> get(BuildStep buildStep) =>
_tracker.trackStage('ResolverGet', () => _delegate.get(buildStep));
@override
void reset() => _delegate.reset();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/environment/build_environment.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../generate/build_directory.dart';
import '../generate/build_result.dart';
import '../generate/finalized_assets_view.dart';
/// Utilities to interact with the environment in which a build is running.
///
/// All side effects and user interaction should go through the build
/// environment. An IO based environment can write to disk and interact through
/// stdout/stdin, while a theoretical web or remote environment might interact
/// over HTTP.
abstract class BuildEnvironment {
RunnerAssetReader get reader;
RunnerAssetWriter get writer;
void onLog(LogRecord record);
/// Prompt the user for input.
///
/// The message and choices are displayed to the user and the index of the
/// chosen option is returned.
///
/// If this environmment is non-interactive (such as when running in a test)
/// this method should throw [NonInteractiveBuildException].
Future<int> prompt(String message, List<String> choices);
/// Invoked after each build, can modify the [BuildResult] in any way, even
/// converting it to a failure.
///
/// The [finalizedAssetsView] can only be used until the returned [Future]
/// completes, it will expire afterwords since it can no longer guarantee a
/// consistent state.
///
/// By default this returns the original result.
///
/// Any operation may be performed, as determined by environment.
Future<BuildResult> finalizeBuild(
BuildResult buildResult,
FinalizedAssetsView finalizedAssetsView,
AssetReader assetReader,
Set<BuildDirectory> buildDirs) =>
Future.value(buildResult);
}
/// Thrown when the build attempts to prompt the users but no prompt is
/// possible.
class NonInteractiveBuildException implements Exception {}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/environment/io_environment.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import '../asset/file_based.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../generate/build_directory.dart';
import '../generate/build_result.dart';
import '../generate/finalized_assets_view.dart';
import '../package_graph/package_graph.dart';
import 'build_environment.dart';
import 'create_merged_dir.dart';
final _logger = Logger('IOEnvironment');
/// A [BuildEnvironment] writing to disk and stdout.
class IOEnvironment implements BuildEnvironment {
@override
final RunnerAssetReader reader;
@override
final RunnerAssetWriter writer;
final bool _isInteractive;
final bool _outputSymlinksOnly;
final PackageGraph _packageGraph;
IOEnvironment(this._packageGraph, {bool assumeTty, bool outputSymlinksOnly})
: _isInteractive = assumeTty == true || _canPrompt(),
_outputSymlinksOnly = outputSymlinksOnly ?? false,
reader = FileBasedAssetReader(_packageGraph),
writer = FileBasedAssetWriter(_packageGraph) {
if (_outputSymlinksOnly && Platform.isWindows) {
_logger.warning('Symlinks to files are not yet working on Windows, you '
'may experience issues using this mode. Follow '
'https://github.com/dart-lang/sdk/issues/33966 for updates.');
}
}
@override
void onLog(LogRecord record) {
if (record.level >= Level.SEVERE) {
stderr.writeln(record);
} else {
stdout.writeln(record);
}
}
@override
Future<int> prompt(String message, List<String> choices) async {
if (!_isInteractive) throw NonInteractiveBuildException();
while (true) {
stdout.writeln('\n$message');
for (var i = 0, l = choices.length; i < l; i++) {
stdout.writeln('${i + 1} - ${choices[i]}');
}
final input = stdin.readLineSync();
final choice = int.tryParse(input) ?? -1;
if (choice > 0 && choice <= choices.length) return choice - 1;
stdout.writeln('Unrecognized option $input, '
'a number between 1 and ${choices.length} expected');
}
}
@override
Future<BuildResult> finalizeBuild(
BuildResult buildResult,
FinalizedAssetsView finalizedAssetsView,
AssetReader reader,
Set<BuildDirectory> buildDirs) async {
if (buildDirs.any(
(target) => target.outputLocation?.path?.isNotEmpty ?? false) &&
buildResult.status == BuildStatus.success) {
if (!await createMergedOutputDirectories(buildDirs, _packageGraph, this,
reader, finalizedAssetsView, _outputSymlinksOnly)) {
return _convertToFailure(buildResult,
failureType: FailureType.cantCreate);
}
}
return buildResult;
}
}
bool _canPrompt() =>
stdioType(stdin) == StdioType.terminal &&
// Assume running inside a test if the code is running as a `data:` URI
Platform.script.scheme != 'data';
BuildResult _convertToFailure(BuildResult previous,
{FailureType failureType}) =>
BuildResult(
BuildStatus.failure,
previous.outputs,
performance: previous.performance,
failureType: failureType,
);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/environment/overridable_environment.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../generate/build_directory.dart';
import '../generate/build_result.dart';
import '../generate/finalized_assets_view.dart';
import 'build_environment.dart';
/// A [BuildEnvironment] which can have individual features overridden.
class OverrideableEnvironment implements BuildEnvironment {
final BuildEnvironment _default;
final RunnerAssetReader _reader;
final RunnerAssetWriter _writer;
final void Function(LogRecord) _onLog;
final Future<BuildResult> Function(
BuildResult, FinalizedAssetsView, AssetReader, Set<BuildDirectory>)
_finalizeBuild;
OverrideableEnvironment(
this._default, {
RunnerAssetReader reader,
RunnerAssetWriter writer,
void Function(LogRecord) onLog,
Future<BuildResult> Function(
BuildResult, FinalizedAssetsView, AssetReader, Set<BuildDirectory>)
finalizeBuild,
}) : _reader = reader,
_writer = writer,
_onLog = onLog,
_finalizeBuild = finalizeBuild;
@override
RunnerAssetReader get reader => _reader ?? _default.reader;
@override
RunnerAssetWriter get writer => _writer ?? _default.writer;
@override
Future<BuildResult> finalizeBuild(
BuildResult buildResult,
FinalizedAssetsView finalizedAssetsView,
AssetReader reader,
Set<BuildDirectory> buildDirs) =>
(_finalizeBuild ?? _default.finalizeBuild)(
buildResult, finalizedAssetsView, reader, buildDirs);
@override
void onLog(LogRecord record) {
if (_onLog != null) {
_onLog(record);
} else {
_default.onLog(record);
}
}
@override
Future<int> prompt(String message, List<String> choices) =>
_default.prompt(message, choices);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/environment/create_merged_dir.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:pool/pool.dart';
import '../asset/reader.dart';
import '../environment/build_environment.dart';
import '../generate/build_directory.dart';
import '../generate/finalized_assets_view.dart';
import '../logging/logging.dart';
import '../package_graph/package_graph.dart';
/// Pool for async file operations, we don't want to use too many file handles.
final _descriptorPool = Pool(32);
final _logger = Logger('CreateOutputDir');
const _manifestName = '.build.manifest';
const _manifestSeparator = '\n';
/// Creates merged output directories for each [OutputLocation].
///
/// Returns whether it succeeded or not.
Future<bool> createMergedOutputDirectories(
Set<BuildDirectory> buildDirs,
PackageGraph packageGraph,
BuildEnvironment environment,
AssetReader reader,
FinalizedAssetsView finalizedAssetsView,
bool outputSymlinksOnly) async {
if (outputSymlinksOnly && reader is! PathProvidingAssetReader) {
_logger.severe(
'The current environment does not support symlinks, but symlinks were '
'requested.');
return false;
}
var conflictingOutputs = _conflicts(buildDirs);
if (conflictingOutputs.isNotEmpty) {
_logger.severe('Unable to create merged directory. '
'Conflicting outputs for $conflictingOutputs');
return false;
}
for (var target in buildDirs) {
var output = target.outputLocation?.path;
if (output != null) {
if (!await _createMergedOutputDir(
output,
target.directory,
packageGraph,
environment,
reader,
finalizedAssetsView,
// TODO(grouma) - retrieve symlink information from target only.
outputSymlinksOnly || target.outputLocation.useSymlinks,
target.outputLocation.hoist)) {
_logger.severe('Unable to create merged directory for $output.');
return false;
}
}
}
return true;
}
Set<String> _conflicts(Set<BuildDirectory> buildDirs) {
final seen = <String>{};
final conflicts = <String>{};
var outputLocations =
buildDirs.map((d) => d.outputLocation?.path).where((p) => p != null);
for (var location in outputLocations) {
if (!seen.add(location)) conflicts.add(location);
}
return conflicts;
}
Future<bool> _createMergedOutputDir(
String outputPath,
String root,
PackageGraph packageGraph,
BuildEnvironment environment,
AssetReader reader,
FinalizedAssetsView finalizedOutputsView,
bool symlinkOnly,
bool hoist) async {
try {
if (root == null) return false;
var outputDir = Directory(outputPath);
var outputDirExists = await outputDir.exists();
if (outputDirExists) {
if (!await _cleanUpOutputDir(outputDir, environment)) return false;
}
var builtAssets = finalizedOutputsView.allAssets(rootDir: root).toList();
if (root != '' &&
!builtAssets
.where((id) => id.package == packageGraph.root.name)
.any((id) => p.isWithin(root, id.path))) {
_logger.severe('No assets exist in $root, skipping output');
return false;
}
var outputAssets = <AssetId>[];
await logTimedAsync(_logger, 'Creating merged output dir `$outputPath`',
() async {
if (!outputDirExists) {
await outputDir.create(recursive: true);
}
outputAssets.addAll(await Future.wait([
for (var id in builtAssets)
_writeAsset(
id, outputDir, root, packageGraph, reader, symlinkOnly, hoist),
_writeCustomPackagesFile(packageGraph, outputDir),
if (await reader.canRead(_packageConfigId(packageGraph.root.name)))
_writeModifiedPackageConfig(
packageGraph.root.name, reader, outputDir),
]));
if (!hoist) {
for (var dir in _findRootDirs(builtAssets, outputPath)) {
var link = Link(p.join(outputDir.path, dir, 'packages'));
if (!link.existsSync()) {
link.createSync(p.join('..', 'packages'), recursive: true);
}
}
}
});
await logTimedAsync(_logger, 'Writing asset manifest', () async {
var paths = outputAssets.map((id) => id.path).toList()..sort();
var content = paths.join(_manifestSeparator);
await _writeAsString(
outputDir, AssetId(packageGraph.root.name, _manifestName), content);
});
return true;
} on FileSystemException catch (e) {
if (e.osError?.errorCode != 1314) rethrow;
var devModeLink =
'https://docs.microsoft.com/en-us/windows/uwp/get-started/'
'enable-your-device-for-development';
_logger.severe('Unable to create symlink ${e.path}. Note that to create '
'symlinks on windows you need to either run in a console with admin '
'privileges or enable developer mode (see $devModeLink).');
return false;
}
}
/// Creates a custom `.packages` file in [outputDir] containing all the
/// packages in [packageGraph].
///
/// All package root uris are of the form `packages/<package>/`.
Future<AssetId> _writeCustomPackagesFile(
PackageGraph packageGraph, Directory outputDir) async {
var packagesFileContent =
packageGraph.allPackages.keys.map((p) => '$p:packages/$p/').join('\r\n');
var packagesAsset = AssetId(packageGraph.root.name, '.packages');
await _writeAsString(outputDir, packagesAsset, packagesFileContent);
return packagesAsset;
}
AssetId _packageConfigId(String rootPackage) =>
AssetId(rootPackage, '.dart_tool/package_config.json');
/// Creates a modified `.dart_tool/package_config.json` file in [outputDir]
/// based on the current one but with modified root and package uris.
///
/// All `rootUri`s are of the form `packages/<package>` and the `packageUri`
/// is always the empty string. This is because only the lib directory is
/// exposed when using a `packages` directory layout so the root uri and
/// package uri are equivalent.
///
/// All other fields are left as is.
Future<AssetId> _writeModifiedPackageConfig(
String rootPackage, AssetReader reader, Directory outputDir) async {
var packageConfigAsset = _packageConfigId(rootPackage);
var packageConfig = jsonDecode(await reader.readAsString(packageConfigAsset))
as Map<String, dynamic>;
var version = packageConfig['configVersion'] as int;
if (version != 2) {
throw UnsupportedError(
'Unsupported package_config.json version, got $version but only '
'version 2 is supported.');
}
var packages =
(packageConfig['packages'] as List).cast<Map<String, dynamic>>();
for (var package in packages) {
package['rootUri'] = '../packages/${package['name']}';
package['packageUri'] = '';
}
await _writeAsString(
outputDir, packageConfigAsset, jsonEncode(packageConfig));
return packageConfigAsset;
}
Set<String> _findRootDirs(Iterable<AssetId> allAssets, String outputPath) {
var rootDirs = <String>{};
for (var id in allAssets) {
var parts = p.url.split(id.path);
if (parts.length == 1) continue;
var dir = parts.first;
if (dir == outputPath || dir == 'lib') continue;
rootDirs.add(parts.first);
}
return rootDirs;
}
Future<AssetId> _writeAsset(
AssetId id,
Directory outputDir,
String root,
PackageGraph packageGraph,
AssetReader reader,
bool symlinkOnly,
bool hoist) {
return _descriptorPool.withResource(() async {
String assetPath;
if (id.path.startsWith('lib/')) {
assetPath =
p.url.join('packages', id.package, id.path.substring('lib/'.length));
} else {
assetPath = id.path;
assert(id.package == packageGraph.root.name);
if (hoist && p.isWithin(root, id.path)) {
assetPath = p.relative(id.path, from: root);
}
}
var outputId = AssetId(packageGraph.root.name, assetPath);
try {
if (symlinkOnly) {
await Link(_filePathFor(outputDir, outputId)).create(
// We assert at the top of `createMergedOutputDirectories` that the
// reader implements this type when requesting symlinks.
(reader as PathProvidingAssetReader).pathTo(id),
recursive: true);
} else {
await _writeAsBytes(outputDir, outputId, await reader.readAsBytes(id));
}
} on AssetNotFoundException catch (e, __) {
if (p.basename(id.path).startsWith('.')) {
_logger.fine('Skipping missing hidden file ${id.path}');
} else {
_logger.severe(
'Missing asset ${e.assetId}, it may have been deleted during the '
'build. Please try rebuilding and if you continue to see the '
'error then file a bug at '
'https://github.com/dart-lang/build/issues/new.');
rethrow;
}
}
return outputId;
});
}
Future<void> _writeAsBytes(Directory outputDir, AssetId id, List<int> bytes) =>
_fileFor(outputDir, id).then((file) => file.writeAsBytes(bytes));
Future<void> _writeAsString(Directory outputDir, AssetId id, String contents) =>
_fileFor(outputDir, id).then((file) => file.writeAsString(contents));
Future<File> _fileFor(Directory outputDir, AssetId id) {
return File(_filePathFor(outputDir, id)).create(recursive: true);
}
String _filePathFor(Directory outputDir, AssetId id) {
String relativePath;
if (id.path.startsWith('lib')) {
relativePath =
p.join('packages', id.package, p.joinAll(p.url.split(id.path).skip(1)));
} else {
relativePath = id.path;
}
return p.join(outputDir.path, relativePath);
}
/// Checks for a manifest file in [outputDir] and deletes all referenced files.
///
/// Prompts the user with a few options if no manifest file is found.
///
/// Returns whether or not the directory was successfully cleaned up.
Future<bool> _cleanUpOutputDir(
Directory outputDir, BuildEnvironment environment) async {
var outputPath = outputDir.path;
var manifestFile = File(p.join(outputPath, _manifestName));
if (!manifestFile.existsSync()) {
if (outputDir.listSync(recursive: false).isNotEmpty) {
var choices = [
'Leave the directory unchanged and skip writing the build output',
'Delete the directory and all contents',
'Leave the directory in place and write over any existing files',
];
int choice;
try {
choice = await environment.prompt(
'Found existing directory `$outputPath` but no manifest file.\n'
'Please choose one of the following options:',
choices);
} on NonInteractiveBuildException catch (_) {
_logger.severe('Unable to create merged directory at $outputPath.\n'
'Choose a different directory or delete the contents of that '
'directory.');
return false;
}
switch (choice) {
case 0:
_logger.severe('Skipped creation of the merged output directory.');
return false;
case 1:
try {
outputDir.deleteSync(recursive: true);
} catch (e) {
_logger.severe(
'Failed to delete output dir at `$outputPath` with error:\n\n'
'$e');
return false;
}
// Actually recreate the directory, but as an empty one.
outputDir.createSync();
break;
case 2:
// Just do nothing here, we overwrite files by default.
break;
}
}
} else {
var previousOutputs = logTimedSync(
_logger,
'Reading manifest at ${manifestFile.path}',
() => manifestFile.readAsStringSync().split(_manifestSeparator));
logTimedSync(_logger, 'Deleting previous outputs in `$outputPath`', () {
for (var path in previousOutputs) {
var file = File(p.join(outputPath, path));
if (file.existsSync()) file.deleteSync();
}
_cleanEmptyDirectories(outputPath, previousOutputs);
});
}
return true;
}
/// Deletes all the directories which used to contain any path in
/// [removedFilePaths] if that directory is now empty.
void _cleanEmptyDirectories(
String outputPath, Iterable<String> removedFilePaths) {
for (var directory in removedFilePaths
.map((path) => p.join(outputPath, p.dirname(path)))
.toSet()) {
_deleteUp(directory, outputPath);
}
}
/// Deletes the directory at [from] and and any parent directories which are
/// subdirectories of [to] if they are empty.
void _deleteUp(String from, String to) {
var directoryPath = from;
while (p.isWithin(to, directoryPath)) {
var directory = Directory(directoryPath);
if (!directory.existsSync() || directory.listSync().isNotEmpty) return;
directory.deleteSync();
directoryPath = p.dirname(directoryPath);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/changes/build_script_updates.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:mirrors';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import '../asset/reader.dart';
import '../asset_graph/graph.dart';
import '../package_graph/package_graph.dart';
/// Functionality for detecting if the build script itself or any of its
/// transitive imports have changed.
abstract class BuildScriptUpdates {
/// Checks if the current running program has been updated, based on
/// [updatedIds].
bool hasBeenUpdated(Set<AssetId> updatedIds);
/// Creates a [BuildScriptUpdates] object, using [reader] to ensure that
/// the [assetGraph] is tracking digests for all transitive sources.
///
/// If [disabled] is `true` then all checks are skipped and
/// [hasBeenUpdated] will always return `false`.
static Future<BuildScriptUpdates> create(RunnerAssetReader reader,
PackageGraph packageGraph, AssetGraph assetGraph,
{bool disabled = false}) async {
disabled ??= false;
if (disabled) return _NoopBuildScriptUpdates();
return _MirrorBuildScriptUpdates.create(reader, packageGraph, assetGraph);
}
}
/// Uses mirrors to find all transitive imports of the current script.
class _MirrorBuildScriptUpdates implements BuildScriptUpdates {
final Set<AssetId> _allSources;
final bool _supportsIncrementalRebuilds;
_MirrorBuildScriptUpdates._(
this._supportsIncrementalRebuilds, this._allSources);
static Future<BuildScriptUpdates> create(RunnerAssetReader reader,
PackageGraph packageGraph, AssetGraph graph) async {
var supportsIncrementalRebuilds = true;
var rootPackage = packageGraph.root.name;
Set<AssetId> allSources;
var logger = Logger('BuildScriptUpdates');
try {
allSources = _urisForThisScript
.map((id) => _idForUri(id, rootPackage))
.where((id) => id != null)
.toSet();
var missing = allSources.firstWhere((id) => !graph.contains(id),
orElse: () => null);
if (missing != null) {
supportsIncrementalRebuilds = false;
logger.warning('$missing was not found in the asset graph, '
'incremental builds will not work.\n This probably means you '
'don\'t have your dependencies specified fully in your '
'pubspec.yaml.');
} else {
// Make sure we are tracking changes for all ids in [allSources].
for (var id in allSources) {
graph.get(id).lastKnownDigest ??= await reader.digest(id);
}
}
} on ArgumentError catch (_) {
supportsIncrementalRebuilds = false;
allSources = <AssetId>{};
}
return _MirrorBuildScriptUpdates._(supportsIncrementalRebuilds, allSources);
}
static Iterable<Uri> get _urisForThisScript =>
currentMirrorSystem().libraries.keys;
/// Checks if the current running program has been updated, based on
/// [updatedIds].
@override
bool hasBeenUpdated(Set<AssetId> updatedIds) {
if (!_supportsIncrementalRebuilds) return true;
return updatedIds.intersection(_allSources).isNotEmpty;
}
/// Attempts to return an [AssetId] for [uri].
///
/// Returns `null` if the uri should be ignored, or throws an [ArgumentError]
/// if the [uri] is not recognized.
static AssetId _idForUri(Uri uri, String _rootPackage) {
switch (uri.scheme) {
case 'dart':
// TODO: check for sdk updates!
break;
case 'package':
var parts = uri.pathSegments;
return AssetId(parts[0],
p.url.joinAll(['lib', ...parts.getRange(1, parts.length)]));
case 'file':
var relativePath = p.relative(uri.toFilePath(), from: p.current);
return AssetId(_rootPackage, relativePath);
case 'data':
// Test runner uses a `data` scheme, don't invalidate for those.
if (uri.path.contains('package:test')) break;
continue unsupported;
case 'http':
continue unsupported;
unsupported:
default:
throw ArgumentError('Unsupported uri scheme `${uri.scheme}` found for '
'library in build script.\n'
'This probably means you are running in an unsupported '
'context, such as in an isolate or via `pub run`.\n'
'Full uri was: $uri.');
}
return null;
}
}
/// Always returns false for [hasBeenUpdated], used when we want to skip
/// the build script checks.
class _NoopBuildScriptUpdates implements BuildScriptUpdates {
@override
bool hasBeenUpdated(void _) => false;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/build_runner.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:watcher/watcher.dart';
import '../environment/build_environment.dart';
import '../package_graph/apply_builders.dart';
import 'build_directory.dart';
import 'build_impl.dart';
import 'build_result.dart';
import 'options.dart';
class BuildRunner {
final BuildImpl _build;
BuildRunner._(this._build);
Future<void> beforeExit() => _build.beforeExit();
Future<BuildResult> run(Map<AssetId, ChangeType> updates,
{Set<BuildDirectory> buildDirs, Set<BuildFilter> buildFilters}) =>
_build.run(updates, buildDirs: buildDirs, buildFilters: buildFilters);
static Future<BuildRunner> create(
BuildOptions options,
BuildEnvironment environment,
List<BuilderApplication> builders,
Map<String, Map<String, dynamic>> builderConfigOverrides,
{bool isReleaseBuild = false}) async {
return BuildRunner._(await BuildImpl.create(
options, environment, builders, builderConfigOverrides,
isReleaseBuild: isReleaseBuild));
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/build_impl.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:pedantic/pedantic.dart';
import 'package:pool/pool.dart';
import 'package:watcher/watcher.dart';
import '../asset/cache.dart';
import '../asset/finalized_reader.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../asset_graph/optional_output_tracker.dart';
import '../changes/build_script_updates.dart';
import '../environment/build_environment.dart';
import '../logging/build_for_input_logger.dart';
import '../logging/failure_reporter.dart';
import '../logging/human_readable_duration.dart';
import '../logging/logging.dart';
import '../package_graph/apply_builders.dart';
import '../package_graph/package_graph.dart';
import '../performance_tracking/performance_tracking_resolvers.dart';
import '../util/async.dart';
import '../util/build_dirs.dart';
import '../util/constants.dart';
import 'build_definition.dart';
import 'build_directory.dart';
import 'build_result.dart';
import 'finalized_assets_view.dart';
import 'heartbeat.dart';
import 'options.dart';
import 'performance_tracker.dart';
import 'phase.dart';
final _logger = Logger('Build');
Set<String> _buildPaths(Set<BuildDirectory> buildDirs) =>
// The empty string means build everything.
buildDirs.any((b) => b.directory == '')
? <String>{}
: buildDirs.map((b) => b.directory).toSet();
class BuildImpl {
final FinalizedReader finalizedReader;
final AssetGraph assetGraph;
final BuildScriptUpdates buildScriptUpdates;
final List<BuildPhase> _buildPhases;
final PackageGraph _packageGraph;
final AssetReader _reader;
final Resolvers _resolvers;
final ResourceManager _resourceManager;
final RunnerAssetWriter _writer;
final bool _trackPerformance;
final BuildEnvironment _environment;
final String _logPerformanceDir;
Future<void> beforeExit() => _resourceManager.beforeExit();
BuildImpl._(BuildDefinition buildDefinition, BuildOptions options,
this._buildPhases, this.finalizedReader)
: buildScriptUpdates = buildDefinition.buildScriptUpdates,
_packageGraph = buildDefinition.packageGraph,
_reader = options.enableLowResourcesMode
? buildDefinition.reader
: CachingAssetReader(buildDefinition.reader),
_resolvers = options.resolvers,
_writer = buildDefinition.writer,
assetGraph = buildDefinition.assetGraph,
_resourceManager = buildDefinition.resourceManager,
_environment = buildDefinition.environment,
_trackPerformance = options.trackPerformance,
_logPerformanceDir = options.logPerformanceDir;
Future<BuildResult> run(Map<AssetId, ChangeType> updates,
{Set<BuildDirectory> buildDirs, Set<BuildFilter> buildFilters}) {
buildDirs ??= <BuildDirectory>{};
buildFilters ??= {};
finalizedReader.reset(_buildPaths(buildDirs), buildFilters);
return _SingleBuild(this, buildDirs, buildFilters).run(updates)
..whenComplete(_resolvers.reset);
}
static Future<BuildImpl> create(
BuildOptions options,
BuildEnvironment environment,
List<BuilderApplication> builders,
Map<String, Map<String, dynamic>> builderConfigOverrides,
{bool isReleaseBuild = false}) async {
// Don't allow any changes to the generated asset directory after this
// point.
lockGeneratedOutputDirectory();
var buildPhases = await createBuildPhases(
options.targetGraph, builders, builderConfigOverrides, isReleaseBuild);
if (buildPhases.isEmpty) {
_logger.severe('Nothing can be built, yet a build was requested.');
}
var buildDefinition = await BuildDefinition.prepareWorkspace(
environment, options, buildPhases);
var singleStepReader = SingleStepReader(
buildDefinition.reader,
buildDefinition.assetGraph,
buildPhases.length,
options.packageGraph.root.name,
_isReadableAfterBuildFactory(buildPhases));
var finalizedReader = FinalizedReader(
singleStepReader,
buildDefinition.assetGraph,
buildPhases,
options.packageGraph.root.name);
var build =
BuildImpl._(buildDefinition, options, buildPhases, finalizedReader);
return build;
}
static IsReadable _isReadableAfterBuildFactory(List<BuildPhase> buildPhases) {
return (AssetNode node, int phaseNum, AssetWriterSpy writtenAssets) {
if (node is GeneratedAssetNode) {
return Readability.fromPreviousPhase(node.wasOutput && !node.isFailure);
}
return Readability.fromPreviousPhase(
node.isReadable && node.isValidInput);
};
}
}
/// Performs a single build and manages state that only lives for a single
/// build.
class _SingleBuild {
final AssetGraph _assetGraph;
final Set<BuildFilter> _buildFilters;
final List<BuildPhase> _buildPhases;
final List<Pool> _buildPhasePool;
final BuildEnvironment _environment;
final _lazyPhases = <String, Future<Iterable<AssetId>>>{};
final _lazyGlobs = <AssetId, Future<void>>{};
final PackageGraph _packageGraph;
final BuildPerformanceTracker _performanceTracker;
final AssetReader _reader;
final Resolvers _resolvers;
final ResourceManager _resourceManager;
final RunnerAssetWriter _writer;
final Set<BuildDirectory> _buildDirs;
final String _logPerformanceDir;
final _failureReporter = FailureReporter();
int actionsCompletedCount = 0;
int actionsStartedCount = 0;
final pendingActions = SplayTreeMap<int, Set<String>>();
/// Can't be final since it needs access to [pendingActions].
HungActionsHeartbeat hungActionsHeartbeat;
_SingleBuild(BuildImpl buildImpl, Set<BuildDirectory> buildDirs,
Set<BuildFilter> buildFilters)
: _assetGraph = buildImpl.assetGraph,
_buildFilters = buildFilters,
_buildPhases = buildImpl._buildPhases,
_buildPhasePool = List(buildImpl._buildPhases.length),
_environment = buildImpl._environment,
_packageGraph = buildImpl._packageGraph,
_performanceTracker = buildImpl._trackPerformance
? BuildPerformanceTracker()
: BuildPerformanceTracker.noOp(),
_reader = buildImpl._reader,
_resolvers = buildImpl._resolvers,
_resourceManager = buildImpl._resourceManager,
_writer = buildImpl._writer,
_buildDirs = buildDirs,
_logPerformanceDir = buildImpl._logPerformanceDir {
hungActionsHeartbeat = HungActionsHeartbeat(() {
final message = StringBuffer();
const actionsToLogMax = 5;
var descriptions = pendingActions.values.fold(
<String>[],
(combined, actions) =>
combined..addAll(actions)).take(actionsToLogMax);
for (final description in descriptions) {
message.writeln(' - $description');
}
var additionalActionsCount =
actionsStartedCount - actionsCompletedCount - actionsToLogMax;
if (additionalActionsCount > 0) {
message.writeln(' .. and $additionalActionsCount more');
}
return '$message';
});
}
Future<BuildResult> run(Map<AssetId, ChangeType> updates) async {
var watch = Stopwatch()..start();
var result = await _safeBuild(updates);
var optionalOutputTracker = OptionalOutputTracker(
_assetGraph, _buildPaths(_buildDirs), _buildFilters, _buildPhases);
if (result.status == BuildStatus.success) {
final failures = _assetGraph.failedOutputs
.where((n) => optionalOutputTracker.isRequired(n.id));
if (failures.isNotEmpty) {
await _failureReporter.reportErrors(failures);
result = BuildResult(BuildStatus.failure, result.outputs,
performance: result.performance);
}
}
await _resourceManager.disposeAll();
result = await _environment.finalizeBuild(
result,
FinalizedAssetsView(_assetGraph, optionalOutputTracker),
_reader,
_buildDirs);
if (result.status == BuildStatus.success) {
_logger.info('Succeeded after ${humanReadable(watch.elapsed)} with '
'${result.outputs.length} outputs '
'($actionsCompletedCount actions)\n');
} else {
_logger.severe('Failed after ${humanReadable(watch.elapsed)}');
}
return result;
}
Future<void> _updateAssetGraph(Map<AssetId, ChangeType> updates) async {
await logTimedAsync(_logger, 'Updating asset graph', () async {
var invalidated = await _assetGraph.updateAndInvalidate(
_buildPhases, updates, _packageGraph.root.name, _delete, _reader);
if (_reader is CachingAssetReader) {
(_reader as CachingAssetReader).invalidate(invalidated);
}
});
}
/// Runs a build inside a zone with an error handler and stack chain
/// capturing.
Future<BuildResult> _safeBuild(Map<AssetId, ChangeType> updates) {
var done = Completer<BuildResult>();
var heartbeat = HeartbeatLogger(
transformLog: (original) => '$original, ${_buildProgress()}',
waitDuration: Duration(seconds: 1))
..start();
hungActionsHeartbeat.start();
done.future.whenComplete(() {
heartbeat.stop();
hungActionsHeartbeat.stop();
});
runZoned(() async {
if (updates.isNotEmpty) {
await _updateAssetGraph(updates);
}
// Run a fresh build.
var result = await logTimedAsync(_logger, 'Running build', _runPhases);
// Write out the dependency graph file.
await logTimedAsync(_logger, 'Caching finalized dependency graph',
() async {
await _writer.writeAsBytes(
AssetId(_packageGraph.root.name, assetGraphPath),
_assetGraph.serialize());
});
// Log performance information if requested
if (_logPerformanceDir != null) {
assert(result.performance != null);
var now = DateTime.now();
var logPath = p.join(
_logPerformanceDir,
'${now.year}-${_twoDigits(now.month)}-${_twoDigits(now.day)}'
'_${_twoDigits(now.hour)}-${_twoDigits(now.minute)}-'
'${_twoDigits(now.second)}');
await logTimedAsync(_logger, 'Writing performance log to $logPath', () {
var performanceLogId = AssetId(_packageGraph.root.name, logPath);
var serialized = jsonEncode(result.performance);
return _writer.writeAsString(performanceLogId, serialized);
});
}
if (!done.isCompleted) done.complete(result);
}, onError: (Object e, StackTrace st) {
if (!done.isCompleted) {
_logger.severe('Unhandled build failure!', e, st);
done.complete(BuildResult(BuildStatus.failure, []));
}
});
return done.future;
}
/// Returns a message describing the progress of the current build.
String _buildProgress() =>
'$actionsCompletedCount/$actionsStartedCount actions completed.';
/// Runs the actions in [_buildPhases] and returns a [Future<BuildResult>]
/// which completes once all [BuildPhase]s are done.
Future<BuildResult> _runPhases() {
return _performanceTracker.track(() async {
final outputs = <AssetId>[];
for (var phaseNum = 0; phaseNum < _buildPhases.length; phaseNum++) {
var phase = _buildPhases[phaseNum];
if (phase.isOptional) continue;
outputs
.addAll(await _performanceTracker.trackBuildPhase(phase, () async {
if (phase is InBuildPhase) {
var primaryInputs =
await _matchingPrimaryInputs(phase.package, phaseNum);
return _runBuilder(phaseNum, phase, primaryInputs);
} else if (phase is PostBuildPhase) {
return _runPostProcessPhase(phaseNum, phase);
} else {
throw StateError('Unrecognized BuildPhase type $phase');
}
}));
}
await Future.forEach(
_lazyPhases.values,
(Future<Iterable<AssetId>> lazyOuts) async =>
outputs.addAll(await lazyOuts));
// Assume success, `_assetGraph.failedOutputs` will be checked later.
return BuildResult(BuildStatus.success, outputs,
performance: _performanceTracker);
});
}
/// Gets a list of all inputs matching the [phaseNumber], as well as
/// its [Builder]s primary inputs.
///
/// Lazily builds any optional build actions that might potentially produce
/// a primary input to this phase.
Future<Set<AssetId>> _matchingPrimaryInputs(
String package, int phaseNumber) async {
var ids = <AssetId>{};
var phase = _buildPhases[phaseNumber];
await Future.wait(
_assetGraph.outputsForPhase(package, phaseNumber).map((node) async {
if (!shouldBuildForDirs(
node.id, _buildPaths(_buildDirs), _buildFilters, phase)) {
return;
}
var input = _assetGraph.get(node.primaryInput);
if (input is GeneratedAssetNode) {
if (input.state != NodeState.upToDate) {
await _runLazyPhaseForInput(input.phaseNumber, input.primaryInput);
}
if (!input.wasOutput) return;
if (input.isFailure) return;
}
ids.add(input.id);
}));
return ids;
}
/// Runs a normal builder with [primaryInputs] as inputs and returns only the
/// outputs that were newly created.
///
/// Does not return outputs that didn't need to be re-ran or were declared
/// but not output.
Future<Iterable<AssetId>> _runBuilder(int phaseNumber, InBuildPhase action,
Iterable<AssetId> primaryInputs) async {
var outputLists = await Future.wait(
primaryInputs.map((input) => _runForInput(phaseNumber, action, input)));
return outputLists.fold<List<AssetId>>(
<AssetId>[], (combined, next) => combined..addAll(next));
}
/// Lazily runs [phaseNumber] with [input]..
Future<Iterable<AssetId>> _runLazyPhaseForInput(
int phaseNumber, AssetId input) {
return _lazyPhases.putIfAbsent('$phaseNumber|$input', () async {
// First check if `input` is generated, and whether or not it was
// actually output. If it wasn't then we just return an empty list here.
var inputNode = _assetGraph.get(input);
if (inputNode is GeneratedAssetNode) {
// Make sure the `inputNode` is up to date, and rebuild it if not.
if (inputNode.state != NodeState.upToDate) {
await _runLazyPhaseForInput(
inputNode.phaseNumber, inputNode.primaryInput);
}
if (!inputNode.wasOutput || inputNode.isFailure) return <AssetId>[];
}
// We can never lazily build `PostProcessBuildAction`s.
var action = _buildPhases[phaseNumber] as InBuildPhase;
return _runForInput(phaseNumber, action, input);
});
}
/// Checks whether [node] can be read by this step - attempting to build the
/// asset if necessary.
FutureOr<Readability> _isReadableNode(
AssetNode node, int phaseNum, AssetWriterSpy writtenAssets) {
if (node is GeneratedAssetNode) {
if (node.phaseNumber > phaseNum) {
return Readability.notReadable;
} else if (node.phaseNumber == phaseNum) {
// allow a build step to read its outputs (contained in writtenAssets)
final isInBuild = _buildPhases[phaseNum] is InBuildPhase &&
writtenAssets.assetsWritten.contains(node.id);
return isInBuild ? Readability.ownOutput : Readability.notReadable;
}
return doAfter(
// ignore: void_checks
_ensureAssetIsBuilt(node),
(_) =>
Readability.fromPreviousPhase(node.wasOutput && !node.isFailure));
}
return Readability.fromPreviousPhase(node.isReadable && node.isValidInput);
}
FutureOr<void> _ensureAssetIsBuilt(AssetNode node) {
if (node is GeneratedAssetNode && node.state != NodeState.upToDate) {
return _runLazyPhaseForInput(node.phaseNumber, node.primaryInput);
}
return null;
}
Future<Iterable<AssetId>> _runForInput(
int phaseNumber, InBuildPhase phase, AssetId input) {
var pool = _buildPhasePool[phaseNumber] ??= Pool(buildPhasePoolSize);
return pool.withResource(() {
final builder = phase.builder;
var tracker =
_performanceTracker.addBuilderAction(input, phase.builderLabel);
return tracker.track(() async {
var builderOutputs = expectedOutputs(builder, input);
// Add `builderOutputs` to the primary outputs of the input.
var inputNode = _assetGraph.get(input);
assert(inputNode != null,
'Inputs should be known in the static graph. Missing $input');
assert(
inputNode.primaryOutputs.containsAll(builderOutputs),
'input $input with builder $builder missing primary outputs: \n'
'Got ${inputNode.primaryOutputs.join(', ')} '
'which was missing:\n' +
builderOutputs
.where((id) => !inputNode.primaryOutputs.contains(id))
.join(', '));
var wrappedWriter = AssetWriterSpy(_writer);
var wrappedReader = SingleStepReader(_reader, _assetGraph, phaseNumber,
input.package, _isReadableNode, _getUpdatedGlobNode, wrappedWriter);
if (!await tracker.trackStage(
'Setup', () => _buildShouldRun(builderOutputs, wrappedReader))) {
return <AssetId>[];
}
await _cleanUpStaleOutputs(builderOutputs);
await FailureReporter.clean(phaseNumber, input);
// We may have read some inputs in the call to `_buildShouldRun`, we want
// to remove those.
wrappedReader.assetsRead.clear();
var actionDescription =
_actionLoggerName(phase, input, _packageGraph.root.name);
var logger = BuildForInputLogger(Logger(actionDescription));
actionsStartedCount++;
pendingActions
.putIfAbsent(phaseNumber, () => <String>{})
.add(actionDescription);
var unusedAssets = <AssetId>{};
await tracker.trackStage(
'Build',
() => runBuilder(
builder,
[input],
wrappedReader,
wrappedWriter,
PerformanceTrackingResolvers(_resolvers, tracker),
logger: logger,
resourceManager: _resourceManager,
stageTracker: tracker,
reportUnusedAssetsForInput: (_, assets) =>
unusedAssets.addAll(assets),
).catchError((void _) {
// Errors tracked through the logger
}));
actionsCompletedCount++;
hungActionsHeartbeat.ping();
pendingActions[phaseNumber].remove(actionDescription);
// Reset the state for all the `builderOutputs` nodes based on what was
// read and written.
await tracker.trackStage(
'Finalize',
() => _setOutputsState(
builderOutputs,
wrappedReader,
wrappedWriter,
actionDescription,
logger.errorsSeen,
unusedAssets: unusedAssets,
));
return wrappedWriter.assetsWritten;
});
});
}
Future<Iterable<AssetId>> _runPostProcessPhase(
int phaseNum, PostBuildPhase phase) async {
var actionNum = 0;
var outputLists = await Future.wait(phase.builderActions
.map((action) => _runPostProcessAction(phaseNum, actionNum++, action)));
return outputLists.fold<List<AssetId>>(
<AssetId>[], (combined, next) => combined..addAll(next));
}
Future<Iterable<AssetId>> _runPostProcessAction(
int phaseNum, int actionNum, PostBuildAction action) async {
var anchorNodes = _assetGraph.packageNodes(action.package).where((node) {
if (node is PostProcessAnchorNode && node.actionNumber == actionNum) {
var inputNode = _assetGraph.get(node.primaryInput);
if (inputNode is SourceAssetNode) {
return true;
} else if (inputNode is GeneratedAssetNode) {
return inputNode.wasOutput &&
!inputNode.isFailure &&
inputNode.state == NodeState.upToDate;
}
}
return false;
}).cast<PostProcessAnchorNode>();
var outputLists = await Future.wait(anchorNodes.map((anchorNode) =>
_runPostProcessBuilderForAnchor(
phaseNum, actionNum, action.builder, anchorNode)));
return outputLists.fold<List<AssetId>>(
<AssetId>[], (combined, next) => combined..addAll(next));
}
Future<Iterable<AssetId>> _runPostProcessBuilderForAnchor(
int phaseNum,
int actionNum,
PostProcessBuilder builder,
PostProcessAnchorNode anchorNode) async {
var input = anchorNode.primaryInput;
var inputNode = _assetGraph.get(input);
assert(inputNode != null,
'Inputs should be known in the static graph. Missing $input');
var wrappedWriter = AssetWriterSpy(_writer);
var wrappedReader = SingleStepReader(_reader, _assetGraph, phaseNum,
input.package, _isReadableNode, null, wrappedWriter);
if (!await _postProcessBuildShouldRun(anchorNode, wrappedReader)) {
return <AssetId>[];
}
// We may have read some inputs in the call to `_buildShouldRun`, we want
// to remove those.
wrappedReader.assetsRead.clear();
// Clean out the impacts of the previous run
await FailureReporter.clean(phaseNum, input);
await _cleanUpStaleOutputs(anchorNode.outputs);
anchorNode.outputs
..toList().forEach(_assetGraph.remove)
..clear();
inputNode.deletedBy.remove(anchorNode.id);
var actionDescription = '$builder on $input';
var logger = BuildForInputLogger(Logger(actionDescription));
actionsStartedCount++;
pendingActions
.putIfAbsent(phaseNum, () => <String>{})
.add(actionDescription);
await runPostProcessBuilder(
builder, input, wrappedReader, wrappedWriter, logger,
addAsset: (assetId) {
if (_assetGraph.contains(assetId)) {
throw InvalidOutputException(assetId, 'Asset already exists');
}
var node = GeneratedAssetNode(assetId,
primaryInput: input,
builderOptionsId: anchorNode.builderOptionsId,
isHidden: true,
phaseNumber: phaseNum,
wasOutput: true,
isFailure: false,
state: NodeState.upToDate);
_assetGraph.add(node);
anchorNode.outputs.add(assetId);
}, deleteAsset: (assetId) {
if (!_assetGraph.contains(assetId)) {
throw AssetNotFoundException(assetId);
}
if (assetId != input) {
throw InvalidOutputException(assetId, 'Can only delete primary input');
}
_assetGraph.get(assetId).deletedBy.add(anchorNode.id);
}).catchError((void _) {
// Errors tracked through the logger
});
actionsCompletedCount++;
hungActionsHeartbeat.ping();
pendingActions[phaseNum].remove(actionDescription);
var assetsWritten = wrappedWriter.assetsWritten.toSet();
// Reset the state for all the output nodes based on what was read and
// written.
inputNode.primaryOutputs.addAll(assetsWritten);
await _setOutputsState(assetsWritten, wrappedReader, wrappedWriter,
actionDescription, logger.errorsSeen);
return assetsWritten;
}
/// Checks and returns whether any [outputs] need to be updated.
Future<bool> _buildShouldRun(
Iterable<AssetId> outputs, AssetReader reader) async {
assert(
outputs.every(_assetGraph.contains),
'Outputs should be known statically. Missing '
'${outputs.where((o) => !_assetGraph.contains(o)).toList()}');
assert(outputs.isNotEmpty, 'Can\'t run a build with no outputs');
// We only check the first output, because all outputs share the same inputs
// and invalidation state.
var firstOutput = outputs.first;
var node = _assetGraph.get(firstOutput) as GeneratedAssetNode;
assert(
outputs.skip(1).every((output) =>
(_assetGraph.get(output) as GeneratedAssetNode)
.inputs
.difference(node.inputs)
.isEmpty),
'All outputs of a build action should share the same inputs.');
// No need to build an up to date output
if (node.state == NodeState.upToDate) return false;
// Early bail out condition, this is a forced update.
if (node.state == NodeState.definitelyNeedsUpdate) return true;
// This is a fresh build or the first time we've seen this output.
if (node.previousInputsDigest == null) return true;
var digest = await _computeCombinedDigest(
node.inputs, node.builderOptionsId, reader);
if (digest != node.previousInputsDigest) {
return true;
} else {
// Make sure to update the `state` field for all outputs.
for (var id in outputs) {
(_assetGraph.get(id) as NodeWithInputs).state = NodeState.upToDate;
}
return false;
}
}
/// Checks if a post process build should run based on [anchorNode].
Future<bool> _postProcessBuildShouldRun(
PostProcessAnchorNode anchorNode, AssetReader reader) async {
var inputsDigest = await _computeCombinedDigest(
[anchorNode.primaryInput], anchorNode.builderOptionsId, reader);
if (inputsDigest != anchorNode.previousInputsDigest) {
anchorNode.previousInputsDigest = inputsDigest;
return true;
}
return false;
}
/// Deletes any of [outputs] which previously were output.
///
/// This should be called after deciding that an asset really needs to be
/// regenerated based on its inputs hash changing. All assets in [outputs]
/// must correspond to a [GeneratedAssetNode].
Future<void> _cleanUpStaleOutputs(Iterable<AssetId> outputs) =>
Future.wait(outputs
.map(_assetGraph.get)
.cast<GeneratedAssetNode>()
.where((n) => n.wasOutput)
.map((n) => _delete(n.id)));
Future<GlobAssetNode> _getUpdatedGlobNode(
Glob glob, String package, int phaseNum) {
var globNodeId = GlobAssetNode.createId(package, glob, phaseNum);
var globNode = _assetGraph.get(globNodeId) as GlobAssetNode;
if (globNode == null) {
globNode = GlobAssetNode(
globNodeId, glob, phaseNum, NodeState.definitelyNeedsUpdate);
_assetGraph.add(globNode);
}
return toFuture(doAfter(
// ignore: void_checks
_updateGlobNodeIfNecessary(globNode),
(_) => globNode));
}
FutureOr<void> _updateGlobNodeIfNecessary(GlobAssetNode globNode) {
if (globNode.state == NodeState.upToDate) return null;
return _lazyGlobs.putIfAbsent(globNode.id, () async {
var potentialNodes = _assetGraph
.packageNodes(globNode.id.package)
.where((n) => n.isReadable && n.isValidInput)
.where((n) =>
n is! GeneratedAssetNode ||
(n as GeneratedAssetNode).phaseNumber < globNode.phaseNumber)
.where((n) => globNode.glob.matches(n.id.path))
.toList();
await Future.wait(potentialNodes
.whereType<GeneratedAssetNode>()
.map(_ensureAssetIsBuilt)
.map(toFuture));
var actualMatches = <AssetId>[];
for (var node in potentialNodes) {
node.outputs.add(globNode.id);
if (node is GeneratedAssetNode && (!node.wasOutput || node.isFailure)) {
continue;
}
actualMatches.add(node.id);
}
globNode
..results = actualMatches
..inputs = HashSet.of(potentialNodes.map((n) => n.id))
..state = NodeState.upToDate
..lastKnownDigest =
md5.convert(utf8.encode(globNode.results.join(' ')));
unawaited(_lazyGlobs.remove(globNode.id));
});
}
/// Computes a single [Digest] based on the combined [Digest]s of [ids] and
/// [builderOptionsId].
Future<Digest> _computeCombinedDigest(Iterable<AssetId> ids,
AssetId builderOptionsId, AssetReader reader) async {
var combinedBytes = Uint8List.fromList(List.filled(16, 0));
void _combine(Uint8List other) {
assert(other.length == 16);
assert(other is Uint8List);
for (var i = 0; i < 16; i++) {
combinedBytes[i] ^= other[i];
}
}
var builderOptionsNode = _assetGraph.get(builderOptionsId);
_combine(builderOptionsNode.lastKnownDigest.bytes as Uint8List);
// Limit the total number of digests we are computing at a time. Otherwise
// this can overload the event queue.
await Future.wait(ids.map((id) async {
var node = _assetGraph.get(id);
if (node is GlobAssetNode) {
await _updateGlobNodeIfNecessary(node);
} else if (!await reader.canRead(id)) {
// We want to add something here, a missing/unreadable input should be
// different from no input at all.
//
// This needs to be unique per input so we use the md5 hash of the id.
_combine(md5.convert(id.toString().codeUnits).bytes as Uint8List);
return;
} else {
node.lastKnownDigest ??= await reader.digest(id);
}
_combine(node.lastKnownDigest.bytes as Uint8List);
}));
return Digest(combinedBytes);
}
/// Sets the state for all [outputs] of a build step, by:
///
/// - Setting `needsUpdate` to `false` for each output
/// - Setting `wasOutput` based on `writer.assetsWritten`.
/// - Setting `isFailed` based on action success.
/// - Adding `outputs` as outputs to all `reader.assetsRead`.
/// - Setting the `lastKnownDigest` on each output based on the new contents.
/// - Setting the `previousInputsDigest` on each output based on the inputs.
/// - Storing the error message with the [_failureReporter].
Future<void> _setOutputsState(
Iterable<AssetId> outputs,
SingleStepReader reader,
AssetWriterSpy writer,
String actionDescription,
Iterable<ErrorReport> errors,
{Set<AssetId> unusedAssets}) async {
if (outputs.isEmpty) return;
var usedInputs = unusedAssets != null
? reader.assetsRead.difference(unusedAssets)
: reader.assetsRead;
final inputsDigest = await _computeCombinedDigest(
usedInputs,
(_assetGraph.get(outputs.first) as GeneratedAssetNode).builderOptionsId,
reader);
final isFailure = errors.isNotEmpty;
for (var output in outputs) {
var wasOutput = writer.assetsWritten.contains(output);
var digest = wasOutput ? await _reader.digest(output) : null;
var node = _assetGraph.get(output) as GeneratedAssetNode;
// **IMPORTANT**: All updates to `node` must be synchronous. With lazy
// builders we can run arbitrary code between updates otherwise, at which
// time a node might not be in a valid state.
_removeOldInputs(node, usedInputs);
_addNewInputs(node, usedInputs);
node
..state = NodeState.upToDate
..wasOutput = wasOutput
..isFailure = isFailure
..lastKnownDigest = digest
..previousInputsDigest = inputsDigest;
if (isFailure) {
await _failureReporter.markReported(actionDescription, node, errors);
var needsMarkAsFailure = Queue.of(node.primaryOutputs);
var allSkippedFailures = <GeneratedAssetNode>[];
while (needsMarkAsFailure.isNotEmpty) {
var output = needsMarkAsFailure.removeLast();
var outputNode = _assetGraph.get(output) as GeneratedAssetNode
..state = NodeState.upToDate
..wasOutput = false
..isFailure = true
..lastKnownDigest = null
..previousInputsDigest = null;
allSkippedFailures.add(outputNode);
needsMarkAsFailure.addAll(outputNode.primaryOutputs);
// Make sure output invalidation follows primary outputs for builds
// that won't run.
node.outputs.add(output);
outputNode.inputs.add(node.id);
}
await _failureReporter.markSkipped(allSkippedFailures);
}
}
}
/// Removes old inputs from [node] based on [updatedInputs], and cleans up all
/// the old edges.
void _removeOldInputs(GeneratedAssetNode node, Set<AssetId> updatedInputs) {
var removedInputs = node.inputs.difference(updatedInputs);
node.inputs.removeAll(removedInputs);
for (var input in removedInputs) {
var inputNode = _assetGraph.get(input);
assert(inputNode != null, 'Asset Graph is missing $input');
inputNode.outputs.remove(node.id);
}
}
/// Adds new inputs to [node] based on [updatedInputs], and adds the
/// appropriate edges.
void _addNewInputs(GeneratedAssetNode node, Set<AssetId> updatedInputs) {
var newInputs = updatedInputs.difference(node.inputs);
node.inputs.addAll(newInputs);
for (var input in newInputs) {
var inputNode = _assetGraph.get(input);
assert(inputNode != null, 'Asset Graph is missing $input');
inputNode.outputs.add(node.id);
}
}
Future _delete(AssetId id) => _writer.delete(id);
}
String _actionLoggerName(
InBuildPhase phase, AssetId primaryInput, String rootPackageName) {
var asset = primaryInput.package == rootPackageName
? primaryInput.path
: primaryInput.uri;
return '${phase.builderLabel} on $asset';
}
String _twoDigits(int n) => '$n'.padLeft(2, '0');
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/exceptions.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Indicates that a build config file has changed, and the build needs to be
/// re-ran.
///
/// An exit code of 75 should be set when handling this exception.
class BuildConfigChangedException implements Exception {
const BuildConfigChangedException();
}
/// Indicates that the build script itself has changed, and needs to be re-ran.
///
/// If the build is running from a snapshot, the snapshot should also be
/// deleted before exiting.
///
/// An exit code of 75 should be set when handling this exception.
class BuildScriptChangedException implements Exception {
const BuildScriptChangedException();
}
/// Indicates that the build cannot be attempted.
///
/// Before throwing this exception a user actionable message should be logged.
class CannotBuildException implements Exception {
const CannotBuildException();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/build_result.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:meta/meta.dart';
import 'performance_tracker.dart';
/// The result of an individual build, this may be an incremental build or
/// a full build.
class BuildResult {
/// The status of this build.
final BuildStatus status;
/// The type of failure.
final FailureType failureType;
/// All outputs created/updated during this build.
final List<AssetId> outputs;
/// The [BuildPerformance] broken out by build action, may be `null`.
@experimental
final BuildPerformance performance;
BuildResult(this.status, List<AssetId> outputs,
{this.performance, FailureType failureType})
: outputs = List.unmodifiable(outputs),
failureType = failureType == null && status == BuildStatus.failure
? FailureType.general
: failureType;
@override
String toString() {
if (status == BuildStatus.success) {
return '''
Build Succeeded!
''';
} else {
return '''
Build Failed :(
''';
}
}
}
/// The status of a build.
enum BuildStatus {
success,
failure,
}
/// The type of failure
class FailureType {
static final general = FailureType._(1);
static final cantCreate = FailureType._(73);
static final buildConfigChanged = FailureType._(75);
static final buildScriptChanged = FailureType._(75);
final int exitCode;
FailureType._(this.exitCode);
}
abstract class BuildState {
Future<BuildResult> get currentBuild;
Stream<BuildResult> get buildResults;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/phase.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:collection/collection.dart';
import 'package:meta/meta.dart';
import 'input_matcher.dart';
/// A "phase" in the build graph, which represents running a one or more
/// builders on a set of sources.
abstract class BuildPhase {
/// Whether to run lazily when an output is read.
///
/// An optional build action will only run if one of its outputs is read by
/// a later [Builder], or is used as a primary input to a later [Builder].
///
/// If no build actions read the output of an optional action, then it will
/// never run.
bool get isOptional;
/// Whether generated assets should be placed in the build cache.
///
/// When this is `false` the Builder may not run on any package other than
/// the root.
bool get hideOutput;
/// The identity of this action in terms of a build graph. If the identity of
/// any action changes the build will be invalidated.
///
/// This should take into account everything except for the builderOptions,
/// which are tracked separately via a `BuilderOptionsNode` which supports
/// more fine grained invalidation.
int get identity;
}
/// An "action" in the build graph which represents running a single builder
/// on a set of sources.
abstract class BuildAction {
/// Either a [Builder] or a [PostProcessBuilder].
dynamic get builder;
String get builderLabel;
BuilderOptions get builderOptions;
InputMatcher get generateFor;
String get package;
InputMatcher get targetSources;
}
/// A [BuildPhase] that uses a single [Builder] to generate files.
class InBuildPhase extends BuildPhase implements BuildAction {
@override
final Builder builder;
@override
final String builderLabel;
@override
final BuilderOptions builderOptions;
@override
final InputMatcher generateFor;
@override
final String package;
@override
final InputMatcher targetSources;
@override
final bool isOptional;
@override
final bool hideOutput;
InBuildPhase._(this.package, this.builder, this.builderOptions,
{@required this.targetSources,
@required this.generateFor,
@required this.builderLabel,
bool isOptional,
bool hideOutput})
: isOptional = isOptional ?? false,
hideOutput = hideOutput ?? false;
/// Creates an [BuildPhase] for a normal [Builder].
///
/// The build target is defined by [package] as well as [targetSources]. By
/// default all sources in the target are used as primary inputs to the
/// builder, but it can be further filtered with [generateFor].
///
/// [isOptional] specifies that a Builder may not be run unless some other
/// Builder in a later phase attempts to read one of the potential outputs.
///
/// [hideOutput] specifies that the generated asses should be placed in the
/// build cache rather than the source tree.
factory InBuildPhase(
Builder builder,
String package, {
String builderKey,
InputSet targetSources,
InputSet generateFor,
BuilderOptions builderOptions,
bool isOptional,
bool hideOutput,
}) {
var targetSourceMatcher = InputMatcher(targetSources ?? const InputSet());
var generateForMatcher = InputMatcher(generateFor ?? const InputSet());
builderOptions ??= const BuilderOptions({});
return InBuildPhase._(package, builder, builderOptions,
targetSources: targetSourceMatcher,
generateFor: generateForMatcher,
builderLabel: builderKey == null || builderKey.isEmpty
? _builderLabel(builder)
: _simpleBuilderKey(builderKey),
isOptional: isOptional,
hideOutput: hideOutput);
}
@override
String toString() {
final settings = <String>[];
if (isOptional) settings.add('optional');
if (hideOutput) settings.add('hidden');
var result = '$builderLabel on $targetSources in $package';
if (settings.isNotEmpty) result += ' $settings';
return result;
}
@override
int get identity => _deepEquals.hash([
builderLabel,
builder.buildExtensions,
package,
targetSources,
generateFor,
isOptional,
hideOutput
]);
}
/// A [BuildPhase] that can run multiple [PostBuildAction]s to
/// generate files.
///
/// There should only be one of these per build, and it should be the final
/// phase.
class PostBuildPhase extends BuildPhase {
final List<PostBuildAction> builderActions;
@override
bool get hideOutput => true;
@override
bool get isOptional => false;
PostBuildPhase(this.builderActions);
@override
String toString() =>
'${builderActions.map((a) => a.builderLabel).join(', ')}';
@override
int get identity =>
_deepEquals.hash(builderActions.map<dynamic>((b) => b.identity).toList()
..addAll([
isOptional,
hideOutput,
]));
}
/// Part of a larger [PostBuildPhase], applies a single
/// [PostProcessBuilder] to a single [package] with some additional options.
class PostBuildAction implements BuildAction {
@override
final PostProcessBuilder builder;
@override
final String builderLabel;
@override
final BuilderOptions builderOptions;
@override
final InputMatcher generateFor;
@override
final String package;
@override
final InputMatcher targetSources;
PostBuildAction(this.builder, this.package,
{String builderKey,
@required BuilderOptions builderOptions,
@required InputSet targetSources,
@required InputSet generateFor})
: builderLabel = builderKey == null || builderKey.isEmpty
? _builderLabel(builder)
: _simpleBuilderKey(builderKey),
builderOptions = builderOptions ?? const BuilderOptions({}),
targetSources = InputMatcher(targetSources ?? const InputSet()),
generateFor = InputMatcher(generateFor ?? const InputSet());
int get identity => _deepEquals.hash([
builderLabel,
builder.inputExtensions.toList(),
generateFor,
package,
targetSources,
]);
}
/// If we have no key find a human friendly name for the Builder.
String _builderLabel(Object builder) {
var label = '$builder';
if (label.startsWith('Instance of \'')) {
label = label.substring(13, label.length - 1);
}
return label;
}
/// Change "angular|angular" to "angular".
String _simpleBuilderKey(String builderKey) {
if (!builderKey.contains('|')) return builderKey;
var parts = builderKey.split('|');
if (parts[0] == parts[1]) return parts[0];
return builderKey;
}
final _deepEquals = const DeepCollectionEquality();
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/build_definition.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:async/async.dart';
import 'package:build/build.dart';
import 'package:collection/collection.dart';
import 'package:glob/glob.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:watcher/watcher.dart';
import '../asset/build_cache.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../asset_graph/exceptions.dart';
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../changes/build_script_updates.dart';
import '../environment/build_environment.dart';
import '../logging/failure_reporter.dart';
import '../logging/logging.dart';
import '../package_graph/package_graph.dart';
import '../package_graph/target_graph.dart';
import '../util/constants.dart';
import '../util/sdk_version_match.dart';
import 'exceptions.dart';
import 'options.dart';
import 'phase.dart';
final _logger = Logger('BuildDefinition');
class BuildDefinition {
final AssetGraph assetGraph;
final TargetGraph targetGraph;
final AssetReader reader;
final RunnerAssetWriter writer;
final PackageGraph packageGraph;
final bool deleteFilesByDefault;
final ResourceManager resourceManager;
final BuildScriptUpdates buildScriptUpdates;
/// Whether or not to run in a mode that conserves RAM at the cost of build
/// speed.
final bool enableLowResourcesMode;
final BuildEnvironment environment;
BuildDefinition._(
this.assetGraph,
this.targetGraph,
this.reader,
this.writer,
this.packageGraph,
this.deleteFilesByDefault,
this.resourceManager,
this.buildScriptUpdates,
this.enableLowResourcesMode,
this.environment);
static Future<BuildDefinition> prepareWorkspace(BuildEnvironment environment,
BuildOptions options, List<BuildPhase> buildPhases) =>
_Loader(environment, options, buildPhases).prepareWorkspace();
}
/// Understands how to find all assets relevant to a build as well as compute
/// updates to those assets.
class AssetTracker {
final AssetGraph _assetGraph;
final RunnerAssetReader _reader;
final TargetGraph _targetGraph;
AssetTracker(this._assetGraph, this._reader, this._targetGraph);
/// Checks for and returns any file system changes compared to the current
/// state of the asset graph.
Future<Map<AssetId, ChangeType>> collectChanges() async {
var inputSources = await _findInputSources();
var generatedSources = await _findCacheDirSources();
var internalSources = await _findInternalSources();
return _computeSourceUpdates(
inputSources, generatedSources, internalSources);
}
/// Returns the all the sources found in the cache directory.
Future<Set<AssetId>> _findCacheDirSources() =>
_listGeneratedAssetIds().toSet();
/// Returns the set of original package inputs on disk.
Future<Set<AssetId>> _findInputSources() {
final targets =
Stream<TargetNode>.fromIterable(_targetGraph.allModules.values);
return targets.asyncExpand(_listAssetIds).toSet();
}
/// Returns all the internal sources, such as those under [entryPointDir].
Future<Set<AssetId>> _findInternalSources() async {
var ids = await _listIdsSafe(Glob('$entryPointDir/**')).toSet();
var packageConfigId = AssetId(_targetGraph.rootPackageConfig.packageName,
'.dart_tool/package_config.json');
if (await _reader.canRead(packageConfigId)) {
ids.add(packageConfigId);
}
return ids;
}
/// Finds the asset changes which have happened while unwatched between builds
/// by taking a difference between the assets in the graph and the assets on
/// disk.
Future<Map<AssetId, ChangeType>> _computeSourceUpdates(
Set<AssetId> inputSources,
Set<AssetId> generatedSources,
Set<AssetId> internalSources) async {
final allSources = <AssetId>{}
..addAll(inputSources)
..addAll(generatedSources)
..addAll(internalSources);
var updates = <AssetId, ChangeType>{};
void addUpdates(Iterable<AssetId> assets, ChangeType type) {
for (var asset in assets) {
updates[asset] = type;
}
}
var newSources = inputSources.difference(_assetGraph.allNodes
.where((node) => node.isValidInput)
.map((node) => node.id)
.toSet());
addUpdates(newSources, ChangeType.ADD);
var removedAssets = _assetGraph.allNodes
.where((n) {
if (!n.isReadable) return false;
if (n is GeneratedAssetNode) return n.wasOutput;
return true;
})
.map((n) => n.id)
.where((id) => !allSources.contains(id));
addUpdates(removedAssets, ChangeType.REMOVE);
var originalGraphSources = _assetGraph.sources.toSet();
var preExistingSources = originalGraphSources.intersection(inputSources)
..addAll(internalSources.where(_assetGraph.contains));
var modifyChecks = preExistingSources.map((id) async {
var node = _assetGraph.get(id);
assert(node != null);
var originalDigest = node.lastKnownDigest;
if (originalDigest == null) return;
var currentDigest = await _reader.digest(id);
if (currentDigest != originalDigest) {
updates[id] = ChangeType.MODIFY;
}
});
await Future.wait(modifyChecks);
return updates;
}
Stream<AssetId> _listAssetIds(TargetNode targetNode) => targetNode
.sourceIncludes.isEmpty
? Stream<AssetId>.empty()
: StreamGroup.merge(targetNode.sourceIncludes.map((glob) =>
_listIdsSafe(glob, package: targetNode.package.name)
.where((id) =>
targetNode.package.isRoot || id.pathSegments.first == 'lib')
.where((id) => !targetNode.excludesSource(id))));
Stream<AssetId> _listGeneratedAssetIds() {
var glob = Glob('$generatedOutputDirectory/**');
return _listIdsSafe(glob).map((id) {
var packagePath = id.path.substring(generatedOutputDirectory.length + 1);
var firstSlash = packagePath.indexOf('/');
if (firstSlash == -1) return null;
var package = packagePath.substring(0, firstSlash);
var path = packagePath.substring(firstSlash + 1);
return AssetId(package, path);
}).where((id) => id != null);
}
/// Lists asset ids and swallows file not found errors.
///
/// Ideally we would warn but in practice the default whitelist will give this
/// error a lot and it would be noisy.
Stream<AssetId> _listIdsSafe(Glob glob, {String package}) =>
_reader.findAssets(glob, package: package).handleError((void _) {},
test: (e) => e is FileSystemException && e.osError.errorCode == 2);
}
class _Loader {
final List<BuildPhase> _buildPhases;
final BuildOptions _options;
final BuildEnvironment _environment;
_Loader(this._environment, this._options, this._buildPhases);
Future<BuildDefinition> prepareWorkspace() async {
_checkBuildPhases();
_logger.info('Initializing inputs');
var assetGraph = await _tryReadCachedAssetGraph();
var assetTracker =
AssetTracker(assetGraph, _environment.reader, _options.targetGraph);
var inputSources = await assetTracker._findInputSources();
var cacheDirSources = await assetTracker._findCacheDirSources();
var internalSources = await assetTracker._findInternalSources();
BuildScriptUpdates buildScriptUpdates;
if (assetGraph != null) {
var updates = await logTimedAsync(
_logger,
'Checking for updates since last build',
() => _updateAssetGraph(assetGraph, assetTracker, _buildPhases,
inputSources, cacheDirSources, internalSources));
buildScriptUpdates = await BuildScriptUpdates.create(
_environment.reader, _options.packageGraph, assetGraph,
disabled: _options.skipBuildScriptCheck);
var buildScriptUpdated = !_options.skipBuildScriptCheck &&
buildScriptUpdates.hasBeenUpdated(updates.keys.toSet());
if (buildScriptUpdated) {
_logger.warning('Invalidating asset graph due to build script update!');
var deletedSourceOutputs = await _cleanupOldOutputs(assetGraph);
if (_runningFromSnapshot) {
// We have to be regenerated if running from a snapshot.
throw BuildScriptChangedException();
}
inputSources.removeAll(deletedSourceOutputs);
assetGraph = null;
buildScriptUpdates = null;
}
}
if (assetGraph == null) {
Set<AssetId> conflictingOutputs;
await logTimedAsync(_logger, 'Building new asset graph', () async {
try {
assetGraph = await AssetGraph.build(_buildPhases, inputSources,
internalSources, _options.packageGraph, _environment.reader);
} on DuplicateAssetNodeException catch (e, st) {
_logger.severe('Conflicting outputs', e, st);
throw CannotBuildException();
}
buildScriptUpdates = await BuildScriptUpdates.create(
_environment.reader, _options.packageGraph, assetGraph,
disabled: _options.skipBuildScriptCheck);
conflictingOutputs = assetGraph.outputs
.where((n) => n.package == _options.packageGraph.root.name)
.where(inputSources.contains)
.toSet();
final conflictsInDeps = assetGraph.outputs
.where((n) => n.package != _options.packageGraph.root.name)
.where(inputSources.contains)
.toSet();
if (conflictsInDeps.isNotEmpty) {
log.severe('There are existing files in dependencies which conflict '
'with files that a Builder may produce. These must be removed or '
'the Builders disabled before a build can continue: '
'${conflictsInDeps.map((a) => a.uri).join('\n')}');
throw CannotBuildException();
}
});
await logTimedAsync(
_logger,
'Checking for unexpected pre-existing outputs.',
() => _initialBuildCleanup(conflictingOutputs,
_wrapWriter(_environment.writer, assetGraph)));
}
return BuildDefinition._(
assetGraph,
_options.targetGraph,
_wrapReader(_environment.reader, assetGraph),
_wrapWriter(_environment.writer, assetGraph),
_options.packageGraph,
_options.deleteFilesByDefault,
ResourceManager(),
buildScriptUpdates,
_options.enableLowResourcesMode,
_environment);
}
/// Checks that the [_buildPhases] are valid based on whether they are
/// written to the build cache.
void _checkBuildPhases() {
final root = _options.packageGraph.root.name;
for (final action in _buildPhases) {
if (!action.hideOutput) {
// Only `InBuildPhase`s can be not hidden.
if (action is InBuildPhase && action.package != root) {
// This should happen only with a manual build script since the build
// script generation filters these out.
_logger.severe('A build phase (${action.builderLabel}) is attempting '
'to operate on package "${action.package}", but the build script '
'is located in package "$root". It\'s not valid to attempt to '
'generate files for another package unless the BuilderApplication'
'specified "hideOutput".'
'\n\n'
'Did you mean to write:\n'
' new BuilderApplication(..., toRoot())\n'
'or\n'
' new BuilderApplication(..., hideOutput: true)\n'
'... instead?');
throw CannotBuildException();
}
}
}
}
/// Deletes the generated output directory.
///
/// Typically this should be done whenever an asset graph is thrown away.
Future<void> _deleteGeneratedDir() async {
var generatedDir = Directory(generatedOutputDirectory);
if (await generatedDir.exists()) {
await generatedDir.delete(recursive: true);
}
}
/// Attempts to read in an [AssetGraph] from disk, and returns `null` if it
/// fails for any reason.
Future<AssetGraph> _tryReadCachedAssetGraph() async {
final assetGraphId =
AssetId(_options.packageGraph.root.name, assetGraphPath);
if (!await _environment.reader.canRead(assetGraphId)) {
return null;
}
return logTimedAsync(_logger, 'Reading cached asset graph', () async {
try {
var cachedGraph = AssetGraph.deserialize(
await _environment.reader.readAsBytes(assetGraphId));
var buildPhasesChanged = computeBuildPhasesDigest(_buildPhases) !=
cachedGraph.buildPhasesDigest;
var pkgVersionsChanged = !const DeepCollectionEquality()
.equals(cachedGraph.packageLanguageVersions, {
for (var pkg in _options.packageGraph.allPackages.values)
pkg.name: pkg.languageVersion
});
if (buildPhasesChanged || pkgVersionsChanged) {
if (buildPhasesChanged) {
_logger.warning(
'Throwing away cached asset graph because the build phases have '
'changed. This most commonly would happen as a result of adding a '
'new dependency or updating your dependencies.');
}
if (pkgVersionsChanged) {
_logger.warning(
'Throwing away cached asset graph because the language '
'version of some package(s) changed. This would most commonly '
'happen when updating dependencies or changing your min sdk '
'constraint.');
}
await Future.wait([
_deleteAssetGraph(_options.packageGraph),
_cleanupOldOutputs(cachedGraph),
FailureReporter.cleanErrorCache(),
]);
if (_runningFromSnapshot) {
throw BuildScriptChangedException();
}
return null;
}
if (!isSameSdkVersion(cachedGraph.dartVersion, Platform.version)) {
_logger.warning(
'Throwing away cached asset graph due to Dart SDK update.');
await Future.wait([
_deleteAssetGraph(_options.packageGraph),
_cleanupOldOutputs(cachedGraph),
FailureReporter.cleanErrorCache(),
]);
if (_runningFromSnapshot) {
throw BuildScriptChangedException();
}
return null;
}
return cachedGraph;
} on AssetGraphCorruptedException catch (_) {
// Start fresh if the cached asset_graph cannot be deserialized
_logger.warning('Throwing away cached asset graph due to '
'version mismatch or corrupted asset graph.');
await Future.wait([
_deleteGeneratedDir(),
FailureReporter.cleanErrorCache(),
]);
return null;
}
});
}
/// Deletes all the old outputs from [graph] that were written to the source
/// tree, and deletes the entire generated directory.
Future<Iterable<AssetId>> _cleanupOldOutputs(AssetGraph graph) async {
var deletedSources = <AssetId>[];
await logTimedAsync(_logger, 'Cleaning up outputs from previous builds.',
() async {
// Delete all the non-hidden outputs.
await Future.wait(graph.outputs.map((id) {
var node = graph.get(id) as GeneratedAssetNode;
if (node.wasOutput && !node.isHidden) {
var idToDelete = id;
// If the package no longer exists, then the user must have renamed
// the root package.
//
// In that case we change `idToDelete` to be in the root package.
if (_options.packageGraph[id.package] == null) {
idToDelete = AssetId(_options.packageGraph.root.name, id.path);
}
deletedSources.add(idToDelete);
return _environment.writer.delete(idToDelete);
}
return null;
}).whereType<Future>());
await _deleteGeneratedDir();
});
return deletedSources;
}
Future<void> _deleteAssetGraph(PackageGraph packageGraph) =>
File(p.join(packageGraph.root.path, assetGraphPath)).delete();
/// Updates [assetGraph] based on a the new view of the world.
///
/// Once done, this returns a map of [AssetId] to [ChangeType] for all the
/// changes.
Future<Map<AssetId, ChangeType>> _updateAssetGraph(
AssetGraph assetGraph,
AssetTracker assetTracker,
List<BuildPhase> buildPhases,
Set<AssetId> inputSources,
Set<AssetId> cacheDirSources,
Set<AssetId> internalSources) async {
var updates = await assetTracker._computeSourceUpdates(
inputSources, cacheDirSources, internalSources);
updates.addAll(_computeBuilderOptionsUpdates(assetGraph, buildPhases));
await assetGraph.updateAndInvalidate(
_buildPhases,
updates,
_options.packageGraph.root.name,
(id) => _wrapWriter(_environment.writer, assetGraph).delete(id),
_wrapReader(_environment.reader, assetGraph));
return updates;
}
/// Wraps [original] in a [BuildCacheWriter].
RunnerAssetWriter _wrapWriter(
RunnerAssetWriter original, AssetGraph assetGraph) {
assert(assetGraph != null);
return BuildCacheWriter(
original, assetGraph, _options.packageGraph.root.name);
}
/// Wraps [original] in a [BuildCacheReader].
AssetReader _wrapReader(AssetReader original, AssetGraph assetGraph) {
assert(assetGraph != null);
return BuildCacheReader(
original, assetGraph, _options.packageGraph.root.name);
}
/// Checks for any updates to the [BuilderOptionsAssetNode]s for
/// [buildPhases] compared to the last known state.
Map<AssetId, ChangeType> _computeBuilderOptionsUpdates(
AssetGraph assetGraph, List<BuildPhase> buildPhases) {
var result = <AssetId, ChangeType>{};
void updateBuilderOptionsNode(
AssetId builderOptionsId, BuilderOptions options) {
var builderOptionsNode =
assetGraph.get(builderOptionsId) as BuilderOptionsAssetNode;
var oldDigest = builderOptionsNode.lastKnownDigest;
builderOptionsNode.lastKnownDigest = computeBuilderOptionsDigest(options);
if (builderOptionsNode.lastKnownDigest != oldDigest) {
result[builderOptionsId] = ChangeType.MODIFY;
}
}
for (var phase = 0; phase < buildPhases.length; phase++) {
var action = buildPhases[phase];
if (action is InBuildPhase) {
updateBuilderOptionsNode(
builderOptionsIdForAction(action, phase), action.builderOptions);
} else if (action is PostBuildPhase) {
var actionNum = 0;
for (var builderAction in action.builderActions) {
updateBuilderOptionsNode(
builderOptionsIdForAction(builderAction, actionNum),
builderAction.builderOptions);
actionNum++;
}
}
}
return result;
}
/// Handles cleanup of pre-existing outputs for initial builds (where there is
/// no cached graph).
Future<void> _initialBuildCleanup(
Set<AssetId> conflictingAssets, RunnerAssetWriter writer) async {
if (conflictingAssets.isEmpty) return;
// Skip the prompt if using this option.
if (_options.deleteFilesByDefault) {
_logger.info('Deleting ${conflictingAssets.length} declared outputs '
'which already existed on disk.');
await Future.wait(conflictingAssets.map((id) => writer.delete(id)));
return;
}
// Prompt the user to delete files that are declared as outputs.
_logger.info('Found ${conflictingAssets.length} declared outputs '
'which already exist on disk. This is likely because the'
'`$cacheDir` folder was deleted, or you are submitting generated '
'files to your source repository.');
var done = false;
while (!done) {
try {
var choice = await _environment.prompt('Delete these files?',
['Delete', 'Cancel build', 'List conflicts']);
switch (choice) {
case 0:
_logger.info('Deleting files...');
done = true;
await Future.wait(conflictingAssets.map((id) => writer.delete(id)));
break;
case 1:
_logger.severe('The build will not be able to contiue until the '
'conflicting assets are removed or the Builders which may '
'output them are disabled. The outputs are: '
'${conflictingAssets.map((a) => a.path).join('\n')}');
throw CannotBuildException();
break;
case 2:
_logger.info('Conflicts:\n${conflictingAssets.join('\n')}');
// Logging should be sync :(
await Future(() {});
}
} on NonInteractiveBuildException {
_logger.severe('Conflicting outputs were detected and the build '
'is unable to prompt for permission to remove them. '
'These outputs must be removed manually or the build can be '
'run with `--delete-conflicting-outputs`. The outputs are: '
'${conflictingAssets.map((a) => a.path).join('\n')}');
throw CannotBuildException();
}
}
}
}
bool get _runningFromSnapshot => !Platform.script.path.endsWith('.dart');
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/options.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:build_resolvers/build_resolvers.dart';
import 'package:glob/glob.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import '../environment/build_environment.dart';
import '../package_graph/package_graph.dart';
import '../package_graph/target_graph.dart';
import '../util/hash.dart';
import 'exceptions.dart';
/// The default list of files to include when an explicit include is not
/// provided.
const List<String> defaultRootPackageWhitelist = [
'assets/**',
'benchmark/**',
'bin/**',
'example/**',
'lib/**',
'test/**',
'tool/**',
'web/**',
'node/**',
'pubspec.yaml',
'pubspec.lock',
r'$package$',
];
final _logger = Logger('BuildOptions');
class LogSubscription {
factory LogSubscription(BuildEnvironment environment,
{bool verbose, Level logLevel}) {
// Set up logging
verbose ??= false;
logLevel ??= verbose ? Level.ALL : Level.INFO;
// Severe logs can fail the build and should always be shown.
if (logLevel == Level.OFF) logLevel = Level.SEVERE;
Logger.root.level = logLevel;
var logListener = Logger.root.onRecord.listen(environment.onLog);
return LogSubscription._(logListener);
}
LogSubscription._(this.logListener);
final StreamSubscription<LogRecord> logListener;
}
/// Describes a set of files that should be built.
class BuildFilter {
/// The package name glob that files must live under in order to match.
final Glob _package;
/// A glob for files under [_package] that must match.
final Glob _path;
BuildFilter(this._package, this._path);
/// Builds a [BuildFilter] from a command line argument.
///
/// Both relative paths and package: uris are supported. Relative
/// paths are treated as relative to the [rootPackage].
///
/// Globs are supported in package names and paths.
factory BuildFilter.fromArg(String arg, String rootPackage) {
var uri = Uri.parse(arg);
if (uri.scheme == 'package') {
var package = uri.pathSegments.first;
var glob = Glob(p.url.joinAll([
'lib',
...uri.pathSegments.skip(1),
]));
return BuildFilter(Glob(package), glob);
} else if (uri.scheme.isEmpty) {
return BuildFilter(Glob(rootPackage), Glob(uri.path));
} else {
throw FormatException('Unsupported scheme ${uri.scheme}', uri);
}
}
/// Returns whether or not [id] mathes this filter.
bool matches(AssetId id) =>
_package.matches(id.package) && _path.matches(id.path);
@override
int get hashCode {
var hash = 0;
hash = hashCombine(hash, _package.context.hashCode);
hash = hashCombine(hash, _package.pattern.hashCode);
hash = hashCombine(hash, _package.recursive.hashCode);
hash = hashCombine(hash, _path.context.hashCode);
hash = hashCombine(hash, _path.pattern.hashCode);
hash = hashCombine(hash, _path.recursive.hashCode);
return hashComplete(hash);
}
@override
bool operator ==(Object other) =>
other is BuildFilter &&
other._path.context == _path.context &&
other._path.pattern == _path.pattern &&
other._path.recursive == _path.recursive &&
other._package.context == _package.context &&
other._package.pattern == _package.pattern &&
other._package.recursive == _package.recursive;
}
/// Manages setting up consistent defaults for all options and build modes.
class BuildOptions {
final bool deleteFilesByDefault;
final bool enableLowResourcesMode;
final StreamSubscription logListener;
/// If present, the path to a directory to write performance logs to.
final String logPerformanceDir;
final PackageGraph packageGraph;
final Resolvers resolvers;
final TargetGraph targetGraph;
final bool trackPerformance;
// Watch mode options.
Duration debounceDelay;
// For testing only, skips the build script updates check.
bool skipBuildScriptCheck;
BuildOptions._({
@required this.debounceDelay,
@required this.deleteFilesByDefault,
@required this.enableLowResourcesMode,
@required this.logListener,
@required this.packageGraph,
@required this.skipBuildScriptCheck,
@required this.trackPerformance,
@required this.targetGraph,
@required this.logPerformanceDir,
@required this.resolvers,
});
static Future<BuildOptions> create(
LogSubscription logSubscription, {
Duration debounceDelay,
bool deleteFilesByDefault,
bool enableLowResourcesMode,
@required PackageGraph packageGraph,
Map<String, BuildConfig> overrideBuildConfig,
bool skipBuildScriptCheck,
bool trackPerformance,
String logPerformanceDir,
Resolvers resolvers,
}) async {
TargetGraph targetGraph;
try {
targetGraph = await TargetGraph.forPackageGraph(packageGraph,
overrideBuildConfig: overrideBuildConfig,
defaultRootPackageWhitelist: defaultRootPackageWhitelist,
requiredSourcePaths: [r'lib/$lib$'],
requiredRootSourcePaths: [r'$package$', r'lib/$lib$']);
} on BuildConfigParseException catch (e, s) {
_logger.severe('''
Failed to parse `build.yaml` for ${e.packageName}.
If you believe you have gotten this message in error, especially if using a new
feature, you may need to run `pub run build_runner clean` and then rebuild.
''', e.exception, s);
throw CannotBuildException();
}
/// Set up other defaults.
debounceDelay ??= const Duration(milliseconds: 250);
deleteFilesByDefault ??= false;
skipBuildScriptCheck ??= false;
enableLowResourcesMode ??= false;
trackPerformance ??= false;
if (logPerformanceDir != null) {
// Requiring this to be under the root package allows us to use an
// `AssetWriter` to write logs.
if (!p.isWithin(p.current, logPerformanceDir)) {
_logger.severe('Performance logs may only be output under the root '
'package, but got `$logPerformanceDir` which is not.');
throw CannotBuildException();
}
trackPerformance = true;
}
resolvers ??= AnalyzerResolvers();
return BuildOptions._(
debounceDelay: debounceDelay,
deleteFilesByDefault: deleteFilesByDefault,
enableLowResourcesMode: enableLowResourcesMode,
logListener: logSubscription.logListener,
packageGraph: packageGraph,
skipBuildScriptCheck: skipBuildScriptCheck,
trackPerformance: trackPerformance,
targetGraph: targetGraph,
logPerformanceDir: logPerformanceDir,
resolvers: resolvers,
);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/performance_tracker.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of build_runner.src.generate.performance_tracker;
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BuildPerformance _$BuildPerformanceFromJson(Map<String, dynamic> json) {
return BuildPerformance(
(json['phases'] as List)?.map((e) => e == null
? null
: BuildPhasePerformance.fromJson(e as Map<String, dynamic>)),
(json['actions'] as List)?.map((e) => e == null
? null
: BuilderActionPerformance.fromJson(e as Map<String, dynamic>)),
json['startTime'] == null
? null
: DateTime.parse(json['startTime'] as String),
json['stopTime'] == null
? null
: DateTime.parse(json['stopTime'] as String));
}
Map<String, dynamic> _$BuildPerformanceToJson(BuildPerformance instance) =>
<String, dynamic>{
'startTime': instance.startTime?.toIso8601String(),
'stopTime': instance.stopTime?.toIso8601String(),
'phases': instance.phases?.toList(),
'actions': instance.actions?.toList()
};
BuildPhasePerformance _$BuildPhasePerformanceFromJson(
Map<String, dynamic> json) {
return BuildPhasePerformance(
(json['builderKeys'] as List)?.map((e) => e as String)?.toList(),
json['startTime'] == null
? null
: DateTime.parse(json['startTime'] as String),
json['stopTime'] == null
? null
: DateTime.parse(json['stopTime'] as String));
}
Map<String, dynamic> _$BuildPhasePerformanceToJson(
BuildPhasePerformance instance) =>
<String, dynamic>{
'startTime': instance.startTime?.toIso8601String(),
'stopTime': instance.stopTime?.toIso8601String(),
'builderKeys': instance.builderKeys
};
BuilderActionPerformance _$BuilderActionPerformanceFromJson(
Map<String, dynamic> json) {
return BuilderActionPerformance(
json['builderKey'] as String,
_assetIdFromJson(json['primaryInput'] as String),
(json['stages'] as List)?.map((e) => e == null
? null
: BuilderActionStagePerformance.fromJson(e as Map<String, dynamic>)),
json['startTime'] == null
? null
: DateTime.parse(json['startTime'] as String),
json['stopTime'] == null
? null
: DateTime.parse(json['stopTime'] as String));
}
Map<String, dynamic> _$BuilderActionPerformanceToJson(
BuilderActionPerformance instance) =>
<String, dynamic>{
'startTime': instance.startTime?.toIso8601String(),
'stopTime': instance.stopTime?.toIso8601String(),
'builderKey': instance.builderKey,
'primaryInput': _assetIdToJson(instance.primaryInput),
'stages': instance.stages?.toList()
};
BuilderActionStagePerformance _$BuilderActionStagePerformanceFromJson(
Map<String, dynamic> json) {
return BuilderActionStagePerformance(
json['label'] as String,
(json['slices'] as List)
?.map((e) =>
e == null ? null : TimeSlice.fromJson(e as Map<String, dynamic>))
?.toList());
}
Map<String, dynamic> _$BuilderActionStagePerformanceToJson(
BuilderActionStagePerformance instance) =>
<String, dynamic>{'slices': instance.slices, 'label': instance.label};
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/build_directory.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import '../util/hash.dart';
class BuildDirectory {
final String directory;
final OutputLocation outputLocation;
BuildDirectory(this.directory, {this.outputLocation});
@override
bool operator ==(Object other) =>
other is BuildDirectory &&
other.directory == directory &&
other.outputLocation == outputLocation;
@override
int get hashCode {
var hash = 0;
hash = hashCombine(hash, directory.hashCode);
hash = hashCombine(hash, outputLocation.hashCode);
return hashComplete(hash);
}
}
class OutputLocation {
final String path;
final bool useSymlinks;
final bool hoist;
OutputLocation(this.path, {bool useSymlinks, bool hoist})
: useSymlinks = useSymlinks ?? false,
hoist = hoist ?? true {
if (path.isEmpty && hoist) {
throw ArgumentError('Can not build everything and hoist');
}
}
@override
bool operator ==(Object other) =>
other is OutputLocation &&
other.path == path &&
other.useSymlinks == useSymlinks &&
other.hoist == hoist;
@override
int get hashCode {
var hash = 0;
hash = hashCombine(hash, path.hashCode);
hash = hashCombine(hash, useSymlinks.hashCode);
hash = hashCombine(hash, hoist.hashCode);
return hashComplete(hash);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/finalized_assets_view.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:path/path.dart' as p;
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../asset_graph/optional_output_tracker.dart';
/// A lazily computed view of all the assets available after a build.
///
/// Note that this class has a limited lifetime during which it is available,
/// and should not be used outside of the scope in which it is given. It will
/// throw a [StateError] if you attempt to use it once it has expired.
class FinalizedAssetsView {
final AssetGraph _assetGraph;
final OptionalOutputTracker _optionalOutputTracker;
bool _expired = false;
FinalizedAssetsView(this._assetGraph, this._optionalOutputTracker);
List<AssetId> allAssets({String rootDir}) {
if (_expired) {
throw StateError(
'Cannot use a FinalizedAssetsView after it has expired!');
}
return _assetGraph.allNodes
.map((node) {
if (_shouldSkipNode(node, rootDir, _optionalOutputTracker)) {
return null;
}
return node.id;
})
.where((id) => id != null)
.toList();
}
void markExpired() {
assert(!_expired);
_expired = true;
}
}
bool _shouldSkipNode(AssetNode node, String rootDir,
OptionalOutputTracker optionalOutputTracker) {
if (!node.isReadable) return true;
if (node.isDeleted) return true;
if (rootDir != null &&
!node.id.path.startsWith('lib/') &&
!p.isWithin(rootDir, node.id.path)) {
return true;
}
if (node is InternalAssetNode) return true;
if (node is GeneratedAssetNode) {
if (!node.wasOutput || node.isFailure || node.state != NodeState.upToDate) {
return true;
}
return !optionalOutputTracker.isRequired(node.id);
}
if (node.id.path == '.packages') return true;
if (node.id.path == '.dart_tool/package_config.json') return true;
return false;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/input_matcher.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:collection/collection.dart';
import 'package:glob/glob.dart';
/// A filter on files to run through a Builder.
class InputMatcher {
/// The files to include
///
/// Null or empty means include everything.
final List<Glob> includeGlobs;
/// The files within [includeGlobs] to exclude.
///
/// Null or empty means exclude nothing.
final List<Glob> excludeGlobs;
InputMatcher(InputSet inputSet, {List<String> defaultInclude})
: includeGlobs =
(inputSet.include ?? defaultInclude)?.map((p) => Glob(p))?.toList(),
excludeGlobs = inputSet.exclude?.map((p) => Glob(p))?.toList();
/// Whether [input] is included in this set of assets.
bool matches(AssetId input) => includes(input) && !excludes(input);
/// Whether [input] matches any [includeGlobs].
///
/// If there are no [includeGlobs] this always returns `true`.
bool includes(AssetId input) =>
includeGlobs == null ||
includeGlobs.isEmpty ||
includeGlobs.any((g) => g.matches(input.path));
/// Whether [input] matches any [excludeGlobs].
///
/// If there are no [excludeGlobs] this always returns `false`.
bool excludes(AssetId input) =>
excludeGlobs != null &&
excludeGlobs.isNotEmpty &&
excludeGlobs.any((g) => g.matches(input.path));
@override
String toString() {
final result = StringBuffer();
if (includeGlobs == null || includeGlobs.isEmpty) {
result.write('any assets');
} else {
result.write('assets matching ${_patterns(includeGlobs).toList()}');
}
if (excludeGlobs != null && excludeGlobs.isNotEmpty) {
result.write(' except ${_patterns(excludeGlobs).toList()}');
}
return '$result';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is InputMatcher &&
_deepEquals.equals(
_patterns(includeGlobs), _patterns(other.includeGlobs)) &&
_deepEquals.equals(
_patterns(excludeGlobs), _patterns(other.excludeGlobs)));
@override
int get hashCode =>
_deepEquals.hash([_patterns(includeGlobs), _patterns(excludeGlobs)]);
}
final _deepEquals = const DeepCollectionEquality();
Iterable<String> _patterns(Iterable<Glob> globs) =>
globs?.map((g) => g.pattern);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/heartbeat.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:logging/logging.dart';
import '../logging/human_readable_duration.dart';
var _logger = Logger('Heartbeat');
/// Base class for a heartbeat implementation.
///
/// Once [start]ed, if [waitDuration] passes between calls to [ping], then
/// [onTimeout] will be invoked with the duration.
abstract class Heartbeat {
Stopwatch _intervalWatch;
Timer _timer;
/// The interval at which to check if [waitDuration] has passed.
final Duration checkInterval;
/// The amount of time between heartbeats.
final Duration waitDuration;
Heartbeat({Duration checkInterval, Duration waitDuration})
: checkInterval = checkInterval ?? const Duration(milliseconds: 100),
waitDuration = waitDuration ?? const Duration(seconds: 5);
/// Invoked if [waitDuration] time has elapsed since the last call to [ping].
void onTimeout(Duration elapsed);
/// Resets the internal timers. If more than [waitDuration] elapses without
/// this method being called, then [onTimeout] will be invoked with the
/// duration since the last ping.
void ping() {
_intervalWatch.reset();
}
/// Starts this heartbeat logger, must not already be started.
///
/// This method can be overridden to add additional logic for handling calls
/// to [ping], but you must call `super.start()`.
void start() {
if (_intervalWatch != null || _timer != null) {
throw StateError('HeartbeatLogger already started');
}
_intervalWatch = Stopwatch()..start();
ping();
_timer = Timer.periodic(checkInterval, _checkDuration);
}
/// Stops this heartbeat logger, must already be started.
///
/// This method can be overridden to add additional logic for cleanup
/// purposes, but you must call `super.stop()`.
void stop() {
if (_intervalWatch == null || _timer == null) {
throw StateError('HeartbeatLogger was never started');
}
_intervalWatch.stop();
_intervalWatch = null;
_timer.cancel();
_timer = null;
}
void _checkDuration(void _) {
if (_intervalWatch.elapsed < waitDuration) return;
onTimeout(_intervalWatch.elapsed);
ping();
}
}
/// Watches [Logger.root] and if there are no logs for [waitDuration] then it
/// will log a heartbeat message with the current elapsed time since [start] was
/// originally invoked.
class HeartbeatLogger extends Heartbeat {
StreamSubscription<LogRecord> _listener;
Stopwatch _totalWatch;
/// Will be invoked with each original log message and the returned value will
/// be logged instead.
final String Function(String original) transformLog;
HeartbeatLogger(
{Duration checkInterval, Duration waitDuration, this.transformLog})
: super(checkInterval: checkInterval, waitDuration: waitDuration);
/// Start listening to logs.
@override
void start() {
_totalWatch = Stopwatch()..start();
super.start();
_listener = Logger.root.onRecord.listen((_) => ping());
}
/// Stops listenting to the logger;
@override
void stop() {
super.stop();
_listener.cancel();
_listener = null;
_totalWatch.stop();
_totalWatch = null;
}
/// Logs a heartbeat message if we reach the timeout.
@override
void onTimeout(void _) {
var formattedTime = humanReadable(_totalWatch.elapsed);
var message = '$formattedTime elapsed';
if (transformLog != null) {
message = transformLog(message);
}
_logger.info(message);
}
}
class HungActionsHeartbeat extends Heartbeat {
/// Returns a description of pending actions
final String Function() listActions;
HungActionsHeartbeat(this.listActions,
{Duration checkInterval, Duration waitDuration})
: super(
checkInterval: checkInterval,
waitDuration: waitDuration ?? Duration(seconds: 15));
@override
void onTimeout(Duration elapsed) {
var formattedTime = humanReadable(elapsed);
var message = 'No actions completed for $formattedTime, '
'waiting on:\n${listActions()}';
_logger.warning(message);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/generate/performance_tracker.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@experimental
library build_runner.src.generate.performance_tracker;
import 'dart:async';
import 'package:build/build.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'package:timing/timing.dart';
import 'phase.dart';
part 'performance_tracker.g.dart';
/// The [TimeSlice] of an entire build, including all its [actions].
@JsonSerializable()
class BuildPerformance extends TimeSlice {
/// The [TimeSlice] of each phase ran in this build.
final Iterable<BuildPhasePerformance> phases;
/// The [TimeSlice] of running an individual [Builder] on an individual input.
final Iterable<BuilderActionPerformance> actions;
BuildPerformance(
this.phases, this.actions, DateTime startTime, DateTime stopTime)
: super(startTime, stopTime);
factory BuildPerformance.fromJson(Map<String, dynamic> json) =>
_$BuildPerformanceFromJson(json);
@override
Map<String, dynamic> toJson() => _$BuildPerformanceToJson(this);
}
/// The [TimeSlice] of a full [BuildPhase] within a larger build.
@JsonSerializable()
class BuildPhasePerformance extends TimeSlice {
final List<String> builderKeys;
BuildPhasePerformance(this.builderKeys, DateTime startTime, DateTime stopTime)
: super(startTime, stopTime);
factory BuildPhasePerformance.fromJson(Map<String, dynamic> json) =>
_$BuildPhasePerformanceFromJson(json);
@override
Map<String, dynamic> toJson() => _$BuildPhasePerformanceToJson(this);
}
/// The [TimeSlice] of a [builderKey] running on [primaryInput] within a build.
@JsonSerializable()
class BuilderActionPerformance extends TimeSlice {
final String builderKey;
@JsonKey(fromJson: _assetIdFromJson, toJson: _assetIdToJson)
final AssetId primaryInput;
final Iterable<BuilderActionStagePerformance> stages;
Duration get innerDuration => stages.fold(
Duration.zero, (duration, stage) => duration + stage.innerDuration);
BuilderActionPerformance(this.builderKey, this.primaryInput, this.stages,
DateTime startTime, DateTime stopTime)
: super(startTime, stopTime);
factory BuilderActionPerformance.fromJson(Map<String, dynamic> json) =>
_$BuilderActionPerformanceFromJson(json);
@override
Map<String, dynamic> toJson() => _$BuilderActionPerformanceToJson(this);
}
/// The [TimeSlice] of a particular task within a builder action.
///
/// This is some slice of overall [BuilderActionPerformance].
@JsonSerializable()
class BuilderActionStagePerformance extends TimeSliceGroup {
final String label;
BuilderActionStagePerformance(this.label, List<TimeSlice> slices)
: super(slices);
factory BuilderActionStagePerformance.fromJson(Map<String, dynamic> json) =>
_$BuilderActionStagePerformanceFromJson(json);
@override
Map<String, dynamic> toJson() => _$BuilderActionStagePerformanceToJson(this);
}
/// Interface for tracking the overall performance of a build.
abstract class BuildPerformanceTracker
implements TimeTracker, BuildPerformance {
/// Tracks [runPhase] which performs [action] on all inputs in a phase, and
/// return the outputs generated.
Future<Iterable<AssetId>> trackBuildPhase(
BuildPhase action, Future<Iterable<AssetId>> Function() runPhase);
/// Returns a [BuilderActionTracker] for tracking [builderKey] on
/// [primaryInput] and adds it to [actions].
BuilderActionTracker addBuilderAction(
AssetId primaryInput, String builderKey);
factory BuildPerformanceTracker() => _BuildPerformanceTrackerImpl();
/// A [BuildPerformanceTracker] with as little overhead as possible. Does no
/// actual tracking and does not implement many fields/methods.
factory BuildPerformanceTracker.noOp() =>
_NoOpBuildPerformanceTracker.sharedInstance;
}
/// Real implementation of [BuildPerformanceTracker].
///
/// Use [BuildPerformanceTracker] factory to get an instance.
class _BuildPerformanceTrackerImpl extends SimpleAsyncTimeTracker
implements BuildPerformanceTracker {
@override
Iterable<BuildPhaseTracker> get phases => _phases;
final _phases = <BuildPhaseTracker>[];
@override
Iterable<BuilderActionTracker> get actions => _actions;
final _actions = <BuilderActionTracker>[];
/// Tracks [action] which is ran with [runPhase].
///
/// This represents running a [Builder] on a group of sources.
///
/// Returns all the outputs generated by the phase.
@override
Future<Iterable<AssetId>> trackBuildPhase(
BuildPhase action, Future<Iterable<AssetId>> Function() runPhase) {
assert(isTracking);
var tracker = BuildPhaseTracker(action);
_phases.add(tracker);
return tracker.track(runPhase);
}
/// Returns a new [BuilderActionTracker] and adds it to [actions].
///
/// The [BuilderActionTracker] will already be started, but you must stop it.
@override
BuilderActionTracker addBuilderAction(
AssetId primaryInput, String builderKey) {
assert(isTracking);
var tracker = BuilderActionTracker(primaryInput, builderKey);
_actions.add(tracker);
return tracker;
}
@override
Map<String, dynamic> toJson() => _$BuildPerformanceToJson(this);
}
/// No-op implementation of [BuildPerformanceTracker].
///
/// Read-only fields will throw, and tracking methods just directly invoke their
/// closures without tracking anything.
///
/// Use [BuildPerformanceTracker.noOp] to get an instance.
class _NoOpBuildPerformanceTracker extends NoOpTimeTracker
implements BuildPerformanceTracker {
static final _NoOpBuildPerformanceTracker sharedInstance =
_NoOpBuildPerformanceTracker();
@override
Iterable<BuilderActionTracker> get actions => throw UnimplementedError();
@override
Iterable<BuildPhaseTracker> get phases => throw UnimplementedError();
@override
BuilderActionTracker addBuilderAction(
AssetId primaryInput, String builderKey) =>
BuilderActionTracker.noOp();
@override
Future<Iterable<AssetId>> trackBuildPhase(
BuildPhase action, Future<Iterable<AssetId>> Function() runPhase) =>
runPhase();
@override
Map<String, dynamic> toJson() => _$BuildPerformanceToJson(this);
}
/// Internal class that tracks the [TimeSlice] of an entire [BuildPhase].
///
/// Tracks total time it took to run on all inputs available to that action.
///
/// Use [track] to start actually tracking an operation.
///
/// This is only meaningful for non-lazy phases.
class BuildPhaseTracker extends SimpleAsyncTimeTracker
implements BuildPhasePerformance {
@override
final List<String> builderKeys;
BuildPhaseTracker(BuildPhase action)
: builderKeys = action is InBuildPhase
? [action.builderLabel]
: (action as PostBuildPhase)
.builderActions
.map((action) => action.builderLabel)
.toList();
@override
Map<String, dynamic> toJson() => _$BuildPhasePerformanceToJson(this);
}
/// Interface for tracking the [TimeSlice] of an individual [Builder] on a given
/// primary input.
abstract class BuilderActionTracker
implements TimeTracker, BuilderActionPerformance, StageTracker {
/// Tracks the time of [runStage] and associates it with [label].
///
/// You can specify [runStage] as [isExternal] (waiting for some external
/// resource like network, process or file IO). In that case [runStage] will
/// be tracked as single time slice from the beginning of the stage till
/// completion of Future returned by [runStage].
///
/// Otherwise all separate time slices of asynchronous execution will be
/// tracked, but waiting for external resources will be a gap.
@override
T trackStage<T>(String label, T Function() runStage,
{bool isExternal = false});
factory BuilderActionTracker(AssetId primaryInput, String builderKey) =>
_BuilderActionTrackerImpl(primaryInput, builderKey);
/// A [BuilderActionTracker] with as little overhead as possible. Does no
/// actual tracking and does not implement many fields/methods.
factory BuilderActionTracker.noOp() =>
_NoOpBuilderActionTracker._sharedInstance;
}
/// Real implementation of [BuilderActionTracker] which records timings.
///
/// Use the [BuilderActionTracker] factory to get an instance.
class _BuilderActionTrackerImpl extends SimpleAsyncTimeTracker
implements BuilderActionTracker {
@override
final String builderKey;
@override
final AssetId primaryInput;
@override
final List<BuilderActionStageTracker> stages = [];
@override
Duration get innerDuration => stages.fold(
Duration.zero, (duration, stage) => duration + stage.innerDuration);
_BuilderActionTrackerImpl(this.primaryInput, this.builderKey);
@override
T trackStage<T>(String label, T Function() action,
{bool isExternal = false}) {
var tracker = isExternal
? BuilderActionStageSimpleTracker(label)
: BuilderActionStageAsyncTracker(label);
stages.add(tracker);
return tracker.track(action);
}
@override
Map<String, dynamic> toJson() => _$BuilderActionPerformanceToJson(this);
}
/// No-op instance of [BuilderActionTracker] which does nothing and throws an
/// unimplemented error for everything but [trackStage], which delegates directly to
/// the wrapped function.
///
/// Use the [BuilderActionTracker.noOp] factory to get an instance.
class _NoOpBuilderActionTracker extends NoOpTimeTracker
implements BuilderActionTracker {
static final _NoOpBuilderActionTracker _sharedInstance =
_NoOpBuilderActionTracker();
@override
String get builderKey => throw UnimplementedError();
@override
Duration get duration => throw UnimplementedError();
@override
Iterable<BuilderActionStagePerformance> get stages =>
throw UnimplementedError();
@override
Duration get innerDuration => throw UnimplementedError();
@override
AssetId get primaryInput => throw UnimplementedError();
@override
T trackStage<T>(String label, T Function() runStage,
{bool isExternal = false}) =>
runStage();
@override
Map<String, dynamic> toJson() => _$BuilderActionPerformanceToJson(this);
}
/// Tracks the [TimeSliceGroup] of an individual task.
///
/// These represent a slice of the [BuilderActionPerformance].
abstract class BuilderActionStageTracker
implements BuilderActionStagePerformance {
T track<T>(T Function() action);
}
class BuilderActionStageAsyncTracker extends AsyncTimeTracker
implements BuilderActionStageTracker {
@override
final String label;
BuilderActionStageAsyncTracker(this.label) : super(trackNested: false);
@override
Map<String, dynamic> toJson() => _$BuilderActionStagePerformanceToJson(this);
}
class BuilderActionStageSimpleTracker extends BuilderActionStagePerformance
implements BuilderActionStageTracker {
final _tracker = SimpleAsyncTimeTracker();
BuilderActionStageSimpleTracker(String label) : super(label, []) {
slices.add(_tracker);
}
@override
T track<T>(T Function() action) => _tracker.track(action);
}
AssetId _assetIdFromJson(String json) => AssetId.parse(json);
String _assetIdToJson(AssetId id) => id.toString();
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/logging/logging.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:logging/logging.dart';
import 'human_readable_duration.dart';
// Ensures this message does not get overwritten by later logs.
final _logSuffix = '\n';
/// Logs an asynchronous [action] with [description] before and after.
///
/// Returns a future that completes after the action and logging finishes.
Future<T> logTimedAsync<T>(
Logger logger,
String description,
Future<T> Function() action, {
Level level = Level.INFO,
}) async {
final watch = Stopwatch()..start();
logger.log(level, '$description...');
final result = await action();
watch.stop();
final time = '${humanReadable(watch.elapsed)}$_logSuffix';
logger.log(level, '$description completed, took $time');
return result;
}
/// Logs a synchronous [action] with [description] before and after.
///
/// Returns a future that completes after the action and logging finishes.
T logTimedSync<T>(
Logger logger,
String description,
T Function() action, {
Level level = Level.INFO,
}) {
final watch = Stopwatch()..start();
logger.log(level, '$description...');
final result = action();
watch.stop();
final time = '${humanReadable(watch.elapsed)}$_logSuffix';
logger.log(level, '$description completed, took $time');
return result;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/logging/failure_reporter.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:build/build.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import '../asset_graph/node.dart';
import '../util/constants.dart';
/// A tracker for the errors which have already been reported during the current
/// build.
///
/// Errors that occur due to actions that are run within this build will be
/// reported directly as they happen. When an action is skipped and remains a
/// failure the error will not have been reported by the time we check wether
/// the build is failed.
///
/// The lifetime of this class should be a single build.
class FailureReporter {
/// Removes all stored errors from previous builds.
///
/// This should be called any time the build phases change since the naming
/// scheme is dependent on the build phases.
static Future<void> cleanErrorCache() async {
final errorCacheDirectory = Directory(errorCachePath);
if (await errorCacheDirectory.exists()) {
await errorCacheDirectory.delete(recursive: true);
}
}
/// Remove the stored error for [phaseNumber] runnon on [primaryInput].
///
/// This should be called anytime the action is being run.
static Future<void> clean(int phaseNumber, AssetId primaryInput) async {
final errorFile =
File(_errorPathForPrimaryInput(phaseNumber, primaryInput));
if (await errorFile.exists()) {
await errorFile.delete();
}
}
/// A set of Strings which uniquely identify a particular build action and
/// it's primary input.
final _reportedActions = <String>{};
/// Indicate that a failure reason for the build step which would produce
/// [output] and all other outputs from the same build step has been printed.
Future<void> markReported(String actionDescription, GeneratedAssetNode output,
Iterable<ErrorReport> errors) async {
if (!_reportedActions.add(_actionKey(output))) return;
final errorFile =
await File(_errorPathForOutput(output)).create(recursive: true);
await errorFile.writeAsString(jsonEncode(<dynamic>[actionDescription]
.followedBy(errors
.map((e) => [e.message, e.error, e.stackTrace?.toString() ?? '']))
.toList()));
}
/// Indicate that the build steps which would produce [outputs] are failing
/// due to a dependency and being skipped so no actuall error will be
/// produced.
Future<void> markSkipped(Iterable<GeneratedAssetNode> outputs) =>
Future.wait(outputs.map((output) async {
if (!_reportedActions.add(_actionKey(output))) return;
await clean(output.phaseNumber, output.primaryInput);
}));
/// Log stored errors for any build steps which would output nodes in
/// [failingNodes] which haven't already been reported.
Future<void> reportErrors(Iterable<GeneratedAssetNode> failingNodes) {
final errorFiles = <File>[];
for (final failure in failingNodes) {
final key = _actionKey(failure);
if (!_reportedActions.add(key)) continue;
errorFiles.add(File(_errorPathForOutput(failure)));
}
return Future.wait(errorFiles.map((errorFile) async {
if (await errorFile.exists()) {
final errorReports = jsonDecode(await errorFile.readAsString()) as List;
final actionDescription = '${errorReports.first} (cached)';
final logger = Logger(actionDescription);
for (final error in errorReports.skip(1).cast<List>()) {
final stackTraceString = error[2] as String;
final stackTrace = stackTraceString.isEmpty
? null
: StackTrace.fromString(stackTraceString);
logger.severe(error[0], error[1], stackTrace);
}
}
}));
}
}
/// Matches the call to [Logger.severe] except the [message] and [error] are
/// eagerly converted to String.
class ErrorReport {
final String message;
final String error;
final StackTrace stackTrace;
ErrorReport(this.message, this.error, this.stackTrace);
}
String _actionKey(GeneratedAssetNode node) =>
'${node.builderOptionsId} on ${node.primaryInput}';
String _errorPathForOutput(GeneratedAssetNode output) => p.joinAll([
errorCachePath,
output.id.package,
'${output.phaseNumber}',
...p.posix.split(output.primaryInput.path)
]);
String _errorPathForPrimaryInput(int phaseNumber, AssetId primaryInput) =>
p.joinAll([
errorCachePath,
primaryInput.package,
'$phaseNumber',
...p.posix.split(primaryInput.path)
]);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/logging/human_readable_duration.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Returns a human readable string for a duration.
///
/// Handles durations that span up to hours - this will not be a good fit for
/// durations that are longer than days.
///
/// Always attempts 2 'levels' of precision. Will show hours/minutes,
/// minutes/seconds, seconds/tenths of a second, or milliseconds depending on
/// the largest level that needs to be displayed.
String humanReadable(Duration duration) {
if (duration < const Duration(seconds: 1)) {
return '${duration.inMilliseconds}ms';
}
if (duration < const Duration(minutes: 1)) {
return '${(duration.inMilliseconds / 1000.0).toStringAsFixed(1)}s';
}
if (duration < const Duration(hours: 1)) {
final minutes = duration.inMinutes;
final remaining = duration - Duration(minutes: minutes);
return '${minutes}m ${remaining.inSeconds}s';
}
final hours = duration.inHours;
final remaining = duration - Duration(hours: hours);
return '${hours}h ${remaining.inMinutes}m';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/logging/build_for_input_logger.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:logging/logging.dart';
import 'failure_reporter.dart';
/// A delegating [Logger] that records if any logs of level >= [Level.SEVERE]
/// were seen.
class BuildForInputLogger implements Logger {
final Logger _delegate;
final errorsSeen = <ErrorReport>[];
BuildForInputLogger(this._delegate);
@override
Level get level => _delegate.level;
@override
set level(Level level) => _delegate.level = level;
@override
Map<String, Logger> get children => _delegate.children;
@override
void clearListeners() => _delegate.clearListeners();
@override
void config(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.config(message, error, stackTrace);
@override
void fine(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.fine(message, error, stackTrace);
@override
void finer(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.finer(message, error, stackTrace);
@override
void finest(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.finest(message, error, stackTrace);
@override
String get fullName => _delegate.fullName;
@override
void info(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.info(message, error, stackTrace);
@override
bool isLoggable(Level value) => _delegate.isLoggable(value);
@override
void log(Level logLevel, Object message,
[Object error, StackTrace stackTrace, Zone zone]) {
if (logLevel >= Level.SEVERE) {
errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace));
}
_delegate.log(logLevel, message, error, stackTrace, zone);
}
@override
String get name => _delegate.name;
@override
Stream<LogRecord> get onRecord => _delegate.onRecord;
@override
Logger get parent => _delegate.parent;
@override
void severe(Object message, [Object error, StackTrace stackTrace]) {
errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace));
_delegate.severe(message, error, stackTrace);
}
@override
void shout(Object message, [Object error, StackTrace stackTrace]) {
errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace));
_delegate.shout(message, error, stackTrace);
}
@override
void warning(Object message, [Object error, StackTrace stackTrace]) =>
_delegate.warning(message, error, stackTrace);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/clock.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
/// A function that returns the current [DateTime].
typedef _Clock = DateTime Function();
DateTime _defaultClock() => DateTime.now();
/// Returns the current [DateTime].
///
/// May be overridden for tests using [scopeClock].
DateTime now() => (Zone.current[_Clock] as _Clock ?? _defaultClock)();
/// Runs [f], with [clock] scoped whenever [now] is called.
T scopeClock<T>(DateTime Function() clock, T Function() f) =>
runZoned(f, zoneValues: {_Clock: clock});
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/constants.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:path/path.dart' as p;
/// Relative path to the asset graph from the root package dir.
final String assetGraphPath = assetGraphPathFor(_scriptPath);
/// Relative path to the asset graph for a build script at [path]
String assetGraphPathFor(String path) =>
'$cacheDir/${_scriptHashFor(path)}/asset_graph.json';
/// Relative path to the directory which holds serialized versions of errors
/// reported during previous builds.
final errorCachePath =
p.join(cacheDir, _scriptHashFor(_scriptPath), 'error_cache');
final String _scriptPath = Platform.script.scheme == 'file'
? p.url.joinAll(
p.split(p.relative(Platform.script.toFilePath(), from: p.current)))
: Platform.script.path;
/// Directory containing automatically generated build entrypoints.
///
/// Files in this directory must be read to do build script invalidation.
const entryPointDir = '$cacheDir/entrypoint';
/// The directory to which hidden assets will be written.
String get generatedOutputDirectory => '$cacheDir/$_generatedOutputDirectory';
/// Locks the generated directory name for the duration of this process.
///
/// This should be invoked before any builds start.
void lockGeneratedOutputDirectory() => _generatedOutputDirectoryIsLocked = true;
/// The default generated dir name. Can be modified with
/// [overrideGeneratedOutputDirectory].
String _generatedOutputDirectory = 'generated';
/// Whether or not the [generatedOutputDirectory] is locked. This must be `true`
/// before you can access [generatedOutputDirectory];
bool _generatedOutputDirectoryIsLocked = false;
/// Overrides the generated directory name.
///
/// This is interpreted as a relative path under the [cacheDir].
void overrideGeneratedOutputDirectory(String path) {
if (_generatedOutputDirectory != 'generated') {
throw StateError('You can only override the generated dir once.');
} else if (_generatedOutputDirectoryIsLocked) {
throw StateError(
'Attempted to override the generated dir after it was locked.');
} else if (!p.isRelative(path)) {
throw StateError('Only relative paths are accepted for the generated dir '
'but got `$path`.');
}
_generatedOutputDirectory = path;
}
/// Relative path to the cache directory from the root package dir.
const String cacheDir = '.dart_tool/build';
/// Returns a hash for a given Dart script path.
///
/// Normalizes between snapshot and Dart source file paths so they give the same
/// hash.
String _scriptHashFor(String path) => md5
.convert(utf8.encode(
path.endsWith('.snapshot') ? path.substring(0, path.length - 9) : path))
.toString();
/// The name of the pub binary on the current platform.
final pubBinary = p.join(sdkBin, Platform.isWindows ? 'pub.bat' : 'pub');
/// The path to the sdk bin directory on the current platform.
final sdkBin = p.join(sdkPath, 'bin');
/// The path to the sdk on the current platform.
final sdkPath = p.dirname(p.dirname(Platform.resolvedExecutable));
/// The maximum number of concurrent actions to run per build phase.
const buildPhasePoolSize = 16;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/sdk_version_match.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Checks whether [thisVersion] and [thatVersion] have the same semver
/// identifier without extra platform specific information.
bool isSameSdkVersion(String thisVersion, String thatVersion) =>
thisVersion?.split(' ')?.first == thatVersion?.split(' ')?.first;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/async.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
/// Invokes [callback] and returns the result as soon as possible. This will
/// happen synchronously if [value] is available.
FutureOr<S> doAfter<T, S>(
FutureOr<T> value, FutureOr<S> Function(T value) callback) {
if (value is Future<T>) {
return value.then(callback);
} else {
return callback(value as T);
}
}
/// Converts [value] to a [Future] if it is not already.
Future<T> toFuture<T>(FutureOr<T> value) =>
value is Future<T> ? value : Future.value(value);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/hash.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
int hashCombine(int hash, int value) {
hash = 0x1fffffff & (hash + value);
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
return hash ^ (hash >> 6);
}
int hashComplete(int hash) {
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/util/build_dirs.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import '../generate/options.dart';
import '../generate/phase.dart';
/// Returns whether or not [id] should be built based upon [buildDirs],
/// [phase], and optional [buildFilters].
///
/// The logic for this is as follows:
///
/// - If any [buildFilters] are supplied, then this only returns `true` if [id]
/// explicitly matches one of the filters.
/// - If no [buildFilters] are supplied, then the old behavior applies - all
/// build to source builders and all files under `lib` of all packages are
/// always built.
/// - Regardless of the [buildFilters] setting, if [buildDirs] is supplied then
/// `id.path` must start with one of the specified directory names.
bool shouldBuildForDirs(AssetId id, Set<String> buildDirs,
Set<BuildFilter> buildFilters, BuildPhase phase) {
buildFilters ??= {};
if (buildFilters.isEmpty) {
if (!phase.hideOutput) return true;
if (id.path.startsWith('lib/')) return true;
} else {
if (!buildFilters.any((f) => f.matches(id))) {
return false;
}
}
if (buildDirs.isEmpty) return true;
return id.path.startsWith('lib/') || buildDirs.any(id.path.startsWith);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/writer.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
@deprecated
typedef OnDelete = void Function(AssetId id);
abstract class RunnerAssetWriter implements AssetWriter {
Future delete(AssetId id);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/lru_cache.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// A basic LRU Cache.
class LruCache<K, V> {
_Link<K, V> _head;
_Link<K, V> _tail;
final int Function(V) _computeWeight;
int _currentWeightTotal = 0;
final int _individualWeightMax;
final int _totalWeightMax;
final _entries = <K, _Link<K, V>>{};
LruCache(
this._individualWeightMax, this._totalWeightMax, this._computeWeight);
V operator [](K key) {
var entry = _entries[key];
if (entry == null) return null;
_promote(entry);
return entry.value;
}
void operator []=(K key, V value) {
var entry = _Link(key, value, _computeWeight(value));
// Don't cache at all if above the individual weight max.
if (entry.weight > _individualWeightMax) {
return;
}
_entries[key] = entry;
_currentWeightTotal += entry.weight;
_promote(entry);
while (_currentWeightTotal > _totalWeightMax) {
assert(_tail != null);
remove(_tail.key);
}
}
/// Removes the value at [key] from the cache, and returns the value if it
/// existed.
V remove(K key) {
var entry = _entries[key];
if (entry == null) return null;
_currentWeightTotal -= entry.weight;
_entries.remove(key);
if (entry == _tail) {
_tail = entry.next;
_tail?.previous = null;
}
if (entry == _head) {
_head = entry.previous;
_head?.next = null;
}
return entry.value;
}
/// Moves [link] to the [_head] of the list.
void _promote(_Link<K, V> link) {
if (link == _head) return;
if (link == _tail) {
_tail = link.next;
}
if (link.previous != null) {
link.previous.next = link.next;
}
if (link.next != null) {
link.next.previous = link.previous;
}
_head?.next = link;
link.previous = _head;
_head = link;
_tail ??= link;
link.next = null;
}
}
/// A [MapEntry] which is also a part of a doubly linked list.
class _Link<K, V> implements MapEntry<K, V> {
_Link<K, V> next;
_Link<K, V> previous;
final int weight;
@override
final K key;
@override
final V value;
_Link(this.key, this.value, this.weight);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/build_cache.dart | import 'dart:async';
import 'dart:convert';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../util/constants.dart';
import 'reader.dart';
import 'writer.dart';
/// Wraps an [AssetReader] and translates reads for generated files into reads
/// from the build cache directory
class BuildCacheReader implements AssetReader {
final AssetGraph _assetGraph;
final AssetReader _delegate;
final String _rootPackage;
BuildCacheReader._(this._delegate, this._assetGraph, this._rootPackage);
factory BuildCacheReader(
AssetReader delegate, AssetGraph assetGraph, String rootPackage) =>
delegate is PathProvidingAssetReader
? _PathProvidingBuildCacheReader._(delegate, assetGraph, rootPackage)
: BuildCacheReader._(delegate, assetGraph, rootPackage);
@override
Future<bool> canRead(AssetId id) =>
_delegate.canRead(_cacheLocation(id, _assetGraph, _rootPackage));
@override
Future<Digest> digest(AssetId id) =>
_delegate.digest(_cacheLocation(id, _assetGraph, _rootPackage));
@override
Future<List<int>> readAsBytes(AssetId id) =>
_delegate.readAsBytes(_cacheLocation(id, _assetGraph, _rootPackage));
@override
Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) =>
_delegate.readAsString(_cacheLocation(id, _assetGraph, _rootPackage),
encoding: encoding);
@override
Stream<AssetId> findAssets(Glob glob) => throw UnimplementedError(
'Asset globbing should be done per phase with the AssetGraph');
}
class _PathProvidingBuildCacheReader extends BuildCacheReader
implements PathProvidingAssetReader {
@override
PathProvidingAssetReader get _delegate =>
super._delegate as PathProvidingAssetReader;
_PathProvidingBuildCacheReader._(PathProvidingAssetReader delegate,
AssetGraph assetGraph, String rootPackage)
: super._(delegate, assetGraph, rootPackage);
@override
String pathTo(AssetId id) =>
_delegate.pathTo(_cacheLocation(id, _assetGraph, _rootPackage));
}
class BuildCacheWriter implements RunnerAssetWriter {
final AssetGraph _assetGraph;
final RunnerAssetWriter _delegate;
final String _rootPackage;
BuildCacheWriter(this._delegate, this._assetGraph, this._rootPackage);
@override
Future writeAsBytes(AssetId id, List<int> content) => _delegate.writeAsBytes(
_cacheLocation(id, _assetGraph, _rootPackage), content);
@override
Future writeAsString(AssetId id, String content,
{Encoding encoding = utf8}) =>
_delegate.writeAsString(
_cacheLocation(id, _assetGraph, _rootPackage), content,
encoding: encoding);
@override
Future delete(AssetId id) =>
_delegate.delete(_cacheLocation(id, _assetGraph, _rootPackage));
}
AssetId _cacheLocation(AssetId id, AssetGraph assetGraph, String rootPackage) {
if (id.path.startsWith(generatedOutputDirectory) ||
id.path.startsWith(cacheDir)) {
return id;
}
if (!assetGraph.contains(id)) {
return id;
}
final assetNode = assetGraph.get(id);
if (assetNode is GeneratedAssetNode && assetNode.isHidden) {
return AssetId(
rootPackage, '$generatedOutputDirectory/${id.package}/${id.path}');
}
return id;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/finalized_reader.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:build/build.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:build_runner_core/src/generate/phase.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../asset_graph/optional_output_tracker.dart';
/// An [AssetReader] which ignores deleted files.
class FinalizedReader implements AssetReader {
final AssetReader _delegate;
final AssetGraph _assetGraph;
OptionalOutputTracker _optionalOutputTracker;
final String _rootPackage;
final List<BuildPhase> _buildPhases;
void reset(Set<String> buildDirs, Set<BuildFilter> buildFilters) {
_optionalOutputTracker = OptionalOutputTracker(
_assetGraph, buildDirs, buildFilters, _buildPhases);
}
FinalizedReader(
this._delegate, this._assetGraph, this._buildPhases, this._rootPackage);
/// Returns a reason why [id] is not readable, or null if it is readable.
Future<UnreadableReason> unreadableReason(AssetId id) async {
if (!_assetGraph.contains(id)) return UnreadableReason.notFound;
var node = _assetGraph.get(id);
if (node.isDeleted) return UnreadableReason.deleted;
if (!node.isReadable) return UnreadableReason.assetType;
if (node is GeneratedAssetNode) {
if (node.isFailure) return UnreadableReason.failed;
if (!(node.wasOutput && (_optionalOutputTracker.isRequired(node.id)))) {
return UnreadableReason.notOutput;
}
}
if (await _delegate.canRead(id)) return null;
return UnreadableReason.unknown;
}
@override
Future<bool> canRead(AssetId id) async =>
(await unreadableReason(id)) == null;
@override
Future<Digest> digest(AssetId id) => _delegate.digest(id);
@override
Future<List<int>> readAsBytes(AssetId id) => _delegate.readAsBytes(id);
@override
Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) async {
if (_assetGraph.get(id)?.isDeleted ?? true) {
throw AssetNotFoundException(id);
}
return _delegate.readAsString(id, encoding: encoding);
}
@override
Stream<AssetId> findAssets(Glob glob) async* {
var potentialNodes = _assetGraph
.packageNodes(_rootPackage)
.where((n) => glob.matches(n.id.path))
.toList();
var potentialIds = potentialNodes.map((n) => n.id).toList();
for (var id in potentialIds) {
if (await _delegate.canRead(id)) {
yield id;
}
}
}
}
enum UnreadableReason {
notFound,
notOutput,
assetType,
deleted,
failed,
unknown,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/reader.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'package:async/async.dart';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import 'package:meta/meta.dart';
import '../asset_graph/graph.dart';
import '../asset_graph/node.dart';
import '../util/async.dart';
/// A [RunnerAssetReader] must implement [MultiPackageAssetReader].
abstract class RunnerAssetReader implements MultiPackageAssetReader {}
/// An [AssetReader] that can provide actual paths to assets on disk.
abstract class PathProvidingAssetReader implements AssetReader {
String pathTo(AssetId id);
}
/// Describes if and how a [SingleStepReader] should read an [AssetId].
class Readability {
final bool canRead;
final bool inSamePhase;
const Readability({@required this.canRead, @required this.inSamePhase});
/// Determines readability for a node written in a previous build phase, which
/// means that [ownOutput] is impossible.
factory Readability.fromPreviousPhase(bool readable) =>
readable ? Readability.readable : Readability.notReadable;
static const Readability notReadable =
Readability(canRead: false, inSamePhase: false);
static const Readability readable =
Readability(canRead: true, inSamePhase: false);
static const Readability ownOutput =
Readability(canRead: true, inSamePhase: true);
}
typedef IsReadable = FutureOr<Readability> Function(
AssetNode node, int phaseNum, AssetWriterSpy writtenAssets);
/// An [AssetReader] with a lifetime equivalent to that of a single step in a
/// build.
///
/// A step is a single Builder and primary input (or package for package
/// builders) combination.
///
/// Limits reads to the assets which are sources or were generated by previous
/// phases.
///
/// Tracks the assets and globs read during this step for input dependency
/// tracking.
class SingleStepReader implements AssetReader {
final AssetGraph _assetGraph;
final AssetReader _delegate;
final int _phaseNumber;
final String _primaryPackage;
final AssetWriterSpy _writtenAssets;
final IsReadable _isReadableNode;
final FutureOr<GlobAssetNode> Function(
Glob glob, String package, int phaseNum) _getGlobNode;
/// The assets read during this step.
final assetsRead = HashSet<AssetId>();
SingleStepReader(this._delegate, this._assetGraph, this._phaseNumber,
this._primaryPackage, this._isReadableNode,
[this._getGlobNode, this._writtenAssets]);
/// Checks whether [id] can be read by this step - attempting to build the
/// asset if necessary.
FutureOr<bool> _isReadable(AssetId id) {
final node = _assetGraph.get(id);
if (node == null) {
assetsRead.add(id);
_assetGraph.add(SyntheticSourceAssetNode(id));
return false;
}
return doAfter(_isReadableNode(node, _phaseNumber, _writtenAssets),
(Readability readability) {
if (!readability.inSamePhase) {
assetsRead.add(id);
}
return readability.canRead;
});
}
@override
Future<bool> canRead(AssetId id) {
return toFuture(doAfter(_isReadable(id), (bool isReadable) {
if (!isReadable) return false;
var node = _assetGraph.get(id);
FutureOr<bool> _canRead() {
if (node is GeneratedAssetNode) {
// Short circut, we know this file exists because its readable and it was
// output.
return true;
} else {
return _delegate.canRead(id);
}
}
return doAfter(_canRead(), (bool canRead) {
if (!canRead) return false;
return doAfter(_ensureDigest(id), (_) => true);
});
}));
}
@override
Future<Digest> digest(AssetId id) {
return toFuture(doAfter(_isReadable(id), (bool isReadable) {
if (!isReadable) {
return Future.error(AssetNotFoundException(id));
}
return _ensureDigest(id);
}));
}
@override
Future<List<int>> readAsBytes(AssetId id) {
return toFuture(doAfter(_isReadable(id), (bool isReadable) {
if (!isReadable) {
return Future.error(AssetNotFoundException(id));
}
return doAfter(_ensureDigest(id), (_) => _delegate.readAsBytes(id));
}));
}
@override
Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) {
return toFuture(doAfter(_isReadable(id), (bool isReadable) {
if (!isReadable) {
return Future.error(AssetNotFoundException(id));
}
return doAfter(_ensureDigest(id),
(_) => _delegate.readAsString(id, encoding: encoding));
}));
}
@override
Stream<AssetId> findAssets(Glob glob) {
var streamCompleter = StreamCompleter<AssetId>();
doAfter(_getGlobNode(glob, _primaryPackage, _phaseNumber),
(GlobAssetNode globNode) {
assetsRead.add(globNode.id);
streamCompleter.setSourceStream(Stream.fromIterable(globNode.results));
});
return streamCompleter.stream;
}
FutureOr<Digest> _ensureDigest(AssetId id) {
var node = _assetGraph.get(id);
if (node?.lastKnownDigest != null) return node.lastKnownDigest;
return _delegate.digest(id).then((digest) => node.lastKnownDigest = digest);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/cache.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'package:glob/glob.dart';
import 'lru_cache.dart';
import 'reader.dart';
/// An [AssetReader] that caches all results from the delegate.
///
/// Assets are cached until [invalidate] is invoked.
///
/// Does not implement [findAssets].
class CachingAssetReader implements AssetReader {
/// Cached results of [readAsBytes].
final _bytesContentCache = LruCache<AssetId, List<int>>(
1024 * 1024,
1024 * 1024 * 512,
(value) => value is Uint8List ? value.lengthInBytes : value.length * 8);
/// Pending [readAsBytes] operations.
final _pendingBytesContentCache = <AssetId, Future<List<int>>>{};
/// Cached results of [canRead].
///
/// Don't bother using an LRU cache for this since it's just booleans.
final _canReadCache = <AssetId, Future<bool>>{};
/// Cached results of [readAsString].
///
/// These are computed and stored lazily using [readAsBytes].
///
/// Only files read with [utf8] encoding (the default) will ever be cached.
final _stringContentCache = LruCache<AssetId, String>(
1024 * 1024, 1024 * 1024 * 512, (value) => value.length);
/// Pending `readAsString` operations.
final _pendingStringContentCache = <AssetId, Future<String>>{};
final AssetReader _delegate;
CachingAssetReader._(this._delegate);
factory CachingAssetReader(AssetReader delegate) =>
delegate is PathProvidingAssetReader
? _PathProvidingCachingAssetReader._(delegate)
: CachingAssetReader._(delegate);
@override
Future<bool> canRead(AssetId id) =>
_canReadCache.putIfAbsent(id, () => _delegate.canRead(id));
@override
Future<Digest> digest(AssetId id) => _delegate.digest(id);
@override
Stream<AssetId> findAssets(Glob glob) =>
throw UnimplementedError('unimplemented!');
@override
Future<List<int>> readAsBytes(AssetId id, {bool cache = true}) {
var cached = _bytesContentCache[id];
if (cached != null) return Future.value(cached);
return _pendingBytesContentCache.putIfAbsent(
id,
() => _delegate.readAsBytes(id).then((result) {
if (cache) _bytesContentCache[id] = result;
_pendingBytesContentCache.remove(id);
return result;
}));
}
@override
Future<String> readAsString(AssetId id, {Encoding encoding}) {
encoding ??= utf8;
if (encoding != utf8) {
// Fallback case, we never cache the String value for the non-default,
// encoding but we do allow it to cache the bytes.
return readAsBytes(id).then(encoding.decode);
}
var cached = _stringContentCache[id];
if (cached != null) return Future.value(cached);
return _pendingStringContentCache.putIfAbsent(
id,
() => readAsBytes(id, cache: false).then((bytes) {
var decoded = encoding.decode(bytes);
_stringContentCache[id] = decoded;
_pendingStringContentCache.remove(id);
return decoded;
}));
}
/// Clears all [ids] from all caches.
void invalidate(Iterable<AssetId> ids) {
for (var id in ids) {
_bytesContentCache.remove(id);
_canReadCache.remove(id);
_stringContentCache.remove(id);
_pendingBytesContentCache.remove(id);
_pendingStringContentCache.remove(id);
}
}
}
/// A version of a [CachingAssetReader] that implements
/// [PathProvidingAssetReader].
class _PathProvidingCachingAssetReader extends CachingAssetReader
implements PathProvidingAssetReader {
@override
PathProvidingAssetReader get _delegate =>
super._delegate as PathProvidingAssetReader;
_PathProvidingCachingAssetReader._(AssetReader delegate) : super._(delegate);
@override
String pathTo(AssetId id) => _delegate.pathTo(id);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/asset/file_based.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:build/build.dart';
import 'package:glob/glob.dart';
import 'package:path/path.dart' as path;
import 'package:pool/pool.dart';
import '../package_graph/package_graph.dart';
import 'reader.dart';
import 'writer.dart';
/// Pool for async file operations, we don't want to use too many file handles.
final _descriptorPool = Pool(32);
/// Basic [AssetReader] which uses a [PackageGraph] to look up where to read
/// files from disk.
class FileBasedAssetReader extends AssetReader
implements RunnerAssetReader, PathProvidingAssetReader {
final PackageGraph packageGraph;
FileBasedAssetReader(this.packageGraph);
@override
Future<bool> canRead(AssetId id) =>
_descriptorPool.withResource(() => _fileFor(id, packageGraph).exists());
@override
Future<List<int>> readAsBytes(AssetId id) => _fileForOrThrow(id, packageGraph)
.then((file) => _descriptorPool.withResource(file.readAsBytes));
@override
Future<String> readAsString(AssetId id, {Encoding encoding}) =>
_fileForOrThrow(id, packageGraph).then((file) => _descriptorPool
.withResource(() => file.readAsString(encoding: encoding ?? utf8)));
@override
Stream<AssetId> findAssets(Glob glob, {String package}) {
var packageNode =
package == null ? packageGraph.root : packageGraph[package];
if (packageNode == null) {
throw ArgumentError(
"Could not find package '$package' which was listed as "
'an input. Please ensure you have that package in your deps, or '
'remove it from your input sets.');
}
return glob
.list(followLinks: true, root: packageNode.path)
.where((e) => e is File && !path.basename(e.path).startsWith('._'))
.cast<File>()
.map((file) => _fileToAssetId(file, packageNode));
}
@override
String pathTo(AssetId id) => _filePathFor(id, packageGraph);
}
/// Creates an [AssetId] for [file], which is a part of [packageNode].
AssetId _fileToAssetId(File file, PackageNode packageNode) {
var filePath = path.normalize(file.absolute.path);
var relativePath = path.relative(filePath, from: packageNode.path);
return AssetId(packageNode.name, relativePath);
}
/// Basic [AssetWriter] which uses a [PackageGraph] to look up where to write
/// files to disk.
class FileBasedAssetWriter implements RunnerAssetWriter {
final PackageGraph packageGraph;
FileBasedAssetWriter(this.packageGraph);
@override
Future writeAsBytes(AssetId id, List<int> bytes) async {
var file = _fileFor(id, packageGraph);
await _descriptorPool.withResource(() async {
await file.create(recursive: true);
await file.writeAsBytes(bytes);
});
}
@override
Future writeAsString(AssetId id, String contents,
{Encoding encoding = utf8}) async {
var file = _fileFor(id, packageGraph);
await _descriptorPool.withResource(() async {
await file.create(recursive: true);
await file.writeAsString(contents, encoding: encoding);
});
}
@override
Future delete(AssetId id) {
if (id.package != packageGraph.root.name) {
throw InvalidOutputException(
id, 'Should not delete assets outside of ${packageGraph.root.name}');
}
var file = _fileFor(id, packageGraph);
return _descriptorPool.withResource(() async {
if (await file.exists()) {
await file.delete();
}
});
}
}
/// Returns the path to [id] for a given [packageGraph].
String _filePathFor(AssetId id, PackageGraph packageGraph) {
var package = packageGraph[id.package];
if (package == null) {
throw PackageNotFoundException(id.package);
}
return path.join(package.path, id.path);
}
/// Returns a [File] for [id] given [packageGraph].
File _fileFor(AssetId id, PackageGraph packageGraph) {
return File(_filePathFor(id, packageGraph));
}
/// Returns a [Future<File>] for [id] given [packageGraph].
///
/// Throws an `AssetNotFoundException` if it doesn't exist.
Future<File> _fileForOrThrow(AssetId id, PackageGraph packageGraph) {
if (packageGraph[id.package] == null) {
return Future.error(PackageNotFoundException(id.package));
}
var file = _fileFor(id, packageGraph);
return _descriptorPool.withResource(file.exists).then((exists) {
if (!exists) throw AssetNotFoundException(id);
return file;
});
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/validation/config_validation.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build_config/build_config.dart';
import 'package:logging/logging.dart';
import '../package_graph/apply_builders.dart';
/// Checks that all configuration is for valid builder keys.
void validateBuilderConfig(
Iterable<BuilderApplication> builders,
BuildConfig rootPackageConfig,
Map<String, Map<String, dynamic>> builderConfigOverrides,
Logger logger) {
final builderKeys = builders.map((b) => b.builderKey).toSet();
for (final key in builderConfigOverrides.keys) {
if (!builderKeys.contains(key)) {
logger.warning('Overriding configuration for `$key` but this is not a '
'known Builder');
}
}
for (final target in rootPackageConfig.buildTargets.values) {
for (final key in target.builders.keys) {
if (!builderKeys.contains(key)) {
logger.warning('Configuring `$key` in target `${target.key}` but this '
'is not a known Builder');
}
}
}
for (final key in rootPackageConfig.globalOptions.keys) {
if (!builderKeys.contains(key)) {
logger.warning('Configuring `$key` in global options but this is not a '
'known Builder');
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/package_graph/package_graph.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:package_config/package_config.dart';
import 'package:path/path.dart' as p;
import 'package:yaml/yaml.dart';
import '../util/constants.dart';
/// The SDK package, we filter this to the core libs and dev compiler
/// resources.
final _sdkPackageNode = PackageNode(
r'$sdk',
sdkPath,
DependencyType.hosted,
// A fake language version for the SDK, we don't allow you to read its
// sources anyways, and invalidate the whole build if this changes.
LanguageVersion(0, 0));
/// A graph of the package dependencies for an application.
class PackageGraph {
/// The root application package.
final PackageNode root;
/// All [PackageNode]s indexed by package name.
final Map<String, PackageNode> allPackages;
PackageGraph._(this.root, Map<String, PackageNode> allPackages)
: allPackages = Map.unmodifiable(
Map<String, PackageNode>.from(allPackages)
..putIfAbsent(r'$sdk', () => _sdkPackageNode)) {
if (!root.isRoot) {
throw ArgumentError('Root node must indicate `isRoot`');
}
if (allPackages.values.where((n) => n != root).any((n) => n.isRoot)) {
throw ArgumentError('No nodes other than the root may indicate `isRoot`');
}
}
/// Creates a [PackageGraph] given the [root] [PackageNode].
factory PackageGraph.fromRoot(PackageNode root) {
final allPackages = <String, PackageNode>{root.name: root};
void addDeps(PackageNode package) {
for (var dep in package.dependencies) {
if (allPackages.containsKey(dep.name)) continue;
allPackages[dep.name] = dep;
addDeps(dep);
}
}
addDeps(root);
return PackageGraph._(root, allPackages);
}
/// Creates a [PackageGraph] for the package whose top level directory lives
/// at [packagePath] (no trailing slash).
static Future<PackageGraph> forPath(String packagePath) async {
/// Read in the pubspec file and parse it as yaml.
final pubspec = File(p.join(packagePath, 'pubspec.yaml'));
if (!pubspec.existsSync()) {
throw StateError(
'Unable to generate package graph, no `pubspec.yaml` found. '
'This program must be ran from the root directory of your package.');
}
final rootPubspec = _pubspecForPath(packagePath);
final rootPackageName = rootPubspec['name'] as String;
final packageConfig =
await findPackageConfig(Directory(packagePath), recurse: false);
final dependencyTypes = _parseDependencyTypes(packagePath);
final nodes = <String, PackageNode>{};
// A consistent package order _should_ mean a consistent order of build
// phases. It's not a guarantee, but also not required for correctness, only
// an optimization.
final consistentlyOrderedPackages = packageConfig.packages.toList()
..sort((a, b) => a.name.compareTo(b.name));
for (final package in consistentlyOrderedPackages) {
var isRoot = package.name == rootPackageName;
nodes[package.name] = PackageNode(
package.name,
package.root.toFilePath(),
isRoot ? DependencyType.path : dependencyTypes[package.name],
package.languageVersion,
isRoot: isRoot);
}
final rootNode = nodes[rootPackageName];
rootNode.dependencies
.addAll(_depsFromYaml(rootPubspec, isRoot: true).map((n) => nodes[n]));
final packageDependencies = _parsePackageDependencies(
packageConfig.packages.where((p) => p.name != rootPackageName));
for (final packageName in packageDependencies.keys) {
nodes[packageName]
.dependencies
.addAll(packageDependencies[packageName].map((n) => nodes[n]));
}
return PackageGraph._(rootNode, nodes);
}
/// Creates a [PackageGraph] for the package in which you are currently
/// running.
static Future<PackageGraph> forThisPackage() =>
PackageGraph.forPath(p.current);
/// Shorthand to get a package by name.
PackageNode operator [](String packageName) => allPackages[packageName];
@override
String toString() {
var buffer = StringBuffer();
for (var package in allPackages.values) {
buffer.writeln('$package');
}
return buffer.toString();
}
}
/// A node in a [PackageGraph].
class PackageNode {
/// The name of the package as listed in `pubspec.yaml`.
final String name;
/// The type of dependency being used to pull in this package.
///
/// May be `null`.
final DependencyType dependencyType;
/// All the packages that this package directly depends on.
final List<PackageNode> dependencies = [];
/// The absolute path of the current version of this package.
///
/// Paths are platform dependent.
final String path;
/// Whether this node is the [PackageGraph.root].
final bool isRoot;
final LanguageVersion languageVersion;
PackageNode(this.name, String path, this.dependencyType, this.languageVersion,
{bool isRoot})
: path = _toAbsolute(path),
isRoot = isRoot ?? false;
@override
String toString() => '''
$name:
type: $dependencyType
path: $path
dependencies: [${dependencies.map((d) => d.name).join(', ')}]''';
/// Converts [path] to a canonical absolute path, returns `null` if given
/// `null`.
static String _toAbsolute(String path) =>
(path == null) ? null : p.canonicalize(path);
}
/// The type of dependency being used. This dictates how the package should be
/// watched for changes.
enum DependencyType { github, path, hosted }
/// Parse the `pubspec.lock` file and return a Map from package name to the type
/// of dependency.
Map<String, DependencyType> _parseDependencyTypes(String rootPackagePath) {
final pubspecLock = File(p.join(rootPackagePath, 'pubspec.lock'));
if (!pubspecLock.existsSync()) {
throw StateError(
'Unable to generate package graph, no `pubspec.lock` found. '
'This program must be ran from the root directory of your package.');
}
final dependencyTypes = <String, DependencyType>{};
final dependencies = loadYaml(pubspecLock.readAsStringSync()) as YamlMap;
for (final packageName in dependencies['packages'].keys) {
final source = dependencies['packages'][packageName]['source'];
dependencyTypes[packageName as String] =
_dependencyTypeFromSource(source as String);
}
return dependencyTypes;
}
DependencyType _dependencyTypeFromSource(String source) {
switch (source) {
case 'git':
return DependencyType.github;
case 'hosted':
return DependencyType.hosted;
case 'path':
case 'sdk': // Until Flutter supports another type, assum same as path.
return DependencyType.path;
}
throw ArgumentError('Unable to determine dependency type:\n$source');
}
/// Read the pubspec for each package in [packages] and finds it's
/// dependencies.
Map<String, List<String>> _parsePackageDependencies(
Iterable<Package> packages) {
final dependencies = <String, List<String>>{};
for (final package in packages) {
final pubspec = _pubspecForPath(package.root.toFilePath());
dependencies[package.name] = _depsFromYaml(pubspec);
}
return dependencies;
}
/// Gets the deps from a yaml file, taking into account dependency_overrides.
List<String> _depsFromYaml(YamlMap yaml, {bool isRoot = false}) {
var deps = <String>{
..._stringKeys(yaml['dependencies'] as Map),
if (isRoot) ..._stringKeys(yaml['dev_dependencies'] as Map),
if (isRoot) ..._stringKeys(yaml['dependency_overrides'] as Map),
};
// A consistent package order _should_ mean a consistent order of build
// phases. It's not a guarantee, but also not required for correctness, only
// an optimization.
return deps.toList()..sort();
}
Iterable<String> _stringKeys(Map m) =>
m == null ? const [] : m.keys.cast<String>();
/// Should point to the top level directory for the package.
YamlMap _pubspecForPath(String absolutePath) {
var pubspecPath = p.join(absolutePath, 'pubspec.yaml');
var pubspec = File(pubspecPath);
if (!pubspec.existsSync()) {
throw StateError(
'Unable to generate package graph, no `$pubspecPath` found.');
}
return loadYaml(pubspec.readAsStringSync()) as YamlMap;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/package_graph/apply_builders.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:build/build.dart';
import 'package:build/src/builder/logging.dart';
import 'package:build_config/build_config.dart';
import 'package:graphs/graphs.dart';
import 'package:logging/logging.dart';
import '../generate/exceptions.dart';
import '../generate/phase.dart';
import '../validation/config_validation.dart';
import 'package_graph.dart';
import 'target_graph.dart';
typedef BuildPhaseFactory = BuildPhase Function(
PackageNode package,
BuilderOptions options,
InputSet targetSources,
InputSet generateFor,
bool isReleaseBuild);
typedef PackageFilter = bool Function(PackageNode node);
/// Run a builder on all packages in the package graph.
PackageFilter toAllPackages() => (_) => true;
/// Require manual configuration to opt in to a builder.
PackageFilter toNoneByDefault() => (_) => false;
/// Run a builder on all packages with an immediate dependency on [packageName].
PackageFilter toDependentsOf(String packageName) =>
(p) => p.dependencies.any((d) => d.name == packageName);
/// Run a builder on a single package.
PackageFilter toPackage(String package) => (p) => p.name == package;
/// Run a builder on a collection of packages.
PackageFilter toPackages(Set<String> packages) =>
(p) => packages.contains(p.name);
/// Run a builders if the package matches any of [filters]
PackageFilter toAll(Iterable<PackageFilter> filters) =>
(p) => filters.any((f) => f(p));
PackageFilter toRoot() => (p) => p.isRoot;
/// Apply [builder] to the root package.
///
/// Creates a `BuilderApplication` which corresponds to an empty builder key so
/// that no other `build.yaml` based configuration will apply.
BuilderApplication applyToRoot(Builder builder,
{bool isOptional = false,
bool hideOutput = false,
InputSet generateFor}) =>
BuilderApplication.forBuilder('', [(_) => builder], toRoot(),
isOptional: isOptional,
hideOutput: hideOutput,
defaultGenerateFor: generateFor);
/// Apply each builder from [builderFactories] to the packages matching
/// [filter].
///
/// If the builder should only run on a subset of files within a target pass
/// globs to [defaultGenerateFor]. This can be overridden by any target which
/// configured the builder manually.
///
/// If [isOptional] is true the builder will only run if one of its outputs is
/// read by a later builder, or is used as a primary input to a later builder.
/// If no build actions read the output of an optional action, then it will
/// never run.
///
/// Any existing Builders which match a key in [appliesBuilders] will
/// automatically be applied to any target which runs this Builder, whether
/// because it matches [filter] or because it was enabled manually.
BuilderApplication apply(String builderKey,
List<BuilderFactory> builderFactories, PackageFilter filter,
{bool isOptional,
bool hideOutput,
InputSet defaultGenerateFor,
BuilderOptions defaultOptions,
BuilderOptions defaultDevOptions,
BuilderOptions defaultReleaseOptions,
Iterable<String> appliesBuilders}) =>
BuilderApplication.forBuilder(
builderKey,
builderFactories,
filter,
isOptional: isOptional,
hideOutput: hideOutput,
defaultGenerateFor: defaultGenerateFor,
defaultOptions: defaultOptions,
defaultDevOptions: defaultDevOptions,
defaultReleaseOptions: defaultReleaseOptions,
appliesBuilders: appliesBuilders,
);
/// Same as [apply] except it takes [PostProcessBuilderFactory]s.
///
/// Does not provide options for `isOptional` or `hideOutput` because they
/// aren't configurable for these types of builders. They are never optional and
/// always hidden.
BuilderApplication applyPostProcess(
String builderKey, PostProcessBuilderFactory builderFactory,
{InputSet defaultGenerateFor,
BuilderOptions defaultOptions,
BuilderOptions defaultDevOptions,
BuilderOptions defaultReleaseOptions}) =>
BuilderApplication.forPostProcessBuilder(
builderKey,
builderFactory,
defaultGenerateFor: defaultGenerateFor,
defaultOptions: defaultOptions,
defaultDevOptions: defaultDevOptions,
defaultReleaseOptions: defaultReleaseOptions,
);
/// A description of which packages need a given [Builder] or
/// [PostProcessBuilder] applied.
class BuilderApplication {
/// Factories that create [BuildPhase]s for all [Builder]s or
/// [PostProcessBuilder]s that should be applied.
final List<BuildPhaseFactory> buildPhaseFactories;
/// Determines whether a given package needs builder applied.
final PackageFilter filter;
/// Builder keys which, when applied to a target, will also apply this Builder
/// even if [filter] does not match.
final Iterable<String> appliesBuilders;
/// A uniqe key for this builder.
///
/// Ignored when null or empty.
final String builderKey;
/// Whether genereated assets should be placed in the build cache.
final bool hideOutput;
const BuilderApplication._(
this.builderKey,
this.buildPhaseFactories,
this.filter,
this.hideOutput,
Iterable<String> appliesBuilders,
) : appliesBuilders = appliesBuilders ?? const [];
factory BuilderApplication.forBuilder(
String builderKey,
List<BuilderFactory> builderFactories,
PackageFilter filter, {
bool isOptional,
bool hideOutput,
InputSet defaultGenerateFor,
BuilderOptions defaultOptions,
BuilderOptions defaultDevOptions,
BuilderOptions defaultReleaseOptions,
Iterable<String> appliesBuilders,
}) {
hideOutput ??= true;
var phaseFactories = builderFactories.map((builderFactory) {
return (PackageNode package, BuilderOptions options,
InputSet targetSources, InputSet generateFor, bool isReleaseBuild) {
generateFor ??= defaultGenerateFor;
var optionsWithDefaults = (defaultOptions ?? BuilderOptions.empty)
.overrideWith(
isReleaseBuild ? defaultReleaseOptions : defaultDevOptions)
.overrideWith(options);
if (package.isRoot) {
optionsWithDefaults =
optionsWithDefaults.overrideWith(BuilderOptions.forRoot);
}
final logger = Logger(builderKey);
final builder =
_scopeLogSync(() => builderFactory(optionsWithDefaults), logger);
if (builder == null) {
logger.severe(_factoryFailure(package.name, optionsWithDefaults));
throw CannotBuildException();
}
return InBuildPhase(builder, package.name,
builderKey: builderKey,
targetSources: targetSources,
generateFor: generateFor,
builderOptions: optionsWithDefaults,
hideOutput: hideOutput,
isOptional: isOptional);
};
}).toList();
return BuilderApplication._(
builderKey, phaseFactories, filter, hideOutput, appliesBuilders);
}
/// Note that these builder applications each create their own phase, but they
/// will all eventually be merged into a single phase.
factory BuilderApplication.forPostProcessBuilder(
String builderKey,
PostProcessBuilderFactory builderFactory, {
InputSet defaultGenerateFor,
BuilderOptions defaultOptions,
BuilderOptions defaultDevOptions,
BuilderOptions defaultReleaseOptions,
}) {
var phaseFactory = (PackageNode package, BuilderOptions options,
InputSet targetSources, InputSet generateFor, bool isReleaseBuild) {
generateFor ??= defaultGenerateFor;
var optionsWithDefaults = (defaultOptions ?? BuilderOptions.empty)
.overrideWith(
isReleaseBuild ? defaultReleaseOptions : defaultDevOptions)
.overrideWith(options);
if (package.isRoot) {
optionsWithDefaults =
optionsWithDefaults.overrideWith(BuilderOptions.forRoot);
}
final logger = Logger(builderKey);
final builder =
_scopeLogSync(() => builderFactory(optionsWithDefaults), logger);
if (builder == null) {
logger.severe(_factoryFailure(package.name, optionsWithDefaults));
throw CannotBuildException();
}
var builderAction = PostBuildAction(builder, package.name,
builderOptions: optionsWithDefaults,
generateFor: generateFor,
targetSources: targetSources);
return PostBuildPhase([builderAction]);
};
return BuilderApplication._(
builderKey, [phaseFactory], toNoneByDefault(), true, []);
}
}
final _logger = Logger('ApplyBuilders');
/// Creates a [BuildPhase] to apply each builder in [builderApplications] to
/// each target in [targetGraph] such that all builders are run for dependencies
/// before moving on to later packages.
///
/// When there is a package cycle the builders are applied to each packages
/// within the cycle before moving on to packages that depend on any package
/// within the cycle.
///
/// Builders may be filtered, for instance to run only on package which have a
/// dependency on some other package by choosing the appropriate
/// [BuilderApplication].
Future<List<BuildPhase>> createBuildPhases(
TargetGraph targetGraph,
Iterable<BuilderApplication> builderApplications,
Map<String, Map<String, dynamic>> builderConfigOverrides,
bool isReleaseMode) async {
validateBuilderConfig(builderApplications, targetGraph.rootPackageConfig,
builderConfigOverrides, _logger);
final globalOptions = targetGraph.rootPackageConfig.globalOptions.map(
(key, config) => MapEntry(
key,
_options(config?.options).overrideWith(isReleaseMode
? _options(config?.releaseOptions)
: _options(config?.devOptions))));
for (final key in builderConfigOverrides.keys) {
final overrides = BuilderOptions(builderConfigOverrides[key]);
globalOptions[key] =
(globalOptions[key] ?? BuilderOptions.empty).overrideWith(overrides);
}
final cycles = stronglyConnectedComponents<TargetNode>(
targetGraph.allModules.values,
(node) => node.target.dependencies?.map((key) {
if (!targetGraph.allModules.containsKey(key)) {
_logger.severe('${node.target.key} declares a dependency on $key '
'but it does not exist');
throw CannotBuildException();
}
return targetGraph.allModules[key];
})?.where((n) => n != null),
equals: (a, b) => a.target.key == b.target.key,
hashCode: (node) => node.target.key.hashCode);
final applyWith = _applyWith(builderApplications);
final allBuilders = Map<String, BuilderApplication>.fromIterable(
builderApplications,
key: (b) => (b as BuilderApplication).builderKey);
final expandedPhases = cycles
.expand((cycle) => _createBuildPhasesWithinCycle(
cycle,
builderApplications,
globalOptions,
applyWith,
allBuilders,
isReleaseMode))
.toList();
final inBuildPhases = expandedPhases.whereType<InBuildPhase>();
final postBuildPhases = expandedPhases.whereType<PostBuildPhase>().toList();
final collapsedPostBuildPhase = <PostBuildPhase>[];
if (postBuildPhases.isNotEmpty) {
collapsedPostBuildPhase.add(postBuildPhases
.fold<PostBuildPhase>(PostBuildPhase([]), (previous, next) {
previous.builderActions.addAll(next.builderActions);
return previous;
}));
}
return <BuildPhase>[...inBuildPhases, ...collapsedPostBuildPhase];
}
Iterable<BuildPhase> _createBuildPhasesWithinCycle(
Iterable<TargetNode> cycle,
Iterable<BuilderApplication> builderApplications,
Map<String, BuilderOptions> globalOptions,
Map<String, List<BuilderApplication>> applyWith,
Map<String, BuilderApplication> allBuilders,
bool isReleaseMode) =>
builderApplications.expand((builderApplication) =>
_createBuildPhasesForBuilderInCycle(
cycle,
builderApplication,
globalOptions[builderApplication.builderKey] ??
BuilderOptions.empty,
applyWith,
allBuilders,
isReleaseMode));
Iterable<BuildPhase> _createBuildPhasesForBuilderInCycle(
Iterable<TargetNode> cycle,
BuilderApplication builderApplication,
BuilderOptions globalOptionOverrides,
Map<String, List<BuilderApplication>> applyWith,
Map<String, BuilderApplication> allBuilders,
bool isReleaseMode) {
TargetBuilderConfig targetConfig(TargetNode node) =>
node.target.builders[builderApplication.builderKey];
return builderApplication.buildPhaseFactories.expand((createPhase) => cycle
.where((targetNode) => _shouldApply(
builderApplication, targetNode, applyWith, allBuilders))
.map((node) {
final builderConfig = targetConfig(node);
final options = _options(builderConfig?.options)
.overrideWith(isReleaseMode
? _options(builderConfig?.releaseOptions)
: _options(builderConfig?.devOptions))
.overrideWith(globalOptionOverrides);
return createPhase(node.package, options, node.target.sources,
builderConfig?.generateFor, isReleaseMode);
}));
}
bool _shouldApply(
BuilderApplication builderApplication,
TargetNode node,
Map<String, List<BuilderApplication>> applyWith,
Map<String, BuilderApplication> allBuilders) {
if (!(builderApplication.hideOutput &&
builderApplication.appliesBuilders
.every((b) => allBuilders[b]?.hideOutput ?? true)) &&
!node.package.isRoot) {
return false;
}
final builderConfig = node.target.builders[builderApplication.builderKey];
if (builderConfig?.isEnabled != null) {
return builderConfig.isEnabled;
}
final shouldAutoApply =
node.target.autoApplyBuilders && builderApplication.filter(node.package);
return shouldAutoApply ||
(applyWith[builderApplication.builderKey] ?? const []).any(
(anchorBuilder) =>
_shouldApply(anchorBuilder, node, applyWith, allBuilders));
}
/// Inverts the dependency map from 'applies builders' to 'applied with
/// builders'.
Map<String, List<BuilderApplication>> _applyWith(
Iterable<BuilderApplication> builderApplications) {
final applyWith = <String, List<BuilderApplication>>{};
for (final builderApplication in builderApplications) {
for (final alsoApply in builderApplication.appliesBuilders) {
applyWith.putIfAbsent(alsoApply, () => []).add(builderApplication);
}
}
return applyWith;
}
/// Runs [fn] in an error handling [Zone].
///
/// Any calls to [print] will be logged with `log.info`, and any errors will be
/// logged with `log.severe`.
T _scopeLogSync<T>(T Function() fn, Logger log) {
return runZoned(fn,
zoneSpecification:
ZoneSpecification(print: (self, parent, zone, message) {
log.info(message);
}),
zoneValues: {logKey: log},
onError: (Object e, StackTrace s) {
log.severe('', e, s);
});
}
String _factoryFailure(String packageName, BuilderOptions options) =>
'Failed to instantiate builder for $packageName with configuration:\n'
'${JsonEncoder.withIndent(' ').convert(options.config)}';
BuilderOptions _options(Map<String, dynamic> options) =>
options?.isEmpty ?? true ? BuilderOptions.empty : BuilderOptions(options);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_runner_core/src/package_graph/target_graph.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:glob/glob.dart';
import '../generate/input_matcher.dart';
import 'package_graph.dart';
/// Like a [PackageGraph] but packages are further broken down into modules
/// based on build config.
class TargetGraph {
/// All [TargetNode]s indexed by `"$packageName:$targetName"`.
final Map<String, TargetNode> allModules;
/// All [TargetNode]s by package name.
final Map<String, List<TargetNode>> modulesByPackage;
/// The [BuildConfig] of the root package.
final BuildConfig rootPackageConfig;
TargetGraph._(this.allModules, this.modulesByPackage, this.rootPackageConfig);
/// Builds a [TargetGraph] from [packageGraph].
///
/// The [overrideBuildConfig] map overrides the config for packages by name.
///
/// The [defaultRootPackageWhitelist] is the default `sources` list to use
/// for targets in the root package.
///
/// All [requiredSourcePaths] should appear in non-root packages. A warning
/// is logged if this condition is not met.
///
/// All [requiredRootSourcePaths] should appear in the root package. A
/// warning is logged if this condition is not met.
static Future<TargetGraph> forPackageGraph(PackageGraph packageGraph,
{Map<String, BuildConfig> overrideBuildConfig,
List<String> defaultRootPackageWhitelist,
List<String> requiredSourcePaths,
List<String> requiredRootSourcePaths}) async {
requiredSourcePaths ??= const [];
requiredRootSourcePaths ??= const [];
overrideBuildConfig ??= const {};
final modulesByKey = <String, TargetNode>{};
final modulesByPackage = <String, List<TargetNode>>{};
BuildConfig rootPackageConfig;
for (final package in packageGraph.allPackages.values) {
final config = overrideBuildConfig[package.name] ??
await _packageBuildConfig(package);
List<String> defaultInclude;
if (package.isRoot) {
defaultInclude = defaultRootPackageWhitelist;
rootPackageConfig = config;
} else if (package.name == r'$sdk') {
defaultInclude = const [
'lib/dev_compiler/**.js',
'lib/_internal/**.sum',
];
} else {
defaultInclude = const ['lib/**'];
}
final nodes = config.buildTargets.values.map((target) =>
TargetNode(target, package, defaultInclude: defaultInclude));
if (package.name != r'$sdk') {
var requiredPackagePaths =
package.isRoot ? requiredRootSourcePaths : requiredSourcePaths;
var requiredIds =
requiredPackagePaths.map((path) => AssetId(package.name, path));
var missing = _missingSources(nodes, requiredIds);
if (missing.isNotEmpty) {
log.warning(
'The package `${package.name}` does not include some required '
'sources in any of its targets (see their build.yaml file).\n'
'The missing sources are:\n'
'${missing.map((s) => ' - ${s.path}').join('\n')}');
}
}
for (final node in nodes) {
modulesByKey[node.target.key] = node;
modulesByPackage.putIfAbsent(node.target.package, () => []).add(node);
}
}
return TargetGraph._(modulesByKey, modulesByPackage, rootPackageConfig);
}
/// Whether or not [id] is included in the sources of any target in the graph.
bool anyMatchesAsset(AssetId id) =>
modulesByPackage[id.package]?.any((t) => t.matchesSource(id)) ?? false;
}
class TargetNode {
final BuildTarget target;
final PackageNode package;
List<Glob> get sourceIncludes => _sourcesMatcher.includeGlobs;
final InputMatcher _sourcesMatcher;
TargetNode(this.target, this.package, {List<String> defaultInclude})
: _sourcesMatcher =
InputMatcher(target.sources, defaultInclude: defaultInclude);
bool excludesSource(AssetId id) => _sourcesMatcher.excludes(id);
bool matchesSource(AssetId id) => _sourcesMatcher.matches(id);
@override
String toString() => target.key;
}
Future<BuildConfig> _packageBuildConfig(PackageNode package) async {
final dependencyNames = package.dependencies.map((n) => n.name);
if (package.path == null) {
return BuildConfig.useDefault(package.name, dependencyNames);
}
try {
return await BuildConfig.fromBuildConfigDir(
package.name, dependencyNames, package.path);
} on ArgumentError catch (e) {
throw BuildConfigParseException(package.name, e);
}
}
class BuildConfigParseException implements Exception {
final String packageName;
final dynamic exception;
BuildConfigParseException(this.packageName, this.exception);
}
/// Returns the [sources] are not included in any [targets].
Iterable<AssetId> _missingSources(
Iterable<TargetNode> targets, Iterable<AssetId> sources) =>
sources.where((s) => !targets.any((t) => t.matchesSource(s)));
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/build_config.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
export 'src/build_config.dart' show BuildConfig;
export 'src/build_target.dart'
show BuildTarget, TargetBuilderConfig, GlobalBuilderConfig;
export 'src/builder_definition.dart'
show
BuilderDefinition,
AutoApply,
BuildTo,
PostProcessBuilderDefinition,
TargetBuilderConfigDefaults;
export 'src/common.dart' show runInBuildConfigZone;
export 'src/input_set.dart' show InputSet;
export 'src/key_normalization.dart'
show normalizeBuilderKeyUsage, normalizeTargetKeyUsage;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/builder_definition.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'builder_definition.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BuilderDefinition _$BuilderDefinitionFromJson(Map json) {
return $checkedNew('BuilderDefinition', json, () {
$checkKeys(json, allowedKeys: const [
'builder_factories',
'import',
'build_extensions',
'target',
'auto_apply',
'required_inputs',
'runs_before',
'applies_builders',
'is_optional',
'build_to',
'defaults'
], requiredKeys: const [
'builder_factories',
'import',
'build_extensions'
], disallowNullValues: const [
'builder_factories',
'import',
'build_extensions'
]);
final val = BuilderDefinition(
builderFactories: $checkedConvert(json, 'builder_factories',
(v) => (v as List).map((e) => e as String).toList()),
buildExtensions: $checkedConvert(
json,
'build_extensions',
(v) => (v as Map).map(
(k, e) => MapEntry(
k as String, (e as List).map((e) => e as String).toList()),
)),
import: $checkedConvert(json, 'import', (v) => v as String),
target: $checkedConvert(json, 'target', (v) => v as String),
autoApply: $checkedConvert(json, 'auto_apply',
(v) => _$enumDecodeNullable(_$AutoApplyEnumMap, v)),
requiredInputs: $checkedConvert(
json, 'required_inputs', (v) => (v as List)?.map((e) => e as String)),
runsBefore: $checkedConvert(
json, 'runs_before', (v) => (v as List)?.map((e) => e as String)),
appliesBuilders: $checkedConvert(json, 'applies_builders',
(v) => (v as List)?.map((e) => e as String)),
isOptional: $checkedConvert(json, 'is_optional', (v) => v as bool),
buildTo: $checkedConvert(
json, 'build_to', (v) => _$enumDecodeNullable(_$BuildToEnumMap, v)),
defaults: $checkedConvert(
json,
'defaults',
(v) => v == null
? null
: TargetBuilderConfigDefaults.fromJson(v as Map)),
);
return val;
}, fieldKeyMap: const {
'builderFactories': 'builder_factories',
'buildExtensions': 'build_extensions',
'autoApply': 'auto_apply',
'requiredInputs': 'required_inputs',
'runsBefore': 'runs_before',
'appliesBuilders': 'applies_builders',
'isOptional': 'is_optional',
'buildTo': 'build_to'
});
}
T _$enumDecode<T>(
Map<T, dynamic> enumValues,
dynamic source, {
T unknownValue,
}) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
final value = enumValues.entries
.singleWhere((e) => e.value == source, orElse: () => null)
?.key;
if (value == null && unknownValue == null) {
throw ArgumentError('`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}');
}
return value ?? unknownValue;
}
T _$enumDecodeNullable<T>(
Map<T, dynamic> enumValues,
dynamic source, {
T unknownValue,
}) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue);
}
const _$AutoApplyEnumMap = {
AutoApply.none: 'none',
AutoApply.dependents: 'dependents',
AutoApply.allPackages: 'all_packages',
AutoApply.rootPackage: 'root_package',
};
const _$BuildToEnumMap = {
BuildTo.source: 'source',
BuildTo.cache: 'cache',
};
PostProcessBuilderDefinition _$PostProcessBuilderDefinitionFromJson(Map json) {
return $checkedNew('PostProcessBuilderDefinition', json, () {
$checkKeys(json, allowedKeys: const [
'builder_factory',
'import',
'input_extensions',
'target',
'defaults'
], requiredKeys: const [
'builder_factory',
'import'
], disallowNullValues: const [
'builder_factory',
'import'
]);
final val = PostProcessBuilderDefinition(
builderFactory:
$checkedConvert(json, 'builder_factory', (v) => v as String),
import: $checkedConvert(json, 'import', (v) => v as String),
inputExtensions: $checkedConvert(json, 'input_extensions',
(v) => (v as List)?.map((e) => e as String)),
target: $checkedConvert(json, 'target', (v) => v as String),
defaults: $checkedConvert(
json,
'defaults',
(v) => v == null
? null
: TargetBuilderConfigDefaults.fromJson(v as Map)),
);
return val;
}, fieldKeyMap: const {
'builderFactory': 'builder_factory',
'inputExtensions': 'input_extensions'
});
}
TargetBuilderConfigDefaults _$TargetBuilderConfigDefaultsFromJson(Map json) {
return $checkedNew('TargetBuilderConfigDefaults', json, () {
$checkKeys(json, allowedKeys: const [
'generate_for',
'options',
'dev_options',
'release_options'
]);
final val = TargetBuilderConfigDefaults(
generateFor: $checkedConvert(
json, 'generate_for', (v) => v == null ? null : InputSet.fromJson(v)),
options: $checkedConvert(
json,
'options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
devOptions: $checkedConvert(
json,
'dev_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
releaseOptions: $checkedConvert(
json,
'release_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
);
return val;
}, fieldKeyMap: const {
'generateFor': 'generate_for',
'devOptions': 'dev_options',
'releaseOptions': 'release_options'
});
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/build_target.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
import 'builder_definition.dart';
import 'common.dart';
import 'expandos.dart';
import 'input_set.dart';
import 'key_normalization.dart';
part 'build_target.g.dart';
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class BuildTarget {
@JsonKey(name: 'auto_apply_builders')
final bool autoApplyBuilders;
/// A map from builder key to the configuration used for this target.
///
/// Builder keys are in the format `"$package|$builder"`. This does not
/// represent the full set of builders that are applied to the target, only
/// those which have configuration customized against the default.
final Map<String, TargetBuilderConfig> builders;
final List<String> dependencies;
final InputSet sources;
/// A unique key for this target in `'$package:$target'` format.
String get key => builderKeyExpando[this];
String get package => packageExpando[this];
BuildTarget({
bool autoApplyBuilders,
InputSet sources,
Iterable<String> dependencies,
Map<String, TargetBuilderConfig> builders,
}) : autoApplyBuilders = autoApplyBuilders ?? true,
dependencies = (dependencies ?? currentPackageDefaultDependencies)
.map((d) => normalizeTargetKeyUsage(d, currentPackage))
.toList(),
builders = (builders ?? const {}).map((key, config) =>
MapEntry(normalizeBuilderKeyUsage(key, currentPackage), config)),
sources = sources ?? InputSet.anything;
factory BuildTarget.fromJson(Map json) => _$BuildTargetFromJson(json);
@override
String toString() => {
'package': package,
'sources': sources,
'dependencies': dependencies,
'builders': builders,
'autoApplyBuilders': autoApplyBuilders,
}.toString();
}
/// The configuration a particular [BuildTarget] applies to a Builder.
///
/// Build targets may have builders applied automatically based on
/// [BuilderDefinition.autoApply] and may override with more specific
/// configuration.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class TargetBuilderConfig {
/// Overrides the setting of whether the Builder would run on this target.
///
/// Builders may run on this target by default based on the `apply_to`
/// argument, set to `false` to disable a Builder which would otherwise run.
///
/// By default including a config for a Builder enables that builder.
@JsonKey(name: 'enabled')
final bool isEnabled;
/// Sources to use as inputs for this Builder in glob format.
///
/// This is always a subset of the `include` argument in the containing
/// [BuildTarget]. May be `null` in which cases it will be all the sources in
/// the target.
@JsonKey(name: 'generate_for')
final InputSet generateFor;
/// The options to pass to the `BuilderFactory` when constructing this
/// builder.
///
/// The `options` key in the configuration.
///
/// Individual keys may be overridden by either [devOptions] or
/// [releaseOptions].
final Map<String, dynamic> options;
/// Overrides for [options] in dev mode.
@JsonKey(name: 'dev_options')
final Map<String, dynamic> devOptions;
/// Overrides for [options] in release mode.
@JsonKey(name: 'release_options')
final Map<String, dynamic> releaseOptions;
TargetBuilderConfig({
bool isEnabled,
this.generateFor,
Map<String, dynamic> options,
Map<String, dynamic> devOptions,
Map<String, dynamic> releaseOptions,
}) : isEnabled = isEnabled ?? true,
options = options ?? const {},
devOptions = devOptions ?? const {},
releaseOptions = releaseOptions ?? const {};
factory TargetBuilderConfig.fromJson(Map json) =>
_$TargetBuilderConfigFromJson(json);
@override
String toString() => {
'isEnabled': isEnabled,
'generateFor': generateFor,
'options': options,
'devOptions': devOptions,
'releaseOptions': releaseOptions,
}.toString();
}
/// The configuration for a Builder applied globally.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class GlobalBuilderConfig {
/// The options to pass to the `BuilderFactory` when constructing this
/// builder.
///
/// The `options` key in the configuration.
///
/// Individual keys may be overridden by either [devOptions] or
/// [releaseOptions].
final Map<String, dynamic> options;
/// Overrides for [options] in dev mode.
@JsonKey(name: 'dev_options')
final Map<String, dynamic> devOptions;
/// Overrides for [options] in release mode.
@JsonKey(name: 'release_options')
final Map<String, dynamic> releaseOptions;
GlobalBuilderConfig({
Map<String, dynamic> options,
Map<String, dynamic> devOptions,
Map<String, dynamic> releaseOptions,
}) : options = options ?? const {},
devOptions = devOptions ?? const {},
releaseOptions = releaseOptions ?? const {};
factory GlobalBuilderConfig.fromJson(Map json) =>
_$GlobalBuilderConfigFromJson(json);
@override
String toString() => {
'options': options,
'devOptions': devOptions,
'releaseOptions': releaseOptions,
}.toString();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/key_normalization.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
const _defaultTargetNamePlaceholder = r'$default';
/// Returns the normalized [builderKey] definition when used from [packageName].
///
/// Example normalizations:
///
/// - "some_builder" => "$packageName:some_builder"
/// - ":some_builder" => "$packageName:some_builder"
/// - "some_package:some_builder" => "some_package:some_builder"
///
/// If the legacy separator `|` is used it will be transformed to `:`
String normalizeBuilderKeyDefinition(String builderKey, String packageName) =>
_normalizeDefinition(
builderKey.contains('|')
? builderKey.replaceFirst('|', ':')
: builderKey,
packageName);
/// Returns the normalized [builderKey] usage when used from [packageName].
///
/// Example normalizations:
///
/// - "some_package" => "some_package:some_package"
/// - ":some_builder" => "$packageName:some_builder"
/// - "some_package:some_builder" => "some_package:some_builder"
///
/// If the legacy separator `|` is used it will be transformed to `:`
String normalizeBuilderKeyUsage(String builderKey, String packageName) =>
_normalizeUsage(
builderKey.contains('|')
? builderKey.replaceFirst('|', ':')
: builderKey,
packageName);
/// Returns the normalized [targetKey] definition when used from [packageName].
///
/// Example normalizations:
///
/// - "$default" => "$packageName:$packageName"
/// - "some_target" => "$packageName:some_target"
/// - ":some_target" => "$packageName:some_target"
/// - "some_package:some_target" => "some_package|some_target"
String normalizeTargetKeyDefinition(String targetKey, String packageName) =>
targetKey == _defaultTargetNamePlaceholder
? '$packageName:$packageName'
: _normalizeDefinition(targetKey, packageName);
/// Returns the normalized [targetKey] usage when used from [packageName].
///
/// Example normalizations:
///
/// - "$default" => "$packageName:$packageName"
/// - ":$default" => "$packageName:$packageName"
/// - "$default:$default" => "$packageName:$packageName"
/// - "some_package" => "some_package:some_package"
/// - ":some_target" => "$packageName:some_target"
/// - "some_package:some_target" => "some_package:some_target"
String normalizeTargetKeyUsage(String targetKey, String packageName) {
switch (targetKey) {
case _defaultTargetNamePlaceholder:
case ':$_defaultTargetNamePlaceholder':
case '$_defaultTargetNamePlaceholder:$_defaultTargetNamePlaceholder':
return '$packageName:$packageName';
default:
return _normalizeUsage(targetKey, packageName);
}
}
/// Gives a full unique key for [name] used from [packageName].
///
/// If [name] omits the separator we assume it's referring to a target or
/// builder named after a package (which is not this package). If [name] starts
/// with the separator we assume it's referring to a target within the package
/// it's used from.
///
/// For example: If I depend on `angular` from `my_package` it is treated as a
/// dependency on the globally unique `angular:angular`.
String _normalizeUsage(String name, String packageName) {
if (name.startsWith(':')) return '$packageName$name';
if (!name.contains(':')) return '$name:$name';
return name;
}
/// Gives a full unique key for [name] definied within [packageName].
///
/// The result is always '$packageName$separator$name since at definition the
/// key must be referring to something within [packageName].
///
/// For example: If I expose a builder `my_builder` within `my_package` it is
/// turned into the globally unique `my_package|my_builder`.
String _normalizeDefinition(String name, String packageName) {
if (name.startsWith(':')) return '$packageName$name';
if (!name.contains(':')) return '$packageName:$name';
return name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/common.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
final _defaultDependenciesZoneKey = Symbol('buildConfigDefaultDependencies');
final _packageZoneKey = Symbol('buildConfigPackage');
T runInBuildConfigZone<T>(
T Function() fn, String package, List<String> defaultDependencies) =>
runZoned(fn, zoneValues: {
_packageZoneKey: package,
_defaultDependenciesZoneKey: defaultDependencies,
});
String get currentPackage {
var package = Zone.current[_packageZoneKey] as String;
if (package == null) {
throw StateError(
'Must be running inside a build config zone, which can be done using '
'the `runInBuildConfigZone` function.');
}
return package;
}
List<String> get currentPackageDefaultDependencies {
var defaultDependencies =
Zone.current[_defaultDependenciesZoneKey] as List<String>;
if (defaultDependencies == null) {
throw StateError(
'Must be running inside a build config zone, which can be done using '
'the `runInBuildConfigZone` function.');
}
return defaultDependencies;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/build_config.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:checked_yaml/checked_yaml.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'package:pubspec_parse/pubspec_parse.dart';
import 'build_target.dart';
import 'builder_definition.dart';
import 'common.dart';
import 'expandos.dart';
import 'input_set.dart';
import 'key_normalization.dart';
part 'build_config.g.dart';
/// The parsed values from a `build.yaml` file.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class BuildConfig {
/// Returns a parsed [BuildConfig] file in [path], if one exist, otherwise a
/// default config.
///
/// [path] must be a directory which contains a `pubspec.yaml` file and
/// optionally a `build.yaml`.
static Future<BuildConfig> fromPackageDir(String path) async {
final pubspec = await _fromPackageDir(path);
return fromBuildConfigDir(pubspec.name, pubspec.dependencies.keys, path);
}
/// Returns a parsed [BuildConfig] file in [path], if one exists, otherwise a
/// default config.
///
/// [path] should the path to a directory which may contain a `build.yaml`.
static Future<BuildConfig> fromBuildConfigDir(
String packageName, Iterable<String> dependencies, String path) async {
final configPath = p.join(path, 'build.yaml');
final file = File(configPath);
if (await file.exists()) {
return BuildConfig.parse(
packageName,
dependencies,
await file.readAsString(),
configYamlPath: file.path,
);
} else {
return BuildConfig.useDefault(packageName, dependencies);
}
}
@JsonKey(ignore: true)
final String packageName;
/// All the `builders` defined in a `build.yaml` file.
@JsonKey(name: 'builders')
final Map<String, BuilderDefinition> builderDefinitions;
/// All the `post_process_builders` defined in a `build.yaml` file.
@JsonKey(name: 'post_process_builders')
final Map<String, PostProcessBuilderDefinition> postProcessBuilderDefinitions;
/// All the `targets` defined in a `build.yaml` file.
@JsonKey(name: 'targets', fromJson: _buildTargetsFromJson)
final Map<String, BuildTarget> buildTargets;
@JsonKey(name: 'global_options')
final Map<String, GlobalBuilderConfig> globalOptions;
/// The default config if you have no `build.yaml` file.
factory BuildConfig.useDefault(
String packageName, Iterable<String> dependencies) {
return runInBuildConfigZone(() {
final key = '$packageName:$packageName';
final target = BuildTarget(
dependencies: dependencies
.map((dep) => normalizeTargetKeyUsage(dep, packageName))
.toList(),
sources: InputSet.anything,
);
return BuildConfig(
packageName: packageName,
buildTargets: {key: target},
globalOptions: {},
);
}, packageName, dependencies.toList());
}
/// Create a [BuildConfig] by parsing [configYaml].
///
/// If [configYamlPath] is passed, it's used as the URL from which
/// [configYaml] for error reporting.
factory BuildConfig.parse(
String packageName,
Iterable<String> dependencies,
String configYaml, {
String configYamlPath,
}) {
try {
return checkedYamlDecode(
configYaml,
(map) =>
BuildConfig.fromMap(packageName, dependencies, map ?? const {}),
allowNull: true,
sourceUrl: configYamlPath,
);
} on ParsedYamlException catch (e) {
throw ArgumentError(e.formattedMessage);
}
}
/// Create a [BuildConfig] read a map which was already parsed.
factory BuildConfig.fromMap(
String packageName, Iterable<String> dependencies, Map config) {
return runInBuildConfigZone(() => BuildConfig._fromJson(config),
packageName, dependencies.toList());
}
BuildConfig({
String packageName,
@required Map<String, BuildTarget> buildTargets,
Map<String, GlobalBuilderConfig> globalOptions,
Map<String, BuilderDefinition> builderDefinitions,
Map<String, PostProcessBuilderDefinition> postProcessBuilderDefinitions =
const {},
}) : buildTargets = buildTargets ??
{
_defaultTarget(packageName ?? currentPackage): BuildTarget(
dependencies: currentPackageDefaultDependencies,
)
},
globalOptions = (globalOptions ?? const {}).map((key, config) =>
MapEntry(normalizeBuilderKeyUsage(key, currentPackage), config)),
builderDefinitions = _normalizeBuilderDefinitions(
builderDefinitions ?? const {}, packageName ?? currentPackage),
postProcessBuilderDefinitions = _normalizeBuilderDefinitions(
postProcessBuilderDefinitions ?? const {},
packageName ?? currentPackage),
packageName = packageName ?? currentPackage {
// Set up the expandos for all our build targets and definitions so they
// can know which package and builder key they refer to.
this.buildTargets.forEach((key, target) {
packageExpando[target] = this.packageName;
builderKeyExpando[target] = key;
});
this.builderDefinitions.forEach((key, definition) {
packageExpando[definition] = this.packageName;
builderKeyExpando[definition] = key;
});
this.postProcessBuilderDefinitions.forEach((key, definition) {
packageExpando[definition] = this.packageName;
builderKeyExpando[definition] = key;
});
}
factory BuildConfig._fromJson(Map json) => _$BuildConfigFromJson(json);
}
String _defaultTarget(String package) => '$package:$package';
Map<String, T> _normalizeBuilderDefinitions<T>(
Map<String, T> builderDefinitions, String packageName) =>
builderDefinitions.map((key, definition) =>
MapEntry(normalizeBuilderKeyDefinition(key, packageName), definition));
Map<String, BuildTarget> _buildTargetsFromJson(Map json) {
if (json == null) {
return null;
}
var targets = json.map((key, target) => MapEntry(
normalizeTargetKeyDefinition(key as String, currentPackage),
BuildTarget.fromJson(target as Map)));
if (!targets.containsKey(_defaultTarget(currentPackage))) {
throw ArgumentError('Must specify a target with the name '
'`$currentPackage` or `\$default`.');
}
return targets;
}
Future<Pubspec> _fromPackageDir(String path) async {
final pubspec = p.join(path, 'pubspec.yaml');
final file = File(pubspec);
if (await file.exists()) {
return Pubspec.parse(await file.readAsString());
}
throw FileSystemException('No file found', p.absolute(pubspec));
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/builder_definition.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'build_target.dart';
import 'common.dart';
import 'expandos.dart';
import 'input_set.dart';
import 'key_normalization.dart';
part 'builder_definition.g.dart';
enum AutoApply {
none,
dependents,
@JsonValue('all_packages')
allPackages,
@JsonValue('root_package')
rootPackage
}
enum BuildTo {
/// Generated files are written to the source directory next to their primary
/// inputs.
source,
/// Generated files are written to the hidden 'generated' directory.
cache
}
/// Definition of a builder parsed from the `builders` section of `build.yaml`.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class BuilderDefinition {
/// The package which provides this Builder.
String get package => packageExpando[this];
/// A unique key for this Builder in `'$package:$builder'` format.
String get key => builderKeyExpando[this];
/// The names of the top-level methods in [import] from args -> Builder.
@JsonKey(
name: 'builder_factories',
nullable: false,
required: true,
disallowNullValue: true)
final List<String> builderFactories;
/// The import to be used to load `clazz`.
@JsonKey(nullable: false, required: true, disallowNullValue: true)
final String import;
/// A map from input extension to the output extensions created for matching
/// inputs.
@JsonKey(
name: 'build_extensions',
nullable: false,
required: true,
disallowNullValue: true)
final Map<String, List<String>> buildExtensions;
/// The name of the dart_library target that contains `import`.
///
/// May be null or unreliable and should not be used.
@deprecated
final String target;
/// Which packages should have this builder applied automatically.
@JsonKey(name: 'auto_apply')
final AutoApply autoApply;
/// A list of file extensions which are required to run this builder.
///
/// No builder which outputs any extension in this list is allowed to run
/// after this builder.
@JsonKey(name: 'required_inputs')
final List<String> requiredInputs;
/// Builder keys in `$package:$builder` format which should only be run after
/// this Builder.
@JsonKey(name: 'runs_before')
final List<String> runsBefore;
/// Builder keys in `$package:$builder` format which should be run on any
/// target which also runs this Builder.
@JsonKey(name: 'applies_builders')
final List<String> appliesBuilders;
/// Whether this Builder should be deferred until it's output is requested.
///
/// Optional builders are lazy and will not run unless some later builder
/// requests one of it's possible outputs through either `readAs*` or
/// `canRead`.
@JsonKey(name: 'is_optional')
final bool isOptional;
/// Where the outputs of this builder should be written.
@JsonKey(name: 'build_to')
final BuildTo buildTo;
final TargetBuilderConfigDefaults defaults;
BuilderDefinition({
@required this.builderFactories,
@required this.buildExtensions,
@required this.import,
String target,
AutoApply autoApply,
Iterable<String> requiredInputs,
Iterable<String> runsBefore,
Iterable<String> appliesBuilders,
bool isOptional,
BuildTo buildTo,
TargetBuilderConfigDefaults defaults,
}) :
// ignore: deprecated_member_use
target = target != null
? normalizeTargetKeyUsage(target, currentPackage)
: null,
autoApply = autoApply ?? AutoApply.none,
requiredInputs = requiredInputs?.toList() ?? const [],
runsBefore = runsBefore
?.map((builder) =>
normalizeBuilderKeyUsage(builder, currentPackage))
?.toList() ??
const [],
appliesBuilders = appliesBuilders
?.map((builder) =>
normalizeBuilderKeyUsage(builder, currentPackage))
?.toList() ??
const [],
isOptional = isOptional ?? false,
buildTo = buildTo ?? BuildTo.cache,
defaults = defaults ?? const TargetBuilderConfigDefaults() {
if (builderFactories.isEmpty) {
throw ArgumentError.value(builderFactories, 'builderFactories',
'Must have at least one value.');
}
if (buildExtensions.entries.any((e) => e.value.contains(e.key))) {
throw ArgumentError.value(
buildExtensions,
'buildExtensions',
'May not overwrite an input, '
'the output extensions must not contain the input extension');
}
}
factory BuilderDefinition.fromJson(Map json) =>
_$BuilderDefinitionFromJson(json);
@override
String toString() => {
'autoApply': autoApply,
'import': import,
'builderFactories': builderFactories,
'buildExtensions': buildExtensions,
'requiredInputs': requiredInputs,
'runsBefore': runsBefore,
'isOptional': isOptional,
'buildTo': buildTo,
'defaults': defaults,
}.toString();
}
/// The definition of a `PostProcessBuilder` in the `post_process_builders`
/// section of a `build.yaml`.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class PostProcessBuilderDefinition {
/// The package which provides this Builder.
String get package => packageExpando[this];
/// A unique key for this Builder in `'$package:$builder'` format.
String get key => builderKeyExpando[this];
/// The name of the top-level method in [import] from
/// Map<String, dynamic> -> Builder.
@JsonKey(
name: 'builder_factory',
nullable: false,
required: true,
disallowNullValue: true)
final String builderFactory;
/// The import to be used to load `clazz`.
@JsonKey(nullable: false, required: true, disallowNullValue: true)
final String import;
/// A list of input extensions for this builder.
///
/// May be null or unreliable and should not be used.
@deprecated
@JsonKey(name: 'input_extensions')
final Iterable<String> inputExtensions;
/// The name of the dart_library target that contains `import`.
///
/// May be null or unreliable and should not be used.
@deprecated
final String target;
final TargetBuilderConfigDefaults defaults;
PostProcessBuilderDefinition({
@required this.builderFactory,
@required this.import,
this.inputExtensions,
this.target,
TargetBuilderConfigDefaults defaults,
}) : defaults = defaults ?? const TargetBuilderConfigDefaults();
factory PostProcessBuilderDefinition.fromJson(Map json) =>
_$PostProcessBuilderDefinitionFromJson(json);
@override
String toString() => {
'import': import,
'builderFactory': builderFactory,
'defaults': defaults,
}.toString();
}
/// Default values that builder authors can specify when users don't fill in the
/// corresponding key for [TargetBuilderConfig].
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class TargetBuilderConfigDefaults {
@JsonKey(name: 'generate_for')
final InputSet generateFor;
final Map<String, dynamic> options;
@JsonKey(name: 'dev_options')
final Map<String, dynamic> devOptions;
@JsonKey(name: 'release_options')
final Map<String, dynamic> releaseOptions;
const TargetBuilderConfigDefaults({
InputSet generateFor,
Map<String, dynamic> options,
Map<String, dynamic> devOptions,
Map<String, dynamic> releaseOptions,
}) : generateFor = generateFor ?? InputSet.anything,
options = options ?? const {},
devOptions = devOptions ?? const {},
releaseOptions = releaseOptions ?? const {};
factory TargetBuilderConfigDefaults.fromJson(Map json) =>
_$TargetBuilderConfigDefaultsFromJson(json);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/input_set.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
part 'input_set.g.dart';
/// A filter on files inputs or sources.
///
/// Takes a list of strings in glob format for [include] and [exclude]. Matches
/// the `glob()` function in skylark.
@JsonSerializable(createToJson: false, disallowUnrecognizedKeys: true)
class InputSet {
static const anything = InputSet();
/// The globs to include in the set.
///
/// May be null or empty which means every possible path (like `'**'`).
final List<String> include;
/// The globs as a subset of [include] to remove from the set.
///
/// May be null or empty which means every path in [include].
final List<String> exclude;
const InputSet({this.include, this.exclude});
factory InputSet.fromJson(dynamic json) {
if (json is List) {
json = {'include': json};
} else if (json is! Map) {
throw ArgumentError.value(json, 'sources',
'Expected a Map or a List but got a ${json.runtimeType}');
}
final parsed = _$InputSetFromJson(json as Map);
if (parsed.include != null &&
parsed.include.any((s) => s == null || s.isEmpty)) {
throw ArgumentError.value(
parsed.include, 'include', 'Include globs must not be empty');
}
if (parsed.exclude != null &&
parsed.exclude.any((s) => s == null || s.isEmpty)) {
throw ArgumentError.value(
parsed.exclude, 'exclude', 'Exclude globs must not be empty');
}
return parsed;
}
@override
String toString() {
final result = StringBuffer();
if (include == null || include.isEmpty) {
result.write('any path');
} else {
result.write('paths matching $include');
}
if (exclude != null && exclude.isNotEmpty) {
result.write(' except $exclude');
}
return '$result';
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/build_config.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'build_config.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BuildConfig _$BuildConfigFromJson(Map json) {
return $checkedNew('BuildConfig', json, () {
$checkKeys(json, allowedKeys: const [
'builders',
'post_process_builders',
'targets',
'global_options'
]);
final val = BuildConfig(
buildTargets: $checkedConvert(
json, 'targets', (v) => _buildTargetsFromJson(v as Map)),
globalOptions: $checkedConvert(
json,
'global_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String,
e == null ? null : GlobalBuilderConfig.fromJson(e as Map)),
)),
builderDefinitions: $checkedConvert(
json,
'builders',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String,
e == null ? null : BuilderDefinition.fromJson(e as Map)),
)),
postProcessBuilderDefinitions: $checkedConvert(
json,
'post_process_builders',
(v) => (v as Map)?.map(
(k, e) => MapEntry(
k as String,
e == null
? null
: PostProcessBuilderDefinition.fromJson(e as Map)),
)),
);
return val;
}, fieldKeyMap: const {
'buildTargets': 'targets',
'globalOptions': 'global_options',
'builderDefinitions': 'builders',
'postProcessBuilderDefinitions': 'post_process_builders'
});
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/build_target.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'build_target.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BuildTarget _$BuildTargetFromJson(Map json) {
return $checkedNew('BuildTarget', json, () {
$checkKeys(json, allowedKeys: const [
'auto_apply_builders',
'builders',
'dependencies',
'sources'
]);
final val = BuildTarget(
autoApplyBuilders:
$checkedConvert(json, 'auto_apply_builders', (v) => v as bool),
sources: $checkedConvert(
json, 'sources', (v) => v == null ? null : InputSet.fromJson(v)),
dependencies: $checkedConvert(
json, 'dependencies', (v) => (v as List)?.map((e) => e as String)),
builders: $checkedConvert(
json,
'builders',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String,
e == null ? null : TargetBuilderConfig.fromJson(e as Map)),
)),
);
return val;
}, fieldKeyMap: const {'autoApplyBuilders': 'auto_apply_builders'});
}
TargetBuilderConfig _$TargetBuilderConfigFromJson(Map json) {
return $checkedNew('TargetBuilderConfig', json, () {
$checkKeys(json, allowedKeys: const [
'enabled',
'generate_for',
'options',
'dev_options',
'release_options'
]);
final val = TargetBuilderConfig(
isEnabled: $checkedConvert(json, 'enabled', (v) => v as bool),
generateFor: $checkedConvert(
json, 'generate_for', (v) => v == null ? null : InputSet.fromJson(v)),
options: $checkedConvert(
json,
'options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
devOptions: $checkedConvert(
json,
'dev_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
releaseOptions: $checkedConvert(
json,
'release_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
);
return val;
}, fieldKeyMap: const {
'isEnabled': 'enabled',
'generateFor': 'generate_for',
'devOptions': 'dev_options',
'releaseOptions': 'release_options'
});
}
GlobalBuilderConfig _$GlobalBuilderConfigFromJson(Map json) {
return $checkedNew('GlobalBuilderConfig', json, () {
$checkKeys(json,
allowedKeys: const ['options', 'dev_options', 'release_options']);
final val = GlobalBuilderConfig(
options: $checkedConvert(
json,
'options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
devOptions: $checkedConvert(
json,
'dev_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
releaseOptions: $checkedConvert(
json,
'release_options',
(v) => (v as Map)?.map(
(k, e) => MapEntry(k as String, e),
)),
);
return val;
}, fieldKeyMap: const {
'devOptions': 'dev_options',
'releaseOptions': 'release_options'
});
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/expandos.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
final builderKeyExpando = Expando<String>();
final packageExpando = Expando<String>();
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_config/src/input_set.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'input_set.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
InputSet _$InputSetFromJson(Map json) {
return $checkedNew('InputSet', json, () {
$checkKeys(json, allowedKeys: const ['include', 'exclude']);
final val = InputSet(
include: $checkedConvert(json, 'include',
(v) => (v as List)?.map((e) => e as String)?.toList()),
exclude: $checkedConvert(json, 'exclude',
(v) => (v as List)?.map((e) => e as String)?.toList()),
);
return val;
});
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/pub_semver.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
export 'src/version.dart';
export 'src/version_constraint.dart';
export 'src/version_range.dart' hide CompatibleWithVersionRange;
export 'src/version_union.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/version_constraint.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'patterns.dart';
import 'utils.dart';
import 'version.dart';
import 'version_range.dart';
import 'version_union.dart';
/// A [VersionConstraint] is a predicate that can determine whether a given
/// version is valid or not.
///
/// For example, a ">= 2.0.0" constraint allows any version that is "2.0.0" or
/// greater. Version objects themselves implement this to match a specific
/// version.
abstract class VersionConstraint {
/// A [VersionConstraint] that allows all versions.
static VersionConstraint any = VersionRange();
/// A [VersionConstraint] that allows no versions -- the empty set.
static VersionConstraint empty = const _EmptyVersion();
/// Parses a version constraint.
///
/// This string is one of:
///
/// * "any". [any] version.
/// * "^" followed by a version string. Versions compatible with
/// ([VersionConstraint.compatibleWith]) the version.
/// * a series of version parts. Each part can be one of:
/// * A version string like `1.2.3`. In other words, anything that can be
/// parsed by [Version.parse()].
/// * A comparison operator (`<`, `>`, `<=`, or `>=`) followed by a
/// version string.
///
/// Whitespace is ignored.
///
/// Examples:
///
/// any
/// ^0.7.2
/// ^1.0.0-alpha
/// 1.2.3-alpha
/// <=5.1.4
/// >2.0.4 <= 2.4.6
factory VersionConstraint.parse(String text) {
var originalText = text;
void skipWhitespace() {
text = text.trim();
}
skipWhitespace();
// Handle the "any" constraint.
if (text == 'any') return any;
// Try to parse and consume a version number.
Version matchVersion() {
var version = startVersion.firstMatch(text);
if (version == null) return null;
text = text.substring(version.end);
return Version.parse(version[0]);
}
// Try to parse and consume a comparison operator followed by a version.
VersionRange matchComparison() {
var comparison = startComparison.firstMatch(text);
if (comparison == null) return null;
var op = comparison[0];
text = text.substring(comparison.end);
skipWhitespace();
var version = matchVersion();
if (version == null) {
throw FormatException('Expected version number after "$op" in '
'"$originalText", got "$text".');
}
switch (op) {
case '<=':
return VersionRange(max: version, includeMax: true);
case '<':
return VersionRange(
max: version,
includeMax: false,
alwaysIncludeMaxPreRelease: true);
case '>=':
return VersionRange(min: version, includeMin: true);
case '>':
return VersionRange(min: version, includeMin: false);
}
throw FallThroughError();
}
// Try to parse the "^" operator followed by a version.
VersionConstraint matchCompatibleWith() {
if (!text.startsWith(compatibleWithChar)) return null;
text = text.substring(compatibleWithChar.length);
skipWhitespace();
var version = matchVersion();
if (version == null) {
throw FormatException('Expected version number after '
'"$compatibleWithChar" in "$originalText", got "$text".');
}
if (text.isNotEmpty) {
throw FormatException('Cannot include other constraints with '
'"$compatibleWithChar" constraint in "$originalText".');
}
return VersionConstraint.compatibleWith(version);
}
var compatibleWith = matchCompatibleWith();
if (compatibleWith != null) return compatibleWith;
Version min;
var includeMin = false;
Version max;
var includeMax = false;
for (;;) {
skipWhitespace();
if (text.isEmpty) break;
var newRange = matchVersion() ?? matchComparison();
if (newRange == null) {
throw FormatException('Could not parse version "$originalText". '
'Unknown text at "$text".');
}
if (newRange.min != null) {
if (min == null || newRange.min > min) {
min = newRange.min;
includeMin = newRange.includeMin;
} else if (newRange.min == min && !newRange.includeMin) {
includeMin = false;
}
}
if (newRange.max != null) {
if (max == null || newRange.max < max) {
max = newRange.max;
includeMax = newRange.includeMax;
} else if (newRange.max == max && !newRange.includeMax) {
includeMax = false;
}
}
}
if (min == null && max == null) {
throw const FormatException('Cannot parse an empty string.');
}
if (min != null && max != null) {
if (min > max) return VersionConstraint.empty;
if (min == max) {
if (includeMin && includeMax) return min;
return VersionConstraint.empty;
}
}
return VersionRange(
min: min, includeMin: includeMin, max: max, includeMax: includeMax);
}
/// Creates a version constraint which allows all versions that are
/// backward compatible with [version].
///
/// Versions are considered backward compatible with [version] if they
/// are greater than or equal to [version], but less than the next breaking
/// version ([Version.nextBreaking]) of [version].
factory VersionConstraint.compatibleWith(Version version) =>
CompatibleWithVersionRange(version);
/// Creates a new version constraint that is the intersection of
/// [constraints].
///
/// It only allows versions that all of those constraints allow. If
/// constraints is empty, then it returns a VersionConstraint that allows
/// all versions.
factory VersionConstraint.intersection(
Iterable<VersionConstraint> constraints) {
var constraint = VersionRange();
for (var other in constraints) {
constraint = constraint.intersect(other) as VersionRange;
}
return constraint;
}
/// Creates a new version constraint that is the union of [constraints].
///
/// It allows any versions that any of those constraints allows. If
/// [constraints] is empty, this returns a constraint that allows no versions.
factory VersionConstraint.unionOf(Iterable<VersionConstraint> constraints) {
var flattened = constraints.expand((constraint) {
if (constraint.isEmpty) return <VersionRange>[];
if (constraint is VersionUnion) return constraint.ranges;
if (constraint is VersionRange) return [constraint];
throw ArgumentError('Unknown VersionConstraint type $constraint.');
}).toList();
if (flattened.isEmpty) return VersionConstraint.empty;
if (flattened.any((constraint) => constraint.isAny)) {
return VersionConstraint.any;
}
flattened.sort();
var merged = <VersionRange>[];
for (var constraint in flattened) {
// Merge this constraint with the previous one, but only if they touch.
if (merged.isEmpty ||
(!merged.last.allowsAny(constraint) &&
!areAdjacent(merged.last, constraint))) {
merged.add(constraint);
} else {
merged[merged.length - 1] =
merged.last.union(constraint) as VersionRange;
}
}
if (merged.length == 1) return merged.single;
return VersionUnion.fromRanges(merged);
}
/// Returns `true` if this constraint allows no versions.
bool get isEmpty;
/// Returns `true` if this constraint allows all versions.
bool get isAny;
/// Returns `true` if this constraint allows [version].
bool allows(Version version);
/// Returns `true` if this constraint allows all the versions that [other]
/// allows.
bool allowsAll(VersionConstraint other);
/// Returns `true` if this constraint allows any of the versions that [other]
/// allows.
bool allowsAny(VersionConstraint other);
/// Returns a [VersionConstraint] that only allows [Version]s allowed by both
/// this and [other].
VersionConstraint intersect(VersionConstraint other);
/// Returns a [VersionConstraint] that allows [Version]s allowed by either
/// this or [other].
VersionConstraint union(VersionConstraint other);
/// Returns a [VersionConstraint] that allows [Version]s allowed by this but
/// not [other].
VersionConstraint difference(VersionConstraint other);
}
class _EmptyVersion implements VersionConstraint {
const _EmptyVersion();
@override
bool get isEmpty => true;
@override
bool get isAny => false;
@override
bool allows(Version other) => false;
@override
bool allowsAll(VersionConstraint other) => other.isEmpty;
@override
bool allowsAny(VersionConstraint other) => false;
@override
VersionConstraint intersect(VersionConstraint other) => this;
@override
VersionConstraint union(VersionConstraint other) => other;
@override
VersionConstraint difference(VersionConstraint other) => this;
@override
String toString() => '<empty>';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/utils.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'version.dart';
import 'version_range.dart';
/// Returns whether [range1] is immediately next to, but not overlapping,
/// [range2].
bool areAdjacent(VersionRange range1, VersionRange range2) {
if (range1.max != range2.min) return false;
return (range1.includeMax && !range2.includeMin) ||
(!range1.includeMax && range2.includeMin);
}
/// Returns whether [range1] allows lower versions than [range2].
bool allowsLower(VersionRange range1, VersionRange range2) {
if (range1.min == null) return range2.min != null;
if (range2.min == null) return false;
var comparison = range1.min.compareTo(range2.min);
if (comparison == -1) return true;
if (comparison == 1) return false;
return range1.includeMin && !range2.includeMin;
}
/// Returns whether [range1] allows higher versions than [range2].
bool allowsHigher(VersionRange range1, VersionRange range2) {
if (range1.max == null) return range2.max != null;
if (range2.max == null) return false;
var comparison = range1.max.compareTo(range2.max);
if (comparison == 1) return true;
if (comparison == -1) return false;
return range1.includeMax && !range2.includeMax;
}
/// Returns whether [range1] allows only versions lower than those allowed by
/// [range2].
bool strictlyLower(VersionRange range1, VersionRange range2) {
if (range1.max == null || range2.min == null) return false;
var comparison = range1.max.compareTo(range2.min);
if (comparison == -1) return true;
if (comparison == 1) return false;
return !range1.includeMax || !range2.includeMin;
}
/// Returns whether [range1] allows only versions higher than those allowed by
/// [range2].
bool strictlyHigher(VersionRange range1, VersionRange range2) =>
strictlyLower(range2, range1);
bool equalsWithoutPreRelease(Version version1, Version version2) =>
version1.major == version2.major &&
version1.minor == version2.minor &&
version1.patch == version2.patch;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/patterns.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Regex that matches a version number at the beginning of a string.
final startVersion = RegExp(r'^' // Start at beginning.
r'(\d+).(\d+).(\d+)' // Version number.
r'(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?' // Pre-release.
r'(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?'); // Build.
/// Like [startVersion] but matches the entire string.
final completeVersion = RegExp('${startVersion.pattern}\$');
/// Parses a comparison operator ("<", ">", "<=", or ">=") at the beginning of
/// a string.
final startComparison = RegExp(r'^[<>]=?');
/// The "compatible with" operator.
const compatibleWithChar = '^';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/version_union.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:collection/collection.dart';
import 'utils.dart';
import 'version.dart';
import 'version_constraint.dart';
import 'version_range.dart';
/// A version constraint representing a union of multiple disjoint version
/// ranges.
///
/// An instance of this will only be created if the version can't be represented
/// as a non-compound value.
class VersionUnion implements VersionConstraint {
/// The constraints that compose this union.
///
/// This list has two invariants:
///
/// * Its contents are sorted using the standard ordering of [VersionRange]s.
/// * Its contents are disjoint and non-adjacent. In other words, for any two
/// constraints next to each other in the list, there's some version between
/// those constraints that they don't match.
final List<VersionRange> ranges;
@override
bool get isEmpty => false;
@override
bool get isAny => false;
/// Creates a union from a list of ranges with no pre-processing.
///
/// It's up to the caller to ensure that the invariants described in [ranges]
/// are maintained. They are not verified by this constructor. To
/// automatically ensure that they're maintained, use [new
/// VersionConstraint.unionOf] instead.
VersionUnion.fromRanges(this.ranges);
@override
bool allows(Version version) =>
ranges.any((constraint) => constraint.allows(version));
@override
bool allowsAll(VersionConstraint other) {
var ourRanges = ranges.iterator;
var theirRanges = _rangesFor(other).iterator;
// Because both lists of ranges are ordered by minimum version, we can
// safely move through them linearly here.
ourRanges.moveNext();
theirRanges.moveNext();
while (ourRanges.current != null && theirRanges.current != null) {
if (ourRanges.current.allowsAll(theirRanges.current)) {
theirRanges.moveNext();
} else {
ourRanges.moveNext();
}
}
// If our ranges have allowed all of their ranges, we'll have consumed all
// of them.
return theirRanges.current == null;
}
@override
bool allowsAny(VersionConstraint other) {
var ourRanges = ranges.iterator;
var theirRanges = _rangesFor(other).iterator;
// Because both lists of ranges are ordered by minimum version, we can
// safely move through them linearly here.
ourRanges.moveNext();
theirRanges.moveNext();
while (ourRanges.current != null && theirRanges.current != null) {
if (ourRanges.current.allowsAny(theirRanges.current)) {
return true;
}
// Move the constraint with the lower max value forward. This ensures that
// we keep both lists in sync as much as possible.
if (allowsHigher(theirRanges.current, ourRanges.current)) {
ourRanges.moveNext();
} else {
theirRanges.moveNext();
}
}
return false;
}
@override
VersionConstraint intersect(VersionConstraint other) {
var ourRanges = ranges.iterator;
var theirRanges = _rangesFor(other).iterator;
// Because both lists of ranges are ordered by minimum version, we can
// safely move through them linearly here.
var newRanges = <VersionRange>[];
ourRanges.moveNext();
theirRanges.moveNext();
while (ourRanges.current != null && theirRanges.current != null) {
var intersection = ourRanges.current.intersect(theirRanges.current);
if (!intersection.isEmpty) newRanges.add(intersection as VersionRange);
// Move the constraint with the lower max value forward. This ensures that
// we keep both lists in sync as much as possible, and that large ranges
// have a chance to match multiple small ranges that they contain.
if (allowsHigher(theirRanges.current, ourRanges.current)) {
ourRanges.moveNext();
} else {
theirRanges.moveNext();
}
}
if (newRanges.isEmpty) return VersionConstraint.empty;
if (newRanges.length == 1) return newRanges.single;
return VersionUnion.fromRanges(newRanges);
}
@override
VersionConstraint difference(VersionConstraint other) {
var ourRanges = ranges.iterator;
var theirRanges = _rangesFor(other).iterator;
var newRanges = <VersionRange>[];
ourRanges.moveNext();
theirRanges.moveNext();
var current = ourRanges.current;
bool theirNextRange() {
if (theirRanges.moveNext()) return true;
// If there are no more of their ranges, none of the rest of our ranges
// need to be subtracted so we can add them as-is.
newRanges.add(current);
while (ourRanges.moveNext()) {
newRanges.add(ourRanges.current);
}
return false;
}
bool ourNextRange({bool includeCurrent = true}) {
if (includeCurrent) newRanges.add(current);
if (!ourRanges.moveNext()) return false;
current = ourRanges.current;
return true;
}
for (;;) {
// If the current ranges are disjoint, move the lowest one forward.
if (strictlyLower(theirRanges.current, current)) {
if (!theirNextRange()) break;
continue;
}
if (strictlyHigher(theirRanges.current, current)) {
if (!ourNextRange()) break;
continue;
}
// If we're here, we know [theirRanges.current] overlaps [current].
var difference = current.difference(theirRanges.current);
if (difference is VersionUnion) {
// If their range split [current] in half, we only need to continue
// checking future ranges against the latter half.
assert(difference.ranges.length == 2);
newRanges.add(difference.ranges.first);
current = difference.ranges.last;
// Since their range split [current], it definitely doesn't allow higher
// versions, so we should move their ranges forward.
if (!theirNextRange()) break;
} else if (difference.isEmpty) {
if (!ourNextRange(includeCurrent: false)) break;
} else {
current = difference as VersionRange;
// Move the constraint with the lower max value forward. This ensures
// that we keep both lists in sync as much as possible, and that large
// ranges have a chance to subtract or be subtracted by multiple small
// ranges that they contain.
if (allowsHigher(current, theirRanges.current)) {
if (!theirNextRange()) break;
} else {
if (!ourNextRange()) break;
}
}
}
if (newRanges.isEmpty) return VersionConstraint.empty;
if (newRanges.length == 1) return newRanges.single;
return VersionUnion.fromRanges(newRanges);
}
/// Returns [constraint] as a list of ranges.
///
/// This is used to normalize ranges of various types.
List<VersionRange> _rangesFor(VersionConstraint constraint) {
if (constraint.isEmpty) return [];
if (constraint is VersionUnion) return constraint.ranges;
if (constraint is VersionRange) return [constraint];
throw ArgumentError('Unknown VersionConstraint type $constraint.');
}
@override
VersionConstraint union(VersionConstraint other) =>
VersionConstraint.unionOf([this, other]);
@override
bool operator ==(Object other) =>
other is VersionUnion &&
const ListEquality().equals(ranges, other.ranges);
@override
int get hashCode => const ListEquality().hash(ranges);
@override
String toString() => ranges.join(' or ');
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/version_range.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'utils.dart';
import 'version.dart';
import 'version_constraint.dart';
import 'version_union.dart';
/// Constrains versions to a fall within a given range.
///
/// If there is a minimum, then this only allows versions that are at that
/// minimum or greater. If there is a maximum, then only versions less than
/// that are allowed. In other words, this allows `>= min, < max`.
///
/// Version ranges are ordered first by their lower bounds, then by their upper
/// bounds. For example, `>=1.0.0 <2.0.0` is before `>=1.5.0 <2.0.0` is before
/// `>=1.5.0 <3.0.0`.
class VersionRange implements Comparable<VersionRange>, VersionConstraint {
/// The minimum end of the range.
///
/// If [includeMin] is `true`, this will be the minimum allowed version.
/// Otherwise, it will be the highest version below the range that is not
/// allowed.
///
/// This may be `null` in which case the range has no minimum end and allows
/// any version less than the maximum.
final Version min;
/// The maximum end of the range.
///
/// If [includeMax] is `true`, this will be the maximum allowed version.
/// Otherwise, it will be the lowest version above the range that is not
/// allowed.
///
/// This may be `null` in which case the range has no maximum end and allows
/// any version greater than the minimum.
final Version max;
/// If `true` then [min] is allowed by the range.
final bool includeMin;
/// If `true`, then [max] is allowed by the range.
final bool includeMax;
/// Creates a new version range from [min] to [max], either inclusive or
/// exclusive.
///
/// If it is an error if [min] is greater than [max].
///
/// Either [max] or [min] may be omitted to not clamp the range at that end.
/// If both are omitted, the range allows all versions.
///
/// If [includeMin] is `true`, then the minimum end of the range is inclusive.
/// Likewise, passing [includeMax] as `true` makes the upper end inclusive.
///
/// If [alwaysIncludeMaxPreRelease] is `true`, this will always include
/// pre-release versions of an exclusive [max]. Otherwise, it will use the
/// default behavior for pre-release versions of [max].
factory VersionRange(
{Version min,
Version max,
bool includeMin = false,
bool includeMax = false,
bool alwaysIncludeMaxPreRelease = false}) {
if (min != null && max != null && min > max) {
throw ArgumentError(
'Minimum version ("$min") must be less than maximum ("$max").');
}
if (!alwaysIncludeMaxPreRelease &&
!includeMax &&
max != null &&
!max.isPreRelease &&
max.build.isEmpty &&
(min == null ||
!min.isPreRelease ||
!equalsWithoutPreRelease(min, max))) {
max = max.firstPreRelease;
}
return VersionRange._(min, max, includeMin, includeMax);
}
VersionRange._(this.min, this.max, this.includeMin, this.includeMax);
@override
bool operator ==(other) {
if (other is! VersionRange) return false;
return min == other.min &&
max == other.max &&
includeMin == other.includeMin &&
includeMax == other.includeMax;
}
@override
int get hashCode =>
min.hashCode ^
(max.hashCode * 3) ^
(includeMin.hashCode * 5) ^
(includeMax.hashCode * 7);
@override
bool get isEmpty => false;
@override
bool get isAny => min == null && max == null;
/// Tests if [other] falls within this version range.
@override
bool allows(Version other) {
if (min != null) {
if (other < min) return false;
if (!includeMin && other == min) return false;
}
if (max != null) {
if (other > max) return false;
if (!includeMax && other == max) return false;
}
return true;
}
@override
bool allowsAll(VersionConstraint other) {
if (other.isEmpty) return true;
if (other is Version) return allows(other);
if (other is VersionUnion) {
return other.ranges.every(allowsAll);
}
if (other is VersionRange) {
return !allowsLower(other, this) && !allowsHigher(other, this);
}
throw ArgumentError('Unknown VersionConstraint type $other.');
}
@override
bool allowsAny(VersionConstraint other) {
if (other.isEmpty) return false;
if (other is Version) return allows(other);
if (other is VersionUnion) {
return other.ranges.any(allowsAny);
}
if (other is VersionRange) {
return !strictlyLower(other, this) && !strictlyHigher(other, this);
}
throw ArgumentError('Unknown VersionConstraint type $other.');
}
@override
VersionConstraint intersect(VersionConstraint other) {
if (other.isEmpty) return other;
if (other is VersionUnion) return other.intersect(this);
// A range and a Version just yields the version if it's in the range.
if (other is Version) {
return allows(other) ? other : VersionConstraint.empty;
}
if (other is VersionRange) {
// Intersect the two ranges.
Version intersectMin;
bool intersectIncludeMin;
if (allowsLower(this, other)) {
if (strictlyLower(this, other)) return VersionConstraint.empty;
intersectMin = other.min;
intersectIncludeMin = other.includeMin;
} else {
if (strictlyLower(other, this)) return VersionConstraint.empty;
intersectMin = min;
intersectIncludeMin = includeMin;
}
Version intersectMax;
bool intersectIncludeMax;
if (allowsHigher(this, other)) {
intersectMax = other.max;
intersectIncludeMax = other.includeMax;
} else {
intersectMax = max;
intersectIncludeMax = includeMax;
}
if (intersectMin == null && intersectMax == null) {
// Open range.
return VersionRange();
}
// If the range is just a single version.
if (intersectMin == intersectMax) {
// Because we already verified that the lower range isn't strictly
// lower, there must be some overlap.
assert(intersectIncludeMin && intersectIncludeMax);
return intersectMin;
}
// If we got here, there is an actual range.
return VersionRange(
min: intersectMin,
max: intersectMax,
includeMin: intersectIncludeMin,
includeMax: intersectIncludeMax,
alwaysIncludeMaxPreRelease: true);
}
throw ArgumentError('Unknown VersionConstraint type $other.');
}
@override
VersionConstraint union(VersionConstraint other) {
if (other is Version) {
if (allows(other)) return this;
if (other == min) {
return VersionRange(
min: min,
max: max,
includeMin: true,
includeMax: includeMax,
alwaysIncludeMaxPreRelease: true);
}
if (other == max) {
return VersionRange(
min: min,
max: max,
includeMin: includeMin,
includeMax: true,
alwaysIncludeMaxPreRelease: true);
}
return VersionConstraint.unionOf([this, other]);
}
if (other is VersionRange) {
// If the two ranges don't overlap, we won't be able to create a single
// VersionRange for both of them.
var edgesTouch = (max != null &&
max == other.min &&
(includeMax || other.includeMin)) ||
(min != null && min == other.max && (includeMin || other.includeMax));
if (!edgesTouch && !allowsAny(other)) {
return VersionConstraint.unionOf([this, other]);
}
Version unionMin;
bool unionIncludeMin;
if (allowsLower(this, other)) {
unionMin = min;
unionIncludeMin = includeMin;
} else {
unionMin = other.min;
unionIncludeMin = other.includeMin;
}
Version unionMax;
bool unionIncludeMax;
if (allowsHigher(this, other)) {
unionMax = max;
unionIncludeMax = includeMax;
} else {
unionMax = other.max;
unionIncludeMax = other.includeMax;
}
return VersionRange(
min: unionMin,
max: unionMax,
includeMin: unionIncludeMin,
includeMax: unionIncludeMax,
alwaysIncludeMaxPreRelease: true);
}
return VersionConstraint.unionOf([this, other]);
}
@override
VersionConstraint difference(VersionConstraint other) {
if (other.isEmpty) return this;
if (other is Version) {
if (!allows(other)) return this;
if (other == min) {
if (!includeMin) return this;
return VersionRange(
min: min,
max: max,
includeMin: false,
includeMax: includeMax,
alwaysIncludeMaxPreRelease: true);
}
if (other == max) {
if (!includeMax) return this;
return VersionRange(
min: min,
max: max,
includeMin: includeMin,
includeMax: false,
alwaysIncludeMaxPreRelease: true);
}
return VersionUnion.fromRanges([
VersionRange(
min: min,
max: other,
includeMin: includeMin,
includeMax: false,
alwaysIncludeMaxPreRelease: true),
VersionRange(
min: other,
max: max,
includeMin: false,
includeMax: includeMax,
alwaysIncludeMaxPreRelease: true)
]);
} else if (other is VersionRange) {
if (!allowsAny(other)) return this;
VersionRange before;
if (!allowsLower(this, other)) {
before = null;
} else if (min == other.min) {
assert(includeMin && !other.includeMin);
assert(min != null);
before = min;
} else {
before = VersionRange(
min: min,
max: other.min,
includeMin: includeMin,
includeMax: !other.includeMin,
alwaysIncludeMaxPreRelease: true);
}
VersionRange after;
if (!allowsHigher(this, other)) {
after = null;
} else if (max == other.max) {
assert(includeMax && !other.includeMax);
assert(max != null);
after = max;
} else {
after = VersionRange(
min: other.max,
max: max,
includeMin: !other.includeMax,
includeMax: includeMax,
alwaysIncludeMaxPreRelease: true);
}
if (before == null && after == null) return VersionConstraint.empty;
if (before == null) return after;
if (after == null) return before;
return VersionUnion.fromRanges([before, after]);
} else if (other is VersionUnion) {
var ranges = <VersionRange>[];
var current = this;
for (var range in other.ranges) {
// Skip any ranges that are strictly lower than [current].
if (strictlyLower(range, current)) continue;
// If we reach a range strictly higher than [current], no more ranges
// will be relevant so we can bail early.
if (strictlyHigher(range, current)) break;
var difference = current.difference(range);
if (difference.isEmpty) {
return VersionConstraint.empty;
} else if (difference is VersionUnion) {
// If [range] split [current] in half, we only need to continue
// checking future ranges against the latter half.
assert(difference.ranges.length == 2);
ranges.add(difference.ranges.first);
current = difference.ranges.last;
} else {
current = difference as VersionRange;
}
}
if (ranges.isEmpty) return current;
return VersionUnion.fromRanges(ranges..add(current));
}
throw ArgumentError('Unknown VersionConstraint type $other.');
}
@override
int compareTo(VersionRange other) {
if (min == null) {
if (other.min == null) return _compareMax(other);
return -1;
} else if (other.min == null) {
return 1;
}
var result = min.compareTo(other.min);
if (result != 0) return result;
if (includeMin != other.includeMin) return includeMin ? -1 : 1;
return _compareMax(other);
}
/// Compares the maximum values of `this` and [other].
int _compareMax(VersionRange other) {
if (max == null) {
if (other.max == null) return 0;
return 1;
} else if (other.max == null) {
return -1;
}
var result = max.compareTo(other.max);
if (result != 0) return result;
if (includeMax != other.includeMax) return includeMax ? 1 : -1;
return 0;
}
@override
String toString() {
var buffer = StringBuffer();
if (min != null) {
buffer..write(includeMin ? '>=' : '>')..write(min);
}
if (max != null) {
if (min != null) buffer.write(' ');
if (includeMax) {
buffer..write('<=')..write(max);
} else {
buffer.write('<');
if (max.isFirstPreRelease) {
// Since `"<$max"` would parse the same as `"<$max-0"`, we just emit
// `<$max` to avoid confusing "-0" suffixes.
buffer.write('${max.major}.${max.minor}.${max.patch}');
} else {
buffer.write(max);
// If `">=$min <$max"` would parse as `">=$min <$max-0"`, add `-*` to
// indicate that actually does allow pre-release versions.
var minIsPreReleaseOfMax = min != null &&
min.isPreRelease &&
equalsWithoutPreRelease(min, max);
if (!max.isPreRelease && max.build.isEmpty && !minIsPreReleaseOfMax) {
buffer.write('-∞');
}
}
}
}
if (min == null && max == null) buffer.write('any');
return buffer.toString();
}
}
class CompatibleWithVersionRange extends VersionRange {
CompatibleWithVersionRange(Version version)
: super._(version, version.nextBreaking.firstPreRelease, true, false);
@override
String toString() => '^$min';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pub_semver/src/version.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'patterns.dart';
import 'version_constraint.dart';
import 'version_range.dart';
/// The equality operator to use for comparing version components.
final _equality = const IterableEquality();
/// A parsed semantic version number.
class Version implements VersionConstraint, VersionRange {
/// No released version: i.e. "0.0.0".
static Version get none => Version(0, 0, 0);
/// Compares [a] and [b] to see which takes priority over the other.
///
/// Returns `1` if [a] takes priority over [b] and `-1` if vice versa. If
/// [a] and [b] are equivalent, returns `0`.
///
/// Unlike [compareTo], which *orders* versions, this determines which
/// version a user is likely to prefer. In particular, it prioritizes
/// pre-release versions lower than stable versions, regardless of their
/// version numbers. Pub uses this when determining which version to prefer
/// when a number of versions are allowed. In that case, it will always
/// choose a stable version when possible.
///
/// When used to sort a list, orders in ascending priority so that the
/// highest priority version is *last* in the result.
static int prioritize(Version a, Version b) {
// Sort all prerelease versions after all normal versions. This way
// the solver will prefer stable packages over unstable ones.
if (a.isPreRelease && !b.isPreRelease) return -1;
if (!a.isPreRelease && b.isPreRelease) return 1;
return a.compareTo(b);
}
/// Like [prioritize], but lower version numbers are considered greater than
/// higher version numbers.
///
/// This still considers prerelease versions to be lower than non-prerelease
/// versions. Pub uses this when downgrading -- it chooses the lowest version
/// but still excludes pre-release versions when possible.
static int antiprioritize(Version a, Version b) {
if (a.isPreRelease && !b.isPreRelease) return -1;
if (!a.isPreRelease && b.isPreRelease) return 1;
return b.compareTo(a);
}
/// The major version number: "1" in "1.2.3".
final int major;
/// The minor version number: "2" in "1.2.3".
final int minor;
/// The patch version number: "3" in "1.2.3".
final int patch;
/// The pre-release identifier: "foo" in "1.2.3-foo".
///
/// This is split into a list of components, each of which may be either a
/// string or a non-negative integer. It may also be empty, indicating that
/// this version has no pre-release identifier.
final List preRelease;
/// The build identifier: "foo" in "1.2.3+foo".
///
/// This is split into a list of components, each of which may be either a
/// string or a non-negative integer. It may also be empty, indicating that
/// this version has no build identifier.
final List build;
/// The original string representation of the version number.
///
/// This preserves textual artifacts like leading zeros that may be left out
/// of the parsed version.
final String _text;
@override
Version get min => this;
@override
Version get max => this;
@override
bool get includeMin => true;
@override
bool get includeMax => true;
Version._(this.major, this.minor, this.patch, String preRelease, String build,
this._text)
: preRelease = preRelease == null ? [] : _splitParts(preRelease),
build = build == null ? [] : _splitParts(build) {
if (major < 0) throw ArgumentError('Major version must be non-negative.');
if (minor < 0) throw ArgumentError('Minor version must be non-negative.');
if (patch < 0) throw ArgumentError('Patch version must be non-negative.');
}
/// Creates a new [Version] object.
factory Version(int major, int minor, int patch, {String pre, String build}) {
var text = '$major.$minor.$patch';
if (pre != null) text += '-$pre';
if (build != null) text += '+$build';
return Version._(major, minor, patch, pre, build, text);
}
/// Creates a new [Version] by parsing [text].
factory Version.parse(String text) {
final match = completeVersion.firstMatch(text);
if (match == null) {
throw FormatException('Could not parse "$text".');
}
try {
var major = int.parse(match[1]);
var minor = int.parse(match[2]);
var patch = int.parse(match[3]);
var preRelease = match[5];
var build = match[8];
return Version._(major, minor, patch, preRelease, build, text);
} on FormatException {
throw FormatException('Could not parse "$text".');
}
}
/// Returns the primary version out of a list of candidates.
///
/// This is the highest-numbered stable (non-prerelease) version. If there
/// are no stable versions, it's just the highest-numbered version.
static Version primary(List<Version> versions) {
Version primary;
for (var version in versions) {
if (primary == null ||
(!version.isPreRelease && primary.isPreRelease) ||
(version.isPreRelease == primary.isPreRelease && version > primary)) {
primary = version;
}
}
return primary;
}
/// Splits a string of dot-delimited identifiers into their component parts.
///
/// Identifiers that are numeric are converted to numbers.
static List _splitParts(String text) {
return text.split('.').map((part) {
// Return an integer part if possible, otherwise return the string as-is
return int.tryParse(part) ?? part;
}).toList();
}
@override
bool operator ==(Object other) =>
other is Version &&
major == other.major &&
minor == other.minor &&
patch == other.patch &&
_equality.equals(preRelease, other.preRelease) &&
_equality.equals(build, other.build);
@override
int get hashCode =>
major ^
minor ^
patch ^
_equality.hash(preRelease) ^
_equality.hash(build);
bool operator <(Version other) => compareTo(other) < 0;
bool operator >(Version other) => compareTo(other) > 0;
bool operator <=(Version other) => compareTo(other) <= 0;
bool operator >=(Version other) => compareTo(other) >= 0;
@override
bool get isAny => false;
@override
bool get isEmpty => false;
/// Whether or not this is a pre-release version.
bool get isPreRelease => preRelease.isNotEmpty;
/// Gets the next major version number that follows this one.
///
/// If this version is a pre-release of a major version release (i.e. the
/// minor and patch versions are zero), then it just strips the pre-release
/// suffix. Otherwise, it increments the major version and resets the minor
/// and patch.
Version get nextMajor {
if (isPreRelease && minor == 0 && patch == 0) {
return Version(major, minor, patch);
}
return _incrementMajor();
}
/// Gets the next minor version number that follows this one.
///
/// If this version is a pre-release of a minor version release (i.e. the
/// patch version is zero), then it just strips the pre-release suffix.
/// Otherwise, it increments the minor version and resets the patch.
Version get nextMinor {
if (isPreRelease && patch == 0) {
return Version(major, minor, patch);
}
return _incrementMinor();
}
/// Gets the next patch version number that follows this one.
///
/// If this version is a pre-release, then it just strips the pre-release
/// suffix. Otherwise, it increments the patch version.
Version get nextPatch {
if (isPreRelease) {
return Version(major, minor, patch);
}
return _incrementPatch();
}
/// Gets the next breaking version number that follows this one.
///
/// Increments [major] if it's greater than zero, otherwise [minor], resets
/// subsequent digits to zero, and strips any [preRelease] or [build]
/// suffix.
Version get nextBreaking {
if (major == 0) {
return _incrementMinor();
}
return _incrementMajor();
}
/// Returns the first possible pre-release of this version.
Version get firstPreRelease => Version(major, minor, patch, pre: '0');
/// Returns whether this is the first possible pre-release of its version.
bool get isFirstPreRelease => preRelease.length == 1 && preRelease.first == 0;
Version _incrementMajor() => Version(major + 1, 0, 0);
Version _incrementMinor() => Version(major, minor + 1, 0);
Version _incrementPatch() => Version(major, minor, patch + 1);
/// Tests if [other] matches this version exactly.
@override
bool allows(Version other) => this == other;
@override
bool allowsAll(VersionConstraint other) => other.isEmpty || other == this;
@override
bool allowsAny(VersionConstraint other) => other.allows(this);
@override
VersionConstraint intersect(VersionConstraint other) =>
other.allows(this) ? this : VersionConstraint.empty;
@override
VersionConstraint union(VersionConstraint other) {
if (other.allows(this)) return other;
if (other is VersionRange) {
if (other.min == this) {
return VersionRange(
min: other.min,
max: other.max,
includeMin: true,
includeMax: other.includeMax,
alwaysIncludeMaxPreRelease: true);
}
if (other.max == this) {
return VersionRange(
min: other.min,
max: other.max,
includeMin: other.includeMin,
includeMax: true,
alwaysIncludeMaxPreRelease: true);
}
}
return VersionConstraint.unionOf([this, other]);
}
@override
VersionConstraint difference(VersionConstraint other) =>
other.allows(this) ? VersionConstraint.empty : this;
@override
int compareTo(VersionRange other) {
if (other is Version) {
if (major != other.major) return major.compareTo(other.major);
if (minor != other.minor) return minor.compareTo(other.minor);
if (patch != other.patch) return patch.compareTo(other.patch);
// Pre-releases always come before no pre-release string.
if (!isPreRelease && other.isPreRelease) return 1;
if (!other.isPreRelease && isPreRelease) return -1;
var comparison = _compareLists(preRelease, other.preRelease);
if (comparison != 0) return comparison;
// Builds always come after no build string.
if (build.isEmpty && other.build.isNotEmpty) return -1;
if (other.build.isEmpty && build.isNotEmpty) return 1;
return _compareLists(build, other.build);
} else {
return -other.compareTo(this);
}
}
@override
String toString() => _text;
/// Compares a dot-separated component of two versions.
///
/// This is used for the pre-release and build version parts. This follows
/// Rule 12 of the Semantic Versioning spec (v2.0.0-rc.1).
int _compareLists(List a, List b) {
for (var i = 0; i < math.max(a.length, b.length); i++) {
var aPart = (i < a.length) ? a[i] : null;
var bPart = (i < b.length) ? b[i] : null;
if (aPart == bPart) continue;
// Missing parts come before present ones.
if (aPart == null) return -1;
if (bPart == null) return 1;
if (aPart is num) {
if (bPart is num) {
// Compare two numbers.
return aPart.compareTo(bPart);
} else {
// Numbers come before strings.
return -1;
}
} else {
if (bPart is num) {
// Strings come after numbers.
return 1;
} else {
// Compare two strings.
return (aPart as String).compareTo(bPart as String);
}
}
}
// The lists are entirely equal.
return 0;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs/graphs.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
export 'src/crawl_async.dart' show crawlAsync;
export 'src/shortest_path.dart' show shortestPath, shortestPaths;
export 'src/strongly_connected_components.dart'
show stronglyConnectedComponents;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs/src/strongly_connected_components.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:math' show min;
/// Finds the strongly connected components of a directed graph using Tarjan's
/// algorithm.
///
/// The result will be a valid reverse topological order ordering of the
/// strongly connected components. Components further from a root will appear in
/// the result before the components which they are connected to.
///
/// Nodes within a strongly connected component have no ordering guarantees,
/// except that if the first value in [nodes] is a valid root, and is contained
/// in a cycle, it will be the last element of that cycle.
///
/// [nodes] must contain at least a root of every tree in the graph if there are
/// disjoint subgraphs but it may contain all nodes in the graph if the roots
/// are not known.
///
/// If [equals] is provided, it is used to compare nodes in the graph. If
/// [equals] is omitted, the node's own [Object.==] is used instead.
///
/// Similarly, if [hashCode] is provided, it is used to produce a hash value
/// for nodes to efficiently calculate the return value. If it is omitted, the
/// key's own [Object.hashCode] is used.
///
/// If you supply one of [equals] or [hashCode], you should generally also to
/// supply the other.
List<List<T>> stronglyConnectedComponents<T>(
Iterable<T> nodes,
Iterable<T> Function(T) edges, {
bool equals(T key1, T key2),
int hashCode(T key),
}) {
final result = <List<T>>[];
final lowLinks = HashMap<T, int>(equals: equals, hashCode: hashCode);
final indexes = HashMap<T, int>(equals: equals, hashCode: hashCode);
final onStack = HashSet<T>(equals: equals, hashCode: hashCode);
equals ??= _defaultEquals;
var index = 0;
var lastVisited = Queue<T>();
void strongConnect(T node) {
indexes[node] = index;
lowLinks[node] = index;
index++;
lastVisited.addLast(node);
onStack.add(node);
// ignore: omit_local_variable_types
for (final T next in edges(node) ?? const []) {
if (!indexes.containsKey(next)) {
strongConnect(next);
lowLinks[node] = min(lowLinks[node], lowLinks[next]);
} else if (onStack.contains(next)) {
lowLinks[node] = min(lowLinks[node], indexes[next]);
}
}
if (lowLinks[node] == indexes[node]) {
final component = <T>[];
T next;
do {
next = lastVisited.removeLast();
onStack.remove(next);
component.add(next);
} while (!equals(next, node));
result.add(component);
}
}
for (final node in nodes) {
if (!indexes.containsKey(node)) strongConnect(node);
}
return result;
}
bool _defaultEquals(a, b) => a == b;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs/src/crawl_async.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
final _empty = Future<Null>.value(null);
/// Finds and returns every node in a graph who's nodes and edges are
/// asynchronously resolved.
///
/// Cycles are allowed. If this is an undirected graph the [edges] function
/// may be symmetric. In this case the [roots] may be any node in each connected
/// graph.
///
/// [V] is the type of values in the graph nodes. [K] must be a type suitable
/// for using as a Map or Set key. [edges] should return the next reachable
/// nodes.
///
/// There are no ordering guarantees. This is useful for ensuring some work is
/// performed at every node in an asynchronous graph, but does not give
/// guarantees that the work is done in topological order.
///
/// If [readNode] returns null for any key it will be ignored from the rest of
/// the graph. If missing nodes are important they should be tracked within the
/// [readNode] callback.
///
/// If either [readNode] or [edges] throws the error will be forwarded
/// through the result stream and no further nodes will be crawled, though some
/// work may have already been started.
Stream<V> crawlAsync<K, V>(Iterable<K> roots, FutureOr<V> Function(K) readNode,
FutureOr<Iterable<K>> Function(K, V) edges) {
final crawl = _CrawlAsync(roots, readNode, edges)..run();
return crawl.result.stream;
}
class _CrawlAsync<K, V> {
final result = StreamController<V>();
final FutureOr<V> Function(K) readNode;
final FutureOr<Iterable<K>> Function(K, V) edges;
final Iterable<K> roots;
final _seen = HashSet<K>();
_CrawlAsync(this.roots, this.readNode, this.edges);
/// Add all nodes in the graph to [result] and return a Future which fires
/// after all nodes have been seen.
Future<Null> run() async {
try {
await Future.wait(roots.map(_visit), eagerError: true);
await result.close();
} catch (e, st) {
result.addError(e, st);
await result.close();
}
}
/// Resolve the node at [key] and output it, then start crawling all of it's
/// edges.
Future<Null> _crawlFrom(K key) async {
var value = await readNode(key);
if (value == null) return;
if (result.isClosed) return;
result.add(value);
var next = await edges(key, value) ?? const [];
await Future.wait(next.map(_visit), eagerError: true);
}
/// Synchronously record that [key] is being handled then start work on the
/// node for [key].
///
/// The returned Future will complete only after the work for [key] and all
/// transitively reachable nodes has either been finished, or will be finished
/// by some other Future in [_seen].
Future<Null> _visit(K key) {
if (_seen.contains(key)) return _empty;
_seen.add(key);
return _crawlFrom(key);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/graphs/src/shortest_path.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
/// Returns the shortest path from [start] to [target] given the directed
/// edges of a graph provided by [edges].
///
/// If [start] `==` [target], an empty [List] is returned and [edges] is never
/// called.
///
/// [start], [target] and all values returned by [edges] must not be `null`.
/// If asserts are enabled, an [AssertionError] is raised if these conditions
/// are not met. If asserts are not enabled, violations result in undefined
/// behavior.
///
/// If [equals] is provided, it is used to compare nodes in the graph. If
/// [equals] is omitted, the node's own [Object.==] is used instead.
///
/// Similarly, if [hashCode] is provided, it is used to produce a hash value
/// for nodes to efficiently calculate the return value. If it is omitted, the
/// key's own [Object.hashCode] is used.
///
/// If you supply one of [equals] or [hashCode], you should generally also to
/// supply the other.
List<T> shortestPath<T>(
T start,
T target,
Iterable<T> Function(T) edges, {
bool equals(T key1, T key2),
int hashCode(T key),
}) =>
_shortestPaths<T>(
start,
edges,
target: target,
equals: equals,
hashCode: hashCode,
)[target];
/// Returns a [Map] of the shortest paths from [start] to all of the nodes in
/// the directed graph defined by [edges].
///
/// All return values will contain the key [start] with an empty [List] value.
///
/// [start] and all values returned by [edges] must not be `null`.
/// If asserts are enabled, an [AssertionError] is raised if these conditions
/// are not met. If asserts are not enabled, violations result in undefined
/// behavior.
///
/// If [equals] is provided, it is used to compare nodes in the graph. If
/// [equals] is omitted, the node's own [Object.==] is used instead.
///
/// Similarly, if [hashCode] is provided, it is used to produce a hash value
/// for nodes to efficiently calculate the return value. If it is omitted, the
/// key's own [Object.hashCode] is used.
///
/// If you supply one of [equals] or [hashCode], you should generally also to
/// supply the other.
Map<T, List<T>> shortestPaths<T>(
T start,
Iterable<T> Function(T) edges, {
bool equals(T key1, T key2),
int hashCode(T key),
}) =>
_shortestPaths<T>(
start,
edges,
equals: equals,
hashCode: hashCode,
);
Map<T, List<T>> _shortestPaths<T>(
T start,
Iterable<T> Function(T) edges, {
T target,
bool equals(T key1, T key2),
int hashCode(T key),
}) {
assert(start != null, '`start` cannot be null');
assert(edges != null, '`edges` cannot be null');
final distances = HashMap<T, List<T>>(equals: equals, hashCode: hashCode);
distances[start] = List(0);
equals ??= _defaultEquals;
if (equals(start, target)) {
return distances;
}
final toVisit = ListQueue<T>()..add(start);
List<T> bestOption;
while (toVisit.isNotEmpty) {
final current = toVisit.removeFirst();
final currentPath = distances[current];
final currentPathLength = currentPath.length;
if (bestOption != null && (currentPathLength + 1) >= bestOption.length) {
// Skip any existing `toVisit` items that have no chance of being
// better than bestOption (if it exists)
continue;
}
for (var edge in edges(current)) {
assert(edge != null, '`edges` cannot return null values.');
final existingPath = distances[edge];
assert(existingPath == null ||
existingPath.length <= (currentPathLength + 1));
if (existingPath == null) {
final newOption = List<T>(currentPathLength + 1)
..setRange(0, currentPathLength, currentPath)
..[currentPathLength] = edge;
if (equals(edge, target)) {
assert(bestOption == null || bestOption.length > newOption.length);
bestOption = newOption;
}
distances[edge] = newOption;
if (bestOption == null || bestOption.length > newOption.length) {
// Only add a node to visit if it might be a better path to the
// target node
toVisit.add(edge);
}
}
}
}
return distances;
}
bool _defaultEquals(a, b) => a == b;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/meta/dart2js.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Constants for use in metadata annotations to provide hints to dart2js.
///
/// This is an experimental feature and not expected to be useful except for low
/// level framework authors.
///
/// Added at sdk version 2.0.0-dev.6.0
library meta_dart2js;
/// An annotation for methods to request that dart2js does not inline the
/// method.
///
/// import 'package:meta/dart2js.dart' as dart2js;
///
/// @dart2js.noInline
/// String text() => 'A String of unusual size';
const _NoInline noInline = _NoInline();
/// An annotation for methods to request that dart2js always inline the
/// method.
///
/// dart2js will attempt to inline the method regardless of its size. Even with
/// this annotation, there are conditions that can prevent dart2js from inlining
/// a method, including complex control flow.
///
/// import 'package:meta/dart2js.dart' as dart2js;
///
/// @dart2js.tryInline
/// String bigMethod() {
/// for (int i in "Hello".runes) print(i);
/// }
///
/// It is an error to use both `@noInline` and `@tryInline` on the same method.
const _TryInline tryInline = _TryInline();
class _NoInline {
const _NoInline();
}
class _TryInline {
const _TryInline();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/meta/meta_meta.dart | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Annotations that describe the intended use of other annotations.
library meta_meta;
/// An annotation used on classes that are intended to be used as annotations
/// to indicate the kinds of declarations and directives for which the
/// annotation is appropriate.
///
/// The kinds are represented by the constants defined in [TargetKind].
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a class, where the
/// class must be usable as an annotation (that is, contain at least one
/// `const` constructor).
/// * the annotated annotation is associated with anything other than the kinds
/// of declarations listed as valid targets.
@Target({TargetKind.classType})
class Target {
/// The kinds of declarations with which the annotated annotation can be
/// associated.
final Set<TargetKind> kinds;
const Target(this.kinds);
}
/// An enumeration of the kinds of targets to which an annotation can be
/// applied.
enum TargetKind {
/// Indicates that an annotation is valid on any class declaration.
classType,
/// Indicates that an annotation is valid on any enum declaration.
enumType,
/// Indicates that an annotation is valid on any extension declaration.
extension,
/// Indicates that an annotation is valid on any field declaration, both
/// instance and static fields, whether it's in a class, mixin or extension.
field,
/// Indicates that an annotation is valid on any top-level function
/// declaration.
function,
/// Indicates that an annotation is valid on the first directive in a library,
/// whether that's a `library`, `import`, `export` or `part` directive. This
/// doesn't include the `part of` directive in a part file.
library,
/// Indicates that an annotation is valid on any getter declaration, both
/// instance or static getters, whether it's in a class, mixin, extension, or
/// at the top-level of a library.
getter,
/// Indicates that an annotation is valid on any method declaration, both
/// instance and static methods, whether it's in a class, mixin or extension.
method,
/// Indicates that an annotation is valid on any mixin declaration.
mixinType,
/// Indicates that an annotation is valid on any formal parameter declaration,
/// whether it's in a function, method, constructor, or closure.
parameter,
/// Indicates that an annotation is valid on any setter declaration, both
/// instance or static setters, whether it's in a class, mixin, extension, or
/// at the top-level of a library.
setter,
/// Indicates that an annotation is valid on any declaration that introduces a
/// type. This includes classes, enums, mixins and typedefs, but does not
/// include extensions because extensions don't introduce a type.
type,
/// Indicates that an annotation is valid on any typedef declaration.
typedefType,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/meta/meta.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Annotations that developers can use to express the intentions that otherwise
/// can't be deduced by statically analyzing the source code.
///
/// See also `@deprecated` and `@override` in the `dart:core` library.
///
/// Annotations provide semantic information that tools can use to provide a
/// better user experience. For example, an IDE might not autocomplete the name
/// of a function that's been marked `@deprecated`, or it might display the
/// function's name differently.
///
/// For information on installing and importing this library, see the [meta
/// package on pub.dev](https://pub.dev/packages/meta). For examples of using
/// annotations, see
/// [Metadata](https://dart.dev/guides/language/language-tour#metadata) in the
/// language tour.
library meta;
/// Used to annotate a function `f`. Indicates that `f` always throws an
/// exception. Any functions that override `f`, in class inheritance, are also
/// expected to conform to this contract.
///
/// Tools, such as the analyzer, can use this to understand whether a block of
/// code "exits". For example:
///
/// ```dart
/// @alwaysThrows toss() { throw 'Thrown'; }
///
/// int fn(bool b) {
/// if (b) {
/// return 0;
/// } else {
/// toss();
/// print("Hello.");
/// }
/// }
/// ```
///
/// Without the annotation on `toss`, it would look as though `fn` doesn't
/// always return a value. The annotation shows that `fn` does always exit. In
/// addition, the annotation reveals that any statements following a call to
/// `toss` (like the `print` call) are dead code.
///
/// Tools, such as the analyzer, can also expect this contract to be enforced;
/// that is, tools may emit warnings if a function with this annotation
/// _doesn't_ always throw.
const _AlwaysThrows alwaysThrows = _AlwaysThrows();
/// Used to annotate a parameter of an instance method that overrides another
/// method.
///
/// Indicates that this parameter may have a tighter type than the parameter on
/// its superclass. The actual argument will be checked at runtime to ensure it
/// is a subtype of the overridden parameter type.
///
@Deprecated('Use the `covariant` modifier instead')
const _Checked checked = _Checked();
/// Used to annotate a method, getter or top-level getter or function to
/// indicate that the value obtained by invoking it should not be stored in a
/// field or top-level variable. The annotation can also be applied to a class
/// to implicitly annotate all of the valid members of the class, or applied to
/// a library to annotate all of the valid members of the library, including
/// classes. If a value returned by an element marked as `doNotStore` is returned
/// from a function or getter, that function or getter should be similarly
/// annotated.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a library, class,
/// method or getter, top-level getter or function, or
/// * an invocation of a member that has this annotation is returned by a method,
/// getter or function that is not similarly annotated as `doNotStore`, or
/// * an invocation of a member that has this annotation is assigned to a field
/// or top-level variable.
const _DoNotStore doNotStore = _DoNotStore();
/// Used to annotate a library, or any declaration that is part of the public
/// interface of a library (such as top-level members, class members, and
/// function parameters) to indicate that the annotated API is experimental and
/// may be removed or changed at any-time without updating the version of the
/// containing package, despite the fact that it would otherwise be a breaking
/// change.
///
/// If the annotation is applied to a library then it is equivalent to applying
/// the annotation to all of the top-level members of the library. Applying the
/// annotation to a class does *not* apply the annotation to subclasses, but
/// does apply the annotation to members of the class.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with a declaration that is not part of the
/// public interface of a library (such as a local variable or a declaration
/// that is private) or a directive other than the first directive in the
/// library, or
/// * the declaration is referenced by a package that has not explicitly
/// indicated its intention to use experimental APIs (details TBD).
const _Experimental experimental = _Experimental();
/// Used to annotate an instance or static method `m`. Indicates that `m` must
/// either be abstract or must return a newly allocated object or `null`. In
/// addition, every method that either implements or overrides `m` is implicitly
/// annotated with this same annotation.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a method, or
/// * a method that has this annotation can return anything other than a newly
/// allocated object or `null`.
const _Factory factory = _Factory();
/// Used to annotate a class `C`. Indicates that `C` and all subtypes of `C`
/// must be immutable.
///
/// A class is immutable if all of the instance fields of the class, whether
/// defined directly or inherited, are `final`.
///
/// Tools, such as the analyzer, can provide feedback if
/// * the annotation is associated with anything other than a class, or
/// * a class that has this annotation or extends, implements or mixes in a
/// class that has this annotation is not immutable.
const Immutable immutable = Immutable();
/// Used to annotate a declaration which should only be used from within the
/// package in which it is declared, and which should not be exposed from said
/// package's public API.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the declaration is declared in a package's public API, or is exposed from
/// a package's public API, or
/// * the declaration is private, an unnamed extension, a static member of a
/// private class, mixin, or extension, a value of a private enum, or a
/// constructor of a private class, or
/// * the declaration is referenced outside the package in which it is declared.
const _Internal internal = _Internal();
/// Used to annotate a test framework function that runs a single test.
///
/// Tools, such as IDEs, can show invocations of such function in a file
/// structure view to help the user navigating in large test files.
///
/// The first parameter of the function must be the description of the test.
const _IsTest isTest = _IsTest();
/// Used to annotate a test framework function that runs a group of tests.
///
/// Tools, such as IDEs, can show invocations of such function in a file
/// structure view to help the user navigating in large test files.
///
/// The first parameter of the function must be the description of the group.
const _IsTestGroup isTestGroup = _IsTestGroup();
/// Used to annotate a const constructor `c`. Indicates that any invocation of
/// the constructor must use the keyword `const` unless one or more of the
/// arguments to the constructor is not a compile-time constant.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a const constructor,
/// or
/// * an invocation of a constructor that has this annotation is not invoked
/// using the `const` keyword unless one or more of the arguments to the
/// constructor is not a compile-time constant.
const _Literal literal = _Literal();
/// Used to annotate an instance method `m`. Indicates that every invocation of
/// a method that overrides `m` must also invoke `m`. In addition, every method
/// that overrides `m` is implicitly annotated with this same annotation.
///
/// Note that private methods with this annotation cannot be validly overridden
/// outside of the library that defines the annotated method.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than an instance method,
/// or
/// * a method that overrides a method that has this annotation can return
/// without invoking the overridden method.
const _MustCallSuper mustCallSuper = _MustCallSuper();
/// Used to annotate an instance member (method, getter, setter, operator, or
/// field) `m` in a class `C` or mixin `M`. Indicates that `m` should not be
/// overridden in any classes that extend or mixin `C` or `M`.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than an instance member,
/// * the annotation is associated with an abstract member (because subclasses
/// are required to override the member),
/// * the annotation is associated with an extension method,
/// * the annotation is associated with a member `m` in class `C`, and there is
/// a class `D` or mixin `M`, that extends or mixes in `C`, that declares an
/// overriding member `m`.
const _NonVirtual nonVirtual = _NonVirtual();
/// Used to annotate a class, mixin, or extension declaration `C`. Indicates
/// that any type arguments declared on `C` are to be treated as optional.
/// Tools such as the analyzer and linter can use this information to suppress
/// warnings that would otherwise require type arguments on `C` to be provided.
const _OptionalTypeArgs optionalTypeArgs = _OptionalTypeArgs();
/// Used to annotate an instance member (method, getter, setter, operator, or
/// field) `m` in a class `C`. If the annotation is on a field it applies to the
/// getter, and setter if appropriate, that are induced by the field. Indicates
/// that `m` should only be invoked from instance methods of `C` or classes that
/// extend, implement or mix in `C`, either directly or indirectly. Additionally
/// indicates that `m` should only be invoked on `this`, whether explicitly or
/// implicitly.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than an instance member,
/// or
/// * an invocation of a member that has this annotation is used outside of an
/// instance member defined on a class that extends or mixes in (or a mixin
/// constrained to) the class in which the protected member is defined.
/// * an invocation of a member that has this annotation is used within an
/// instance method, but the receiver is something other than `this`.
const _Protected protected = _Protected();
/// Used to annotate a named parameter `p` in a method or function `f`.
/// Indicates that every invocation of `f` must include an argument
/// corresponding to `p`, despite the fact that `p` would otherwise be an
/// optional parameter.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a named parameter,
/// * the annotation is associated with a named parameter in a method `m1` that
/// overrides a method `m0` and `m0` defines a named parameter with the same
/// name that does not have this annotation, or
/// * an invocation of a method or function does not include an argument
/// corresponding to a named parameter that has this annotation.
const Required required = Required();
/// Annotation marking a class as not allowed as a super-type.
///
/// Classes in the same package as the marked class may extend, implement or
/// mix-in the annotated class.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with anything other than a class,
/// * the annotation is associated with a class `C`, and there is a class or
/// mixin `D`, which extends, implements, mixes in, or constrains to `C`, and
/// `C` and `D` are declared in different packages.
const _Sealed sealed = _Sealed();
/// Used to annotate a field that is allowed to be overridden in Strong Mode.
///
/// Deprecated: Most of strong mode is now the default in 2.0, but the notion of
/// virtual fields was dropped, so this annotation no longer has any meaning.
/// Uses of the annotation should be removed.
@Deprecated('No longer has meaning')
const _Virtual virtual = _Virtual();
/// Used to annotate an instance member that was made public so that it could be
/// overridden but that is not intended to be referenced from outside the
/// defining library.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with a declaration other than a public
/// instance member in a class or mixin, or
/// * the member is referenced outside of the defining library.
const _VisibleForOverriding visibleForOverriding = _VisibleForOverriding();
/// Used to annotate a declaration that was made public, so that it is more
/// visible than otherwise necessary, to make code testable.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with a declaration not in the `lib` folder
/// of a package, or a private declaration, or a declaration in an unnamed
/// static extension, or
/// * the declaration is referenced outside of its defining library or a
/// library which is in the `test` folder of the defining package.
const _VisibleForTesting visibleForTesting = _VisibleForTesting();
/// Used to annotate a class.
///
/// See [immutable] for more details.
class Immutable {
/// A human-readable explanation of the reason why the class is immutable.
final String reason;
/// Initialize a newly created instance to have the given [reason].
const Immutable([this.reason = '']);
}
/// Used to annotate a named parameter `p` in a method or function `f`.
///
/// See [required] for more details.
class Required {
/// A human-readable explanation of the reason why the annotated parameter is
/// required. For example, the annotation might look like:
///
/// ButtonWidget({
/// Function onHover,
/// @Required('Buttons must do something when pressed')
/// Function onPressed,
/// ...
/// }) ...
final String reason;
/// Initialize a newly created instance to have the given [reason].
const Required([this.reason = '']);
}
class _AlwaysThrows {
const _AlwaysThrows();
}
class _Checked {
const _Checked();
}
class _DoNotStore {
const _DoNotStore();
}
class _Experimental {
const _Experimental();
}
class _Factory {
const _Factory();
}
class _Internal {
const _Internal();
}
class _IsTest {
const _IsTest();
}
class _IsTestGroup {
const _IsTestGroup();
}
class _Literal {
const _Literal();
}
class _MustCallSuper {
const _MustCallSuper();
}
class _NonVirtual {
const _NonVirtual();
}
class _OptionalTypeArgs {
const _OptionalTypeArgs();
}
class _Protected {
const _Protected();
}
class _Sealed {
const _Sealed();
}
@Deprecated('No longer has meaning')
class _Virtual {
const _Virtual();
}
class _VisibleForOverriding {
const _VisibleForOverriding();
}
class _VisibleForTesting {
const _VisibleForTesting();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_http/node_http.dart | // Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// HTTP client using Node I/O system for Dart.
///
/// See [NodeClient] for details.
library node_http;
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'src/node_client.dart';
export 'package:http/http.dart'
show
BaseClient,
BaseRequest,
BaseResponse,
StreamedRequest,
StreamedResponse,
Request,
Response,
ByteStream,
ClientException;
export 'src/node_client.dart';
/// Sends an HTTP HEAD request with the given headers to the given URL, which
/// can be a [Uri] or a [String].
///
/// This automatically initializes a new [Client] and closes that client once
/// the request is complete. If you're planning on making multiple requests to
/// the same server, you should use a single [Client] for all of those requests.
///
/// For more fine-grained control over the request, use [Request] instead.
Future<Response> head(url, {Map<String, String> headers}) =>
_withClient((client) => client.head(url, headers: headers));
/// Sends an HTTP GET request with the given headers to the given URL, which can
/// be a [Uri] or a [String].
///
/// This automatically initializes a new [Client] and closes that client once
/// the request is complete. If you're planning on making multiple requests to
/// the same server, you should use a single [Client] for all of those requests.
///
/// For more fine-grained control over the request, use [Request] instead.
Future<Response> get(url, {Map<String, String> headers}) =>
_withClient((client) => client.get(url, headers: headers));
/// Sends an HTTP POST request with the given headers and body to the given URL,
/// which can be a [Uri] or a [String].
///
/// For more fine-grained control over the request, use [Request] or
/// [StreamedRequest] instead.
Future<Response> post(url,
{Map<String, String> headers, body, Encoding encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
/// Sends an HTTP PUT request with the given headers and body to the given URL,
/// which can be a [Uri] or a [String].
///
/// For more fine-grained control over the request, use [Request] or
/// [StreamedRequest] instead.
Future<Response> put(url,
{Map<String, String> headers, body, Encoding encoding}) =>
_withClient((client) =>
client.put(url, headers: headers, body: body, encoding: encoding));
/// Sends an HTTP PATCH request with the given headers and body to the given
/// URL, which can be a [Uri] or a [String].
///
/// For more fine-grained control over the request, use [Request] or
/// [StreamedRequest] instead.
Future<Response> patch(url,
{Map<String, String> headers, body, Encoding encoding}) =>
_withClient((client) =>
client.patch(url, headers: headers, body: body, encoding: encoding));
/// Sends an HTTP DELETE request with the given headers to the given URL, which
/// can be a [Uri] or a [String].
///
/// This automatically initializes a new [Client] and closes that client once
/// the request is complete. If you're planning on making multiple requests to
/// the same server, you should use a single [Client] for all of those requests.
///
/// For more fine-grained control over the request, use [Request] instead.
Future<Response> delete(url, {Map<String, String> headers}) =>
_withClient((client) => client.delete(url, headers: headers));
/// Sends an HTTP GET request with the given headers to the given URL, which can
/// be a [Uri] or a [String], and returns a Future that completes to the body of
/// the response as a [String].
///
/// The Future will emit a [ClientException] if the response doesn't have a
/// success status code.
///
/// This automatically initializes a new [Client] and closes that client once
/// the request is complete. If you're planning on making multiple requests to
/// the same server, you should use a single [Client] for all of those requests.
///
/// For more fine-grained control over the request and response, use [Request]
/// instead.
Future<String> read(url, {Map<String, String> headers}) =>
_withClient((client) => client.read(url, headers: headers));
Future<T> _withClient<T>(Future<T> Function(Client client) fn) async {
var client = NodeClient();
try {
return await fn(client);
} finally {
client.close();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_http | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_http/src/node_client.dart | // Copyright (c) 2018, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:js';
import 'package:http/http.dart';
import 'package:node_interop/http.dart';
import 'package:node_interop/https.dart';
import 'package:node_interop/node.dart';
import 'package:node_interop/util.dart';
import 'package:node_io/node_io.dart';
export 'package:node_interop/http.dart' show HttpAgentOptions;
export 'package:node_interop/https.dart' show HttpsAgentOptions;
/// HTTP client which uses Node.js I/O system.
///
/// Make sure to call [close] when work with this client is done.
class NodeClient extends BaseClient {
/// Keep sockets around even when there are no outstanding requests, so they
/// can be used for future requests without having to reestablish a TCP
/// connection. Defaults to `true`.
@Deprecated('To be removed in 1.0.0')
bool get keepAlive => _httpOptions.keepAlive;
/// When using the keepAlive option, specifies the initial delay for TCP
/// Keep-Alive packets. Ignored when the keepAlive option is false.
/// Defaults to 1000.
@Deprecated('To be removed in 1.0.0')
int get keepAliveMsecs => _httpOptions.keepAliveMsecs;
/// Creates new Node HTTP client.
///
/// If [httpOptions] or [httpsOptions] are provided they are used to create
/// underlying `HttpAgent` and `HttpsAgent` respectively. These arguments also
/// take precedence over [keepAlive] and [keepAliveMsecs].
NodeClient({
bool keepAlive = true,
int keepAliveMsecs = 1000,
HttpAgentOptions httpOptions,
HttpsAgentOptions httpsOptions,
}) : _httpOptions = httpOptions ??
HttpAgentOptions(
keepAlive: keepAlive, keepAliveMsecs: keepAliveMsecs),
_httpsOptions = httpsOptions ??
HttpsAgentOptions(
keepAlive: keepAlive, keepAliveMsecs: keepAliveMsecs);
final HttpAgentOptions _httpOptions;
final HttpsAgentOptions _httpsOptions;
/// Native JavaScript connection agent used by this client for insecure
/// requests.
HttpAgent get httpAgent => _httpAgent ??= createHttpAgent(_httpOptions);
HttpAgent _httpAgent;
/// Native JavaScript connection agent used by this client for secure
/// requests.
HttpAgent get httpsAgent => _httpsAgent ??= createHttpsAgent(_httpsOptions);
HttpAgent _httpsAgent;
@override
Future<StreamedResponse> send(BaseRequest request) {
final handler = _RequestHandler(this, request);
return handler.send();
}
@override
void close() {
httpAgent.destroy();
httpsAgent.destroy();
}
}
class _RequestHandler {
final NodeClient client;
final BaseRequest request;
_RequestHandler(this.client, this.request);
final List<_RedirectInfo> _redirects = [];
List<List<int>> _body;
var _headers;
Future<StreamedResponse> send() async {
_body = await request.finalize().toList();
_headers = jsify(request.headers);
var response = await _send();
if (request.followRedirects && response.isRedirect) {
var method = request.method;
while (response.isRedirect) {
if (_redirects.length < request.maxRedirects) {
response = await redirect(response, method);
method = _redirects.last.method;
} else {
throw ClientException('Redirect limit exceeded.');
}
}
}
return response;
}
Future<StreamedResponse> _send({Uri url, String method}) {
url ??= request.url;
method ??= request.method;
var usedAgent =
(url.scheme == 'http') ? client.httpAgent : client.httpsAgent;
var sendRequest = (url.scheme == 'http') ? http.request : https.request;
var pathWithQuery =
url.hasQuery ? [url.path, '?', url.query].join() : url.path;
var options = RequestOptions(
protocol: '${url.scheme}:',
hostname: url.host,
port: url.port,
method: method,
path: pathWithQuery,
headers: _headers,
agent: usedAgent,
);
var completer = Completer<StreamedResponse>();
void handleResponse(IncomingMessage response) {
final rawHeaders = dartify(response.headers) as Map<String, dynamic>;
final headers = <String, String>{};
for (var key in rawHeaders.keys) {
final value = rawHeaders[key];
headers[key] = (value is List) ? value.join(',') : value;
}
final controller = StreamController<List<int>>();
completer.complete(StreamedResponse(
controller.stream,
response.statusCode,
request: request,
headers: headers,
reasonPhrase: response.statusMessage,
isRedirect: isRedirect(response, method),
));
response.on('data', allowInterop((Iterable<int> buffer) {
// buffer is an instance of Node's Buffer.
controller.add(List.unmodifiable(buffer));
}));
response.on('end', allowInterop(() {
controller.close();
}));
}
var nodeRequest = sendRequest(options, allowInterop(handleResponse));
nodeRequest.on('error', allowInterop((e) {
completer.completeError(e);
}));
// TODO: Support StreamedRequest by consuming body asynchronously.
_body.forEach((List<int> chunk) {
var buffer = Buffer.from(chunk);
nodeRequest.write(buffer);
});
nodeRequest.end();
return completer.future;
}
bool isRedirect(IncomingMessage message, String method) {
final statusCode = message.statusCode;
if (method == 'GET' || method == 'HEAD') {
return statusCode == HttpStatus.movedPermanently ||
statusCode == HttpStatus.found ||
statusCode == HttpStatus.seeOther ||
statusCode == HttpStatus.temporaryRedirect;
} else if (method == 'POST') {
return statusCode == HttpStatus.seeOther;
}
return false;
}
Future<StreamedResponse> redirect(StreamedResponse response,
[String method, bool followLoops]) {
// Set method as defined by RFC 2616 section 10.3.4.
if (response.statusCode == HttpStatus.seeOther && method == 'POST') {
method = 'GET';
}
final location = response.headers[HttpHeaders.locationHeader];
if (location == null) {
throw StateError('Response has no Location header for redirect.');
}
final url = Uri.parse(location);
if (followLoops != true) {
for (var redirect in _redirects) {
if (redirect.location == url) {
return Future.error(ClientException('Redirect loop detected.'));
}
}
}
return _send(url: url, method: method).then((response) {
_redirects.add(_RedirectInfo(response.statusCode, method, url));
return response;
});
}
}
class _RedirectInfo {
final int statusCode;
final String method;
final Uri location;
const _RedirectInfo(this.statusCode, this.method, this.location);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/stack_trace.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
export 'src/chain.dart';
export 'src/frame.dart';
export 'src/trace.dart';
export 'src/unparsed_frame.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/unparsed_frame.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'frame.dart';
/// A frame that failed to parse.
///
/// The [member] property contains the original frame's contents.
class UnparsedFrame implements Frame {
@override
final Uri uri = Uri(path: 'unparsed');
@override
final int line = null;
@override
final int column = null;
@override
final bool isCore = false;
@override
final String library = 'unparsed';
@override
final String package = null;
@override
final String location = 'unparsed';
@override
final String member;
UnparsedFrame(this.member);
@override
String toString() => member;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/frame.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:path/path.dart' as path;
import 'trace.dart';
import 'unparsed_frame.dart';
// #1 Foo._bar (file:///home/nweiz/code/stuff.dart:42:21)
// #1 Foo._bar (file:///home/nweiz/code/stuff.dart:42)
// #1 Foo._bar (file:///home/nweiz/code/stuff.dart)
final _vmFrame = RegExp(r'^#\d+\s+(\S.*) \((.+?)((?::\d+){0,2})\)$');
// at Object.stringify (native)
// at VW.call$0 (https://example.com/stuff.dart.js:560:28)
// at VW.call$0 (eval as fn
// (https://example.com/stuff.dart.js:560:28), efn:3:28)
// at https://example.com/stuff.dart.js:560:28
final _v8Frame =
RegExp(r'^\s*at (?:(\S.*?)(?: \[as [^\]]+\])? \((.*)\)|(.*))$');
// https://example.com/stuff.dart.js:560:28
// https://example.com/stuff.dart.js:560
final _v8UrlLocation = RegExp(r'^(.*?):(\d+)(?::(\d+))?$|native$');
// eval as function (https://example.com/stuff.dart.js:560:28), efn:3:28
// eval as function (https://example.com/stuff.dart.js:560:28)
// eval as function (eval as otherFunction
// (https://example.com/stuff.dart.js:560:28))
final _v8EvalLocation =
RegExp(r'^eval at (?:\S.*?) \((.*)\)(?:, .*?:\d+:\d+)?$');
// anonymous/<@https://example.com/stuff.js line 693 > Function:3:40
// anonymous/<@https://example.com/stuff.js line 693 > eval:3:40
final _firefoxEvalLocation =
RegExp(r'(\S+)@(\S+) line (\d+) >.* (Function|eval):\d+:\d+');
// .VW.call$0@https://example.com/stuff.dart.js:560
// .VW.call$0("arg")@https://example.com/stuff.dart.js:560
// .VW.call$0/name<@https://example.com/stuff.dart.js:560
// .VW.call$0@https://example.com/stuff.dart.js:560:36
// https://example.com/stuff.dart.js:560
final _firefoxSafariFrame = RegExp(r'^'
r'(?:' // Member description. Not present in some Safari frames.
r'([^@(/]*)' // The actual name of the member.
r'(?:\(.*\))?' // Arguments to the member, sometimes captured by Firefox.
r'((?:/[^/]*)*)' // Extra characters indicating a nested closure.
r'(?:\(.*\))?' // Arguments to the closure.
r'@'
r')?'
r'(.*?)' // The frame's URL.
r':'
r'(\d*)' // The line number. Empty in Safari if it's unknown.
r'(?::(\d*))?' // The column number. Not present in older browsers and
// empty in Safari if it's unknown.
r'$');
// foo/bar.dart 10:11 Foo._bar
// foo/bar.dart 10:11 (anonymous function).dart.fn
// https://dart.dev/foo/bar.dart Foo._bar
// data:... 10:11 Foo._bar
final _friendlyFrame = RegExp(r'^(\S+)(?: (\d+)(?::(\d+))?)?\s+([^\d].*)$');
/// A regular expression that matches asynchronous member names generated by the
/// VM.
final _asyncBody = RegExp(r'<(<anonymous closure>|[^>]+)_async_body>');
final _initialDot = RegExp(r'^\.');
/// A single stack frame. Each frame points to a precise location in Dart code.
class Frame {
/// The URI of the file in which the code is located.
///
/// This URI will usually have the scheme `dart`, `file`, `http`, or `https`.
final Uri uri;
/// The line number on which the code location is located.
///
/// This can be null, indicating that the line number is unknown or
/// unimportant.
final int line;
/// The column number of the code location.
///
/// This can be null, indicating that the column number is unknown or
/// unimportant.
final int column;
/// The name of the member in which the code location occurs.
///
/// Anonymous closures are represented as `<fn>` in this member string.
final String member;
/// Whether this stack frame comes from the Dart core libraries.
bool get isCore => uri.scheme == 'dart';
/// Returns a human-friendly description of the library that this stack frame
/// comes from.
///
/// This will usually be the string form of [uri], but a relative URI will be
/// used if possible. Data URIs will be truncated.
String get library {
if (uri.scheme == 'data') return 'data:...';
return path.prettyUri(uri);
}
/// Returns the name of the package this stack frame comes from, or `null` if
/// this stack frame doesn't come from a `package:` URL.
String get package {
if (uri.scheme != 'package') return null;
return uri.path.split('/').first;
}
/// A human-friendly description of the code location.
String get location {
if (line == null) return library;
if (column == null) return '$library $line';
return '$library $line:$column';
}
/// Returns a single frame of the current stack.
///
/// By default, this will return the frame above the current method. If
/// [level] is `0`, it will return the current method's frame; if [level] is
/// higher than `1`, it will return higher frames.
factory Frame.caller([int level = 1]) {
if (level < 0) {
throw ArgumentError('Argument [level] must be greater than or equal '
'to 0.');
}
return Trace.current(level + 1).frames.first;
}
/// Parses a string representation of a Dart VM stack frame.
factory Frame.parseVM(String frame) => _catchFormatException(frame, () {
// The VM sometimes folds multiple stack frames together and replaces
// them with "...".
if (frame == '...') {
return Frame(Uri(), null, null, '...');
}
var match = _vmFrame.firstMatch(frame);
if (match == null) return UnparsedFrame(frame);
// Get the pieces out of the regexp match. Function, URI and line should
// always be found. The column is optional.
var member = match[1]
.replaceAll(_asyncBody, '<async>')
.replaceAll('<anonymous closure>', '<fn>');
var uri = match[2].startsWith('<data:')
? Uri.dataFromString('')
: Uri.parse(match[2]);
var lineAndColumn = match[3].split(':');
var line =
lineAndColumn.length > 1 ? int.parse(lineAndColumn[1]) : null;
var column =
lineAndColumn.length > 2 ? int.parse(lineAndColumn[2]) : null;
return Frame(uri, line, column, member);
});
/// Parses a string representation of a Chrome/V8 stack frame.
factory Frame.parseV8(String frame) => _catchFormatException(frame, () {
var match = _v8Frame.firstMatch(frame);
if (match == null) return UnparsedFrame(frame);
// v8 location strings can be arbitrarily-nested, since it adds a layer
// of nesting for each eval performed on that line.
Frame parseLocation(String location, String member) {
var evalMatch = _v8EvalLocation.firstMatch(location);
while (evalMatch != null) {
location = evalMatch[1];
evalMatch = _v8EvalLocation.firstMatch(location);
}
if (location == 'native') {
return Frame(Uri.parse('native'), null, null, member);
}
var urlMatch = _v8UrlLocation.firstMatch(location);
if (urlMatch == null) return UnparsedFrame(frame);
final uri = _uriOrPathToUri(urlMatch[1]);
final line = int.parse(urlMatch[2]);
final column = urlMatch[3] != null ? int.parse(urlMatch[3]) : null;
return Frame(uri, line, column, member);
}
// V8 stack frames can be in two forms.
if (match[2] != null) {
// The first form looks like " at FUNCTION (LOCATION)". V8 proper
// lists anonymous functions within eval as "<anonymous>", while IE10
// lists them as "Anonymous function".
return parseLocation(
match[2],
match[1]
.replaceAll('<anonymous>', '<fn>')
.replaceAll('Anonymous function', '<fn>')
.replaceAll('(anonymous function)', '<fn>'));
} else {
// The second form looks like " at LOCATION", and is used for
// anonymous functions.
return parseLocation(match[3], '<fn>');
}
});
/// Parses a string representation of a JavaScriptCore stack trace.
factory Frame.parseJSCore(String frame) => Frame.parseV8(frame);
/// Parses a string representation of an IE stack frame.
///
/// IE10+ frames look just like V8 frames. Prior to IE10, stack traces can't
/// be retrieved.
factory Frame.parseIE(String frame) => Frame.parseV8(frame);
/// Parses a Firefox 'eval' or 'function' stack frame.
///
/// for example:
/// anonymous/<@https://example.com/stuff.js line 693 > Function:3:40
/// anonymous/<@https://example.com/stuff.js line 693 > eval:3:40
factory Frame._parseFirefoxEval(String frame) =>
_catchFormatException(frame, () {
final match = _firefoxEvalLocation.firstMatch(frame);
if (match == null) return UnparsedFrame(frame);
var member = match[1].replaceAll('/<', '');
final uri = _uriOrPathToUri(match[2]);
final line = int.parse(match[3]);
if (member.isEmpty || member == 'anonymous') {
member = '<fn>';
}
return Frame(uri, line, null, member);
});
/// Parses a string representation of a Firefox stack frame.
factory Frame.parseFirefox(String frame) => _catchFormatException(frame, () {
var match = _firefoxSafariFrame.firstMatch(frame);
if (match == null) return UnparsedFrame(frame);
if (match[3].contains(' line ')) {
return Frame._parseFirefoxEval(frame);
}
// Normally this is a URI, but in a jsshell trace it can be a path.
var uri = _uriOrPathToUri(match[3]);
String member;
if (match[1] != null) {
member = match[1];
member +=
List.filled('/'.allMatches(match[2]).length, '.<fn>').join();
if (member == '') member = '<fn>';
// Some Firefox members have initial dots. We remove them for
// consistency with other platforms.
member = member.replaceFirst(_initialDot, '');
} else {
member = '<fn>';
}
var line = match[4] == '' ? null : int.parse(match[4]);
var column =
match[5] == null || match[5] == '' ? null : int.parse(match[5]);
return Frame(uri, line, column, member);
});
/// Parses a string representation of a Safari 6.0 stack frame.
@Deprecated('Use Frame.parseSafari instead.')
factory Frame.parseSafari6_0(String frame) => Frame.parseFirefox(frame);
/// Parses a string representation of a Safari 6.1+ stack frame.
@Deprecated('Use Frame.parseSafari instead.')
factory Frame.parseSafari6_1(String frame) => Frame.parseFirefox(frame);
/// Parses a string representation of a Safari stack frame.
factory Frame.parseSafari(String frame) => Frame.parseFirefox(frame);
/// Parses this package's string representation of a stack frame.
factory Frame.parseFriendly(String frame) => _catchFormatException(frame, () {
var match = _friendlyFrame.firstMatch(frame);
if (match == null) {
throw FormatException(
"Couldn't parse package:stack_trace stack trace line '$frame'.");
}
// Fake truncated data urls generated by the friendly stack trace format
// cause Uri.parse to throw an exception so we have to special case
// them.
var uri = match[1] == 'data:...'
? Uri.dataFromString('')
: Uri.parse(match[1]);
// If there's no scheme, this is a relative URI. We should interpret it
// as relative to the current working directory.
if (uri.scheme == '') {
uri = path.toUri(path.absolute(path.fromUri(uri)));
}
var line = match[2] == null ? null : int.parse(match[2]);
var column = match[3] == null ? null : int.parse(match[3]);
return Frame(uri, line, column, match[4]);
});
/// A regular expression matching an absolute URI.
static final _uriRegExp = RegExp(r'^[a-zA-Z][-+.a-zA-Z\d]*://');
/// A regular expression matching a Windows path.
static final _windowsRegExp = RegExp(r'^([a-zA-Z]:[\\/]|\\\\)');
/// Converts [uriOrPath], which can be a URI, a Windows path, or a Posix path,
/// to a URI (absolute if possible).
static Uri _uriOrPathToUri(String uriOrPath) {
if (uriOrPath.contains(_uriRegExp)) {
return Uri.parse(uriOrPath);
} else if (uriOrPath.contains(_windowsRegExp)) {
return Uri.file(uriOrPath, windows: true);
} else if (uriOrPath.startsWith('/')) {
return Uri.file(uriOrPath, windows: false);
}
// As far as I've seen, Firefox and V8 both always report absolute paths in
// their stack frames. However, if we do get a relative path, we should
// handle it gracefully.
if (uriOrPath.contains('\\')) return path.windows.toUri(uriOrPath);
return Uri.parse(uriOrPath);
}
/// Runs [body] and returns its result.
///
/// If [body] throws a [FormatException], returns an [UnparsedFrame] with
/// [text] instead.
static Frame _catchFormatException(String text, Frame Function() body) {
try {
return body();
} on FormatException catch (_) {
return UnparsedFrame(text);
}
}
Frame(this.uri, this.line, this.column, this.member);
@override
String toString() => '$location in $member';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/lazy_chain.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'chain.dart';
import 'frame.dart';
import 'lazy_trace.dart';
import 'trace.dart';
/// A thunk for lazily constructing a [Chain].
typedef ChainThunk = Chain Function();
/// A wrapper around a [ChainThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyChain implements Chain {
final ChainThunk _thunk;
Chain _inner;
LazyChain(this._thunk);
Chain get _chain => _inner ??= _thunk();
@override
List<Trace> get traces => _chain.traces;
@override
Chain get terse => _chain.terse;
@override
Chain foldFrames(bool Function(Frame) predicate, {bool terse = false}) =>
LazyChain(() => _chain.foldFrames(predicate, terse: terse));
@override
Trace toTrace() => LazyTrace(() => _chain.toTrace());
@override
String toString() => _chain.toString();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/vm_trace.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'frame.dart';
/// An implementation of [StackTrace] that emulates the behavior of the VM's
/// implementation.
///
/// In particular, when [toString] is called, this returns a string in the VM's
/// stack trace format.
class VMTrace implements StackTrace {
/// The stack frames that comprise this stack trace.
final List<Frame> frames;
VMTrace(this.frames);
@override
String toString() {
var i = 1;
return frames.map((frame) {
var number = '#${i++}'.padRight(8);
var member = frame.member
.replaceAllMapped(RegExp(r'[^.]+\.<async>'),
(match) => '${match[1]}.<${match[1]}_async_body>')
.replaceAll('<fn>', '<anonymous closure>');
var line = frame.line ?? 0;
var column = frame.column ?? 0;
return '$number$member (${frame.uri}:$line:$column)\n';
}).join();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/trace.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:math' as math;
import 'chain.dart';
import 'frame.dart';
import 'lazy_trace.dart';
import 'unparsed_frame.dart';
import 'utils.dart';
import 'vm_trace.dart';
final _terseRegExp = RegExp(r'(-patch)?([/\\].*)?$');
/// A RegExp to match V8's stack traces.
///
/// V8's traces start with a line that's either just "Error" or else is a
/// description of the exception that occurred. That description can be multiple
/// lines, so we just look for any line other than the first that begins with
/// three or four spaces and "at".
final _v8Trace = RegExp(r'\n ?at ');
/// A RegExp to match indidual lines of V8's stack traces.
///
/// This is intended to filter out the leading exception details of the trace
/// though it is possible for the message to match this as well.
final _v8TraceLine = RegExp(r' ?at ');
/// A RegExp to match Firefox's eval and Function stack traces.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
///
/// These stack traces looks like:
/// anonymous/<@https://example.com/stuff.js line 693 > Function:3:40
/// anonymous/<@https://example.com/stuff.js line 693 > eval:3:40
final _firefoxEvalTrace = RegExp(r'@\S+ line \d+ >.* (Function|eval):\d+:\d+');
/// A RegExp to match Firefox and Safari's stack traces.
///
/// Firefox and Safari have very similar stack trace formats, so we use the same
/// logic for parsing them.
///
/// Firefox's trace frames start with the name of the function in which the
/// error occurred, possibly including its parameters inside `()`. For example,
/// `.VW.call$0("arg")@https://example.com/stuff.dart.js:560`.
///
/// Safari traces occasionally don't include the initial method name followed by
/// "@", and they always have both the line and column number (or just a
/// trailing colon if no column number is available). They can also contain
/// empty lines or lines consisting only of `[native code]`.
final _firefoxSafariTrace = RegExp(
r'^'
r'(' // Member description. Not present in some Safari frames.
r'([.0-9A-Za-z_$/<]|\(.*\))*' // Member name and arguments.
r'@'
r')?'
r'[^\s]*' // Frame URL.
r':\d*' // Line or column number. Some older frames only have a line number.
r'$',
multiLine: true);
/// A RegExp to match this package's stack traces.
final _friendlyTrace =
RegExp(r'^[^\s<][^\s]*( \d+(:\d+)?)?[ \t]+[^\s]+$', multiLine: true);
/// A stack trace, comprised of a list of stack frames.
class Trace implements StackTrace {
/// The stack frames that comprise this stack trace.
final List<Frame> frames;
/// The original stack trace from which this trace was parsed.
final StackTrace original;
/// Returns a human-readable representation of [stackTrace]. If [terse] is
/// set, this folds together multiple stack frames from the Dart core
/// libraries, so that only the core library method directly called from user
/// code is visible (see [Trace.terse]).
static String format(StackTrace stackTrace, {bool terse = true}) {
var trace = Trace.from(stackTrace);
if (terse) trace = trace.terse;
return trace.toString();
}
/// Returns the current stack trace.
///
/// By default, the first frame of this trace will be the line where
/// [Trace.current] is called. If [level] is passed, the trace will start that
/// many frames up instead.
factory Trace.current([int level = 0]) {
if (level < 0) {
throw ArgumentError('Argument [level] must be greater than or equal '
'to 0.');
}
var trace = Trace.from(StackTrace.current);
return LazyTrace(() {
// JS includes a frame for the call to StackTrace.current, but the VM
// doesn't, so we skip an extra frame in a JS context.
return Trace(trace.frames.skip(level + (inJS ? 2 : 1)),
original: trace.original.toString());
});
}
/// Returns a new stack trace containing the same data as [trace].
///
/// If [trace] is a native [StackTrace], its data will be parsed out; if it's
/// a [Trace], it will be returned as-is.
factory Trace.from(StackTrace trace) {
// Normally explicitly validating null arguments is bad Dart style, but here
// the natural failure will only occur when the LazyTrace is materialized,
// and we want to provide an error that's more local to the actual problem.
if (trace == null) {
throw ArgumentError('Cannot create a Trace from null.');
}
if (trace is Trace) return trace;
if (trace is Chain) return trace.toTrace();
return LazyTrace(() => Trace.parse(trace.toString()));
}
/// Parses a string representation of a stack trace.
///
/// [trace] should be formatted in the same way as a Dart VM or browser stack
/// trace. If it's formatted as a stack chain, this will return the equivalent
/// of [Chain.toTrace].
factory Trace.parse(String trace) {
try {
if (trace.isEmpty) return Trace(<Frame>[]);
if (trace.contains(_v8Trace)) return Trace.parseV8(trace);
if (trace.contains('\tat ')) return Trace.parseJSCore(trace);
if (trace.contains(_firefoxSafariTrace) ||
trace.contains(_firefoxEvalTrace)) {
return Trace.parseFirefox(trace);
}
if (trace.contains(chainGap)) return Chain.parse(trace).toTrace();
if (trace.contains(_friendlyTrace)) {
return Trace.parseFriendly(trace);
}
// Default to parsing the stack trace as a VM trace. This is also hit on
// IE and Safari, where the stack trace is just an empty string (issue
// 11257).
return Trace.parseVM(trace);
} on FormatException catch (error) {
throw FormatException('${error.message}\nStack trace:\n$trace');
}
}
/// Parses a string representation of a Dart VM stack trace.
Trace.parseVM(String trace) : this(_parseVM(trace), original: trace);
static List<Frame> _parseVM(String trace) {
// Ignore [vmChainGap]. This matches the behavior of
// `Chain.parse().toTrace()`.
var lines = trace
.trim()
.replaceAll(vmChainGap, '')
.split('\n')
.where((line) => line.isNotEmpty);
if (lines.isEmpty) {
return [];
}
var frames = lines
.take(lines.length - 1)
.map((line) => Frame.parseVM(line))
.toList();
// TODO(nweiz): Remove this when issue 23614 is fixed.
if (!lines.last.endsWith('.da')) {
frames.add(Frame.parseVM(lines.last));
}
return frames;
}
/// Parses a string representation of a Chrome/V8 stack trace.
Trace.parseV8(String trace)
: this(
trace
.split('\n')
.skip(1)
// It's possible that an Exception's description contains a line
// that looks like a V8 trace line, which will screw this up.
// Unfortunately, that's impossible to detect.
.skipWhile((line) => !line.startsWith(_v8TraceLine))
.map((line) => Frame.parseV8(line)),
original: trace);
/// Parses a string representation of a JavaScriptCore stack trace.
Trace.parseJSCore(String trace)
: this(
trace
.split('\n')
.where((line) => line != '\tat ')
.map((line) => Frame.parseV8(line)),
original: trace);
/// Parses a string representation of an Internet Explorer stack trace.
///
/// IE10+ traces look just like V8 traces. Prior to IE10, stack traces can't
/// be retrieved.
Trace.parseIE(String trace) : this.parseV8(trace);
/// Parses a string representation of a Firefox stack trace.
Trace.parseFirefox(String trace)
: this(
trace
.trim()
.split('\n')
.where((line) => line.isNotEmpty && line != '[native code]')
.map((line) => Frame.parseFirefox(line)),
original: trace);
/// Parses a string representation of a Safari stack trace.
Trace.parseSafari(String trace) : this.parseFirefox(trace);
/// Parses a string representation of a Safari 6.1+ stack trace.
@Deprecated('Use Trace.parseSafari instead.')
Trace.parseSafari6_1(String trace) : this.parseSafari(trace);
/// Parses a string representation of a Safari 6.0 stack trace.
@Deprecated('Use Trace.parseSafari instead.')
Trace.parseSafari6_0(String trace)
: this(
trace
.trim()
.split('\n')
.where((line) => line != '[native code]')
.map((line) => Frame.parseFirefox(line)),
original: trace);
/// Parses this package's string representation of a stack trace.
///
/// This also parses string representations of [Chain]s. They parse to the
/// same trace that [Chain.toTrace] would return.
Trace.parseFriendly(String trace)
: this(
trace.isEmpty
? []
: trace
.trim()
.split('\n')
// Filter out asynchronous gaps from [Chain]s.
.where((line) => !line.startsWith('====='))
.map((line) => Frame.parseFriendly(line)),
original: trace);
/// Returns a new [Trace] comprised of [frames].
Trace(Iterable<Frame> frames, {String original})
: frames = List<Frame>.unmodifiable(frames),
original = StackTrace.fromString(original);
/// Returns a VM-style [StackTrace] object.
///
/// The return value's [toString] method will always return a string
/// representation in the Dart VM's stack trace format, regardless of what
/// platform is being used.
StackTrace get vmTrace => VMTrace(frames);
/// Returns a terser version of [this].
///
/// This is accomplished by folding together multiple stack frames from the
/// core library or from this package, as in [foldFrames]. Remaining core
/// library frames have their libraries, "-patch" suffixes, and line numbers
/// removed. If the outermost frame of the stack trace is a core library
/// frame, it's removed entirely.
///
/// This won't do anything with a raw JavaScript trace, since there's no way
/// to determine which frames come from which Dart libraries. However, the
/// [`source_map_stack_trace`][source_map_stack_trace] package can be used to
/// convert JavaScript traces into Dart-style traces.
///
/// [source_map_stack_trace]: https://pub.dev/packages/source_map_stack_trace
///
/// For custom folding, see [foldFrames].
Trace get terse => foldFrames((_) => false, terse: true);
/// Returns a new [Trace] based on [this] where multiple stack frames matching
/// [predicate] are folded together.
///
/// This means that whenever there are multiple frames in a row that match
/// [predicate], only the last one is kept. This is useful for limiting the
/// amount of library code that appears in a stack trace by only showing user
/// code and code that's called by user code.
///
/// If [terse] is true, this will also fold together frames from the core
/// library or from this package, simplify core library frames, and
/// potentially remove the outermost frame as in [Trace.terse].
Trace foldFrames(bool Function(Frame) predicate, {bool terse = false}) {
if (terse) {
var oldPredicate = predicate;
predicate = (frame) {
if (oldPredicate(frame)) return true;
if (frame.isCore) return true;
if (frame.package == 'stack_trace') return true;
// Ignore async stack frames without any line or column information.
// These come from the VM's async/await implementation and represent
// internal frames. They only ever show up in stack chains and are
// always surrounded by other traces that are actually useful, so we can
// just get rid of them.
// TODO(nweiz): Get rid of this logic some time after issue 22009 is
// fixed.
if (!frame.member.contains('<async>')) return false;
return frame.line == null;
};
}
var newFrames = <Frame>[];
for (var frame in frames.reversed) {
if (frame is UnparsedFrame || !predicate(frame)) {
newFrames.add(frame);
} else if (newFrames.isEmpty || !predicate(newFrames.last)) {
newFrames.add(Frame(frame.uri, frame.line, frame.column, frame.member));
}
}
if (terse) {
newFrames = newFrames.map((frame) {
if (frame is UnparsedFrame || !predicate(frame)) return frame;
var library = frame.library.replaceAll(_terseRegExp, '');
return Frame(Uri.parse(library), null, null, frame.member);
}).toList();
if (newFrames.length > 1 && predicate(newFrames.first)) {
newFrames.removeAt(0);
}
}
return Trace(newFrames.reversed, original: original.toString());
}
@override
String toString() {
// Figure out the longest path so we know how much to pad.
var longest =
frames.map((frame) => frame.location.length).fold(0, math.max);
// Print out the stack trace nicely formatted.
return frames.map((frame) {
if (frame is UnparsedFrame) return '$frame\n';
return '${frame.location.padRight(longest)} ${frame.member}\n';
}).join();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/lazy_trace.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'frame.dart';
import 'trace.dart';
/// A thunk for lazily constructing a [Trace].
typedef TraceThunk = Trace Function();
/// A wrapper around a [TraceThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyTrace implements Trace {
final TraceThunk _thunk;
Trace _inner;
LazyTrace(this._thunk);
Trace get _trace => _inner ??= _thunk();
@override
List<Frame> get frames => _trace.frames;
@override
StackTrace get original => _trace.original;
@override
StackTrace get vmTrace => _trace.vmTrace;
@override
Trace get terse => LazyTrace(() => _trace.terse);
@override
Trace foldFrames(bool Function(Frame) predicate, {bool terse = false}) =>
LazyTrace(() => _trace.foldFrames(predicate, terse: terse));
@override
String toString() => _trace.toString();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/utils.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// The line used in the string representation of stack chains to represent
/// the gap between traces.
const chainGap = '===== asynchronous gap ===========================\n';
/// The line used in the string representation of VM stack chains to represent
/// the gap between traces.
final vmChainGap = RegExp(r'^<asynchronous suspension>\n?$', multiLine: true);
// TODO(nweiz): When cross-platform imports work, use them to set this.
/// Whether we're running in a JS context.
final bool inJS = 0.0 is int;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/stack_zone_specification.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'chain.dart';
import 'lazy_chain.dart';
import 'lazy_trace.dart';
import 'trace.dart';
import 'utils.dart';
/// A class encapsulating the zone specification for a [Chain.capture] zone.
///
/// Until they're materialized and exposed to the user, stack chains are tracked
/// as linked lists of [Trace]s using the [_Node] class. These nodes are stored
/// in three distinct ways:
///
/// * When a callback is registered, a node is created and stored as a captured
/// local variable until the callback is run.
///
/// * When a callback is run, its captured node is set as the [_currentNode] so
/// it can be available to [Chain.current] and to be linked into additional
/// chains when more callbacks are scheduled.
///
/// * When a callback throws an error or a Future or Stream emits an error, the
/// current node is associated with that error's stack trace using the
/// [_chains] expando.
///
/// Since [ZoneSpecification] can't be extended or even implemented, in order to
/// get a real [ZoneSpecification] instance it's necessary to call [toSpec].
class StackZoneSpecification {
/// An opaque object used as a zone value to disable chain tracking in a given
/// zone.
///
/// If `Zone.current[disableKey]` is `true`, no stack chains will be tracked.
static final disableKey = Object();
/// Whether chain-tracking is disabled in the current zone.
bool get _disabled => Zone.current[disableKey] == true;
/// The expando that associates stack chains with [StackTrace]s.
///
/// The chains are associated with stack traces rather than errors themselves
/// because it's a common practice to throw strings as errors, which can't be
/// used with expandos.
///
/// The chain associated with a given stack trace doesn't contain a node for
/// that stack trace.
final _chains = Expando<_Node>('stack chains');
/// The error handler for the zone.
///
/// If this is null, that indicates that any unhandled errors should be passed
/// to the parent zone.
final void Function(Object error, Chain) _onError;
/// The most recent node of the current stack chain.
_Node _currentNode;
/// Whether this is an error zone.
final bool _errorZone;
StackZoneSpecification(this._onError, {bool errorZone = true})
: _errorZone = errorZone;
/// Converts [this] to a real [ZoneSpecification].
ZoneSpecification toSpec() {
return ZoneSpecification(
handleUncaughtError: _errorZone ? _handleUncaughtError : null,
registerCallback: _registerCallback,
registerUnaryCallback: _registerUnaryCallback,
registerBinaryCallback: _registerBinaryCallback,
errorCallback: _errorCallback);
}
/// Returns the current stack chain.
///
/// By default, the first frame of the first trace will be the line where
/// [currentChain] is called. If [level] is passed, the first trace will start
/// that many frames up instead.
Chain currentChain([int level = 0]) => _createNode(level + 1).toChain();
/// Returns the stack chain associated with [trace], if one exists.
///
/// The first stack trace in the returned chain will always be [trace]
/// (converted to a [Trace] if necessary). If there is no chain associated
/// with [trace], this just returns a single-trace chain containing [trace].
Chain chainFor(StackTrace trace) {
if (trace is Chain) return trace;
trace ??= StackTrace.current;
var previous = _chains[trace] ?? _currentNode;
if (previous == null) {
// If there's no [_currentNode], we're running synchronously beneath
// [Chain.capture] and we should fall back to the VM's stack chaining. We
// can't use [Chain.from] here because it'll just call [chainFor] again.
if (trace is Trace) return Chain([trace]);
return LazyChain(() => Chain.parse(trace.toString()));
} else {
if (trace is! Trace) {
var original = trace;
trace = LazyTrace(() => Trace.parse(_trimVMChain(original)));
}
return _Node(trace, previous).toChain();
}
}
/// Tracks the current stack chain so it can be set to [_currentChain] when
/// [f] is run.
ZoneCallback<R> _registerCallback<R>(
Zone self, ZoneDelegate parent, Zone zone, R Function() f) {
if (f == null || _disabled) return parent.registerCallback(zone, f);
var node = _createNode(1);
return parent.registerCallback(zone, () => _run(f, node));
}
/// Tracks the current stack chain so it can be set to [_currentChain] when
/// [f] is run.
ZoneUnaryCallback<R, T> _registerUnaryCallback<R, T>(
Zone self, ZoneDelegate parent, Zone zone, R Function(T) f) {
if (f == null || _disabled) return parent.registerUnaryCallback(zone, f);
var node = _createNode(1);
return parent.registerUnaryCallback(zone, (arg) {
return _run(() => f(arg), node);
});
}
/// Tracks the current stack chain so it can be set to [_currentChain] when
/// [f] is run.
ZoneBinaryCallback<R, T1, T2> _registerBinaryCallback<R, T1, T2>(
Zone self, ZoneDelegate parent, Zone zone, R Function(T1, T2) f) {
if (f == null || _disabled) return parent.registerBinaryCallback(zone, f);
var node = _createNode(1);
return parent.registerBinaryCallback(zone, (arg1, arg2) {
return _run(() => f(arg1, arg2), node);
});
}
/// Looks up the chain associated with [stackTrace] and passes it either to
/// [_onError] or [parent]'s error handler.
void _handleUncaughtError(
Zone self, ZoneDelegate parent, Zone zone, error, StackTrace stackTrace) {
if (_disabled) {
parent.handleUncaughtError(zone, error, stackTrace);
return;
}
var stackChain = chainFor(stackTrace);
if (_onError == null) {
parent.handleUncaughtError(zone, error, stackChain);
return;
}
// TODO(nweiz): Currently this copies a lot of logic from [runZoned]. Just
// allow [runBinary] to throw instead once issue 18134 is fixed.
try {
self.parent.runBinary(_onError, error, stackChain);
} catch (newError, newStackTrace) {
if (identical(newError, error)) {
parent.handleUncaughtError(zone, error, stackChain);
} else {
parent.handleUncaughtError(zone, newError, newStackTrace);
}
}
}
/// Attaches the current stack chain to [stackTrace], replacing it if
/// necessary.
AsyncError _errorCallback(Zone self, ZoneDelegate parent, Zone zone,
Object error, StackTrace stackTrace) {
if (_disabled) return parent.errorCallback(zone, error, stackTrace);
// Go up two levels to get through [_CustomZone.errorCallback].
if (stackTrace == null) {
stackTrace = _createNode(2).toChain();
} else {
if (_chains[stackTrace] == null) _chains[stackTrace] = _createNode(2);
}
var asyncError = parent.errorCallback(zone, error, stackTrace);
return asyncError ?? AsyncError(error, stackTrace);
}
/// Creates a [_Node] with the current stack trace and linked to
/// [_currentNode].
///
/// By default, the first frame of the first trace will be the line where
/// [_createNode] is called. If [level] is passed, the first trace will start
/// that many frames up instead.
_Node _createNode([int level = 0]) =>
_Node(_currentTrace(level + 1), _currentNode);
// TODO(nweiz): use a more robust way of detecting and tracking errors when
// issue 15105 is fixed.
/// Runs [f] with [_currentNode] set to [node].
///
/// If [f] throws an error, this associates [node] with that error's stack
/// trace.
T _run<T>(T Function() f, _Node node) {
var previousNode = _currentNode;
_currentNode = node;
try {
return f();
} catch (e, stackTrace) {
// We can see the same stack trace multiple times if it's rethrown through
// guarded callbacks. The innermost chain will have the most
// information so it should take precedence.
_chains[stackTrace] ??= node;
rethrow;
} finally {
_currentNode = previousNode;
}
}
/// Like [new Trace.current], but if the current stack trace has VM chaining
/// enabled, this only returns the innermost sub-trace.
Trace _currentTrace([int level]) {
level ??= 0;
var stackTrace = StackTrace.current;
return LazyTrace(() {
var text = _trimVMChain(stackTrace);
var trace = Trace.parse(text);
// JS includes a frame for the call to StackTrace.current, but the VM
// doesn't, so we skip an extra frame in a JS context.
return Trace(trace.frames.skip(level + (inJS ? 2 : 1)), original: text);
});
}
/// Removes the VM's stack chains from the native [trace], since we're
/// generating our own and we don't want duplicate frames.
String _trimVMChain(StackTrace trace) {
var text = trace.toString();
var index = text.indexOf(vmChainGap);
return index == -1 ? text : text.substring(0, index);
}
}
/// A linked list node representing a single entry in a stack chain.
class _Node {
/// The stack trace for this link of the chain.
final Trace trace;
/// The previous node in the chain.
final _Node previous;
_Node(StackTrace trace, [this.previous]) : trace = Trace.from(trace);
/// Converts this to a [Chain].
Chain toChain() {
var nodes = <Trace>[];
var node = this;
while (node != null) {
nodes.add(node.trace);
node = node.previous;
}
return Chain(nodes);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/stack_trace/src/chain.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'frame.dart';
import 'lazy_chain.dart';
import 'stack_zone_specification.dart';
import 'trace.dart';
import 'utils.dart';
/// A function that handles errors in the zone wrapped by [Chain.capture].
@Deprecated('Will be removed in stack_trace 2.0.0.')
typedef ChainHandler = void Function(dynamic error, Chain chain);
/// An opaque key used to track the current [StackZoneSpecification].
final _specKey = Object();
/// A chain of stack traces.
///
/// A stack chain is a collection of one or more stack traces that collectively
/// represent the path from [main] through nested function calls to a particular
/// code location, usually where an error was thrown. Multiple stack traces are
/// necessary when using asynchronous functions, since the program's stack is
/// reset before each asynchronous callback is run.
///
/// Stack chains can be automatically tracked using [Chain.capture]. This sets
/// up a new [Zone] in which the current stack chain is tracked and can be
/// accessed using [new Chain.current]. Any errors that would be top-leveled in
/// the zone can be handled, along with their associated chains, with the
/// `onError` callback. For example:
///
/// Chain.capture(() {
/// // ...
/// }, onError: (error, stackChain) {
/// print("Caught error $error\n"
/// "$stackChain");
/// });
class Chain implements StackTrace {
/// The stack traces that make up this chain.
///
/// Like the frames in a stack trace, the traces are ordered from most local
/// to least local. The first one is the trace where the actual exception was
/// raised, the second one is where that callback was scheduled, and so on.
final List<Trace> traces;
/// The [StackZoneSpecification] for the current zone.
static StackZoneSpecification get _currentSpec =>
Zone.current[_specKey] as StackZoneSpecification;
/// If [when] is `true`, runs [callback] in a [Zone] in which the current
/// stack chain is tracked and automatically associated with (most) errors.
///
/// If [when] is `false`, this does not track stack chains. Instead, it's
/// identical to [runZoned], except that it wraps any errors in [new
/// Chain.forTrace]—which will only wrap the trace unless there's a different
/// [Chain.capture] active. This makes it easy for the caller to only capture
/// stack chains in debug mode or during development.
///
/// If [onError] is passed, any error in the zone that would otherwise go
/// unhandled is passed to it, along with the [Chain] associated with that
/// error. Note that if [callback] produces multiple unhandled errors,
/// [onError] may be called more than once. If [onError] isn't passed, the
/// parent Zone's `unhandledErrorHandler` will be called with the error and
/// its chain.
///
/// If [errorZone] is `true`, the zone this creates will be an error zone,
/// even if [onError] isn't passed. This means that any errors that would
/// cross the zone boundary are considered unhandled. If [errorZone] is
/// `false`, [onError] must be `null`.
///
/// If [callback] returns a value, it will be returned by [capture] as well.
static T capture<T>(T Function() callback,
{void Function(Object error, Chain) onError,
bool when = true,
bool errorZone = true}) {
if (!errorZone && onError != null) {
throw ArgumentError.value(
onError, 'onError', 'must be null if errorZone is false');
}
if (!when) {
void Function(Object, StackTrace) newOnError;
if (onError != null) {
newOnError = (error, stackTrace) {
onError(
error,
stackTrace == null
? Chain.current()
: Chain.forTrace(stackTrace));
};
}
return runZoned(callback, onError: newOnError);
}
var spec = StackZoneSpecification(onError, errorZone: errorZone);
return runZoned(() {
try {
return callback();
} catch (error, stackTrace) {
// TODO(nweiz): Don't special-case this when issue 19566 is fixed.
Zone.current.handleUncaughtError(error, stackTrace);
return null;
}
},
zoneSpecification: spec.toSpec(),
zoneValues: {_specKey: spec, StackZoneSpecification.disableKey: false});
}
/// If [when] is `true` and this is called within a [Chain.capture] zone, runs
/// [callback] in a [Zone] in which chain capturing is disabled.
///
/// If [callback] returns a value, it will be returned by [disable] as well.
static T disable<T>(T Function() callback, {bool when = true}) {
var zoneValues =
when ? {_specKey: null, StackZoneSpecification.disableKey: true} : null;
return runZoned(callback, zoneValues: zoneValues);
}
/// Returns [futureOrStream] unmodified.
///
/// Prior to Dart 1.7, this was necessary to ensure that stack traces for
/// exceptions reported with [Completer.completeError] and
/// [StreamController.addError] were tracked correctly.
@Deprecated('Chain.track is not necessary in Dart 1.7+.')
static dynamic track(futureOrStream) => futureOrStream;
/// Returns the current stack chain.
///
/// By default, the first frame of the first trace will be the line where
/// [Chain.current] is called. If [level] is passed, the first trace will
/// start that many frames up instead.
///
/// If this is called outside of a [capture] zone, it just returns a
/// single-trace chain.
factory Chain.current([int level = 0]) {
if (_currentSpec != null) return _currentSpec.currentChain(level + 1);
var chain = Chain.forTrace(StackTrace.current);
return LazyChain(() {
// JS includes a frame for the call to StackTrace.current, but the VM
// doesn't, so we skip an extra frame in a JS context.
var first = Trace(chain.traces.first.frames.skip(level + (inJS ? 2 : 1)),
original: chain.traces.first.original.toString());
return Chain([first]..addAll(chain.traces.skip(1)));
});
}
/// Returns the stack chain associated with [trace].
///
/// The first stack trace in the returned chain will always be [trace]
/// (converted to a [Trace] if necessary). If there is no chain associated
/// with [trace] or if this is called outside of a [capture] zone, this just
/// returns a single-trace chain containing [trace].
///
/// If [trace] is already a [Chain], it will be returned as-is.
factory Chain.forTrace(StackTrace trace) {
if (trace is Chain) return trace;
if (_currentSpec != null) return _currentSpec.chainFor(trace);
if (trace is Trace) return Chain([trace]);
return LazyChain(() => Chain.parse(trace.toString()));
}
/// Parses a string representation of a stack chain.
///
/// If [chain] is the output of a call to [Chain.toString], it will be parsed
/// as a full stack chain. Otherwise, it will be parsed as in [Trace.parse]
/// and returned as a single-trace chain.
factory Chain.parse(String chain) {
if (chain.isEmpty) return Chain([]);
if (chain.contains(vmChainGap)) {
return Chain(chain
.split(vmChainGap)
.where((line) => line.isNotEmpty)
.map((trace) => Trace.parseVM(trace)));
}
if (!chain.contains(chainGap)) return Chain([Trace.parse(chain)]);
return Chain(
chain.split(chainGap).map((trace) => Trace.parseFriendly(trace)));
}
/// Returns a new [Chain] comprised of [traces].
Chain(Iterable<Trace> traces) : traces = List<Trace>.unmodifiable(traces);
/// Returns a terser version of [this].
///
/// This calls [Trace.terse] on every trace in [traces], and discards any
/// trace that contain only internal frames.
///
/// This won't do anything with a raw JavaScript trace, since there's no way
/// to determine which frames come from which Dart libraries. However, the
/// [`source_map_stack_trace`][source_map_stack_trace] package can be used to
/// convert JavaScript traces into Dart-style traces.
///
/// [source_map_stack_trace]: https://pub.dev/packages/source_map_stack_trace
Chain get terse => foldFrames((_) => false, terse: true);
/// Returns a new [Chain] based on [this] where multiple stack frames matching
/// [predicate] are folded together.
///
/// This means that whenever there are multiple frames in a row that match
/// [predicate], only the last one is kept. In addition, traces that are
/// composed entirely of frames matching [predicate] are omitted.
///
/// This is useful for limiting the amount of library code that appears in a
/// stack trace by only showing user code and code that's called by user code.
///
/// If [terse] is true, this will also fold together frames from the core
/// library or from this package, and simplify core library frames as in
/// [Trace.terse].
Chain foldFrames(bool Function(Frame) predicate, {bool terse = false}) {
var foldedTraces =
traces.map((trace) => trace.foldFrames(predicate, terse: terse));
var nonEmptyTraces = foldedTraces.where((trace) {
// Ignore traces that contain only folded frames.
if (trace.frames.length > 1) return true;
if (trace.frames.isEmpty) return false;
// In terse mode, the trace may have removed an outer folded frame,
// leaving a single non-folded frame. We can detect a folded frame because
// it has no line information.
if (!terse) return false;
return trace.frames.single.line != null;
});
// If all the traces contain only internal processing, preserve the last
// (top-most) one so that the chain isn't empty.
if (nonEmptyTraces.isEmpty && foldedTraces.isNotEmpty) {
return Chain([foldedTraces.last]);
}
return Chain(nonEmptyTraces);
}
/// Converts [this] to a [Trace].
///
/// The trace version of a chain is just the concatenation of all the traces
/// in the chain.
Trace toTrace() => Trace(traces.expand((trace) => trace.frames));
@override
String toString() {
// Figure out the longest path so we know how much to pad.
var longest = traces.map((trace) {
return trace.frames
.map((frame) => frame.location.length)
.fold(0, math.max);
}).fold(0, math.max);
// Don't call out to [Trace.toString] here because that doesn't ensure that
// padding is consistent across all traces.
return traces.map((trace) {
return trace.frames.map((frame) {
return '${frame.location.padRight(longest)} ${frame.member}\n';
}).join();
}).join(chainGap);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/net.dart | // Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node.js "net" module.
///
/// Use library-level [net] object to access this module functionality.
@JS()
library node_interop.net;
import 'package:js/js.dart';
import 'events.dart';
import 'node.dart';
import 'stream.dart';
Net get net => _net ??= require('net');
Net _net;
@JS()
@anonymous
abstract class Net {
/// Alias to [createConnection].
external Socket connect(arg1, [arg2, arg3]);
/// See official documentation for possible signatures:
/// - https://nodejs.org/api/net.html#net_net_createconnection
external Socket createConnection(arg1, [arg2, arg3]);
external Socket createServer([options, void Function() connectionListener]);
external num isIP(String input);
external bool isIPv4(String input);
external bool isIPv6(String input);
}
@JS()
@anonymous
abstract class Socket implements Duplex, EventEmitter {
external NetAddress address();
external int get bufferSize;
external int get bytesRead;
external int get bytesWritten;
/// See official documentation on possible signatures:
/// - https://nodejs.org/api/net.html#net_socket_connect
external Socket connect(arg1, [arg2, arg3]);
external bool get connecting;
@override
external Socket destroy([exception]);
external bool get destroyed;
@override
external Socket end([data, encoding, unused]);
external String get localAddress;
external String get localFamily;
external int get localPort;
@override
external Socket pause();
external Socket ref();
external String get remoteAddress;
external String get remoteFamily;
external int get remotePort;
@override
external Socket resume();
@override
external Socket setEncoding([encoding]);
external Socket setKeepAlive([bool enable, initialDelay]);
external Socket setNoDelay([bool noDelay]);
external Socket setTimeout(timeout, [void Function() callback]);
external Socket unref();
@override
external bool write(chunk, [encodingOrCallback, callback]);
}
@JS()
@anonymous
abstract class NetAddress {
external int get port;
external String get family;
external String get address;
}
@JS()
@anonymous
abstract class NetServer implements EventEmitter {
external NetAddress address();
external NetServer close([void Function() callback]);
external void getConnections(
[void Function(dynamic error, int count) callback]);
/// See official documentation on possible signatures:
/// - https://nodejs.org/api/net.html#net_server_listen
external void listen([arg1, arg2, arg3, arg4]);
external bool get listening;
external int get maxConnections;
external NetServer ref();
external NetServer unref();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/path.dart | // Copyright (c) 2018, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node "path" module bindings.
///
/// Use top-level [path] object to access functionality of this module.
@JS()
library node_interop.path;
import 'package:js/js.dart';
import 'node.dart';
Path get path => _path ??= require('path');
Path _path;
@JS()
@anonymous
abstract class Path {
external String get delimiter;
external String get sep;
external Path get win32;
external Path get posix;
external String basename(String path, [String ext]);
external String dirname(String path);
external String extname(String path);
external String format(PathObject path);
external bool isAbsolute(String path);
external String join(String arg1,
[String arg2, String arg3, String arg4, String arg5]);
external String normalize(String path);
external PathObject parse(String path);
external String relative(String from, String to);
external String resolve(
[String arg1, String arg2, String arg3, String arg4, String arg5]);
external String toNamespacedPath(String path);
}
@JS()
@anonymous
abstract class PathObject {
external factory PathObject(
{String dir, String root, String base, String name, String ext});
external String get dir;
external String get root;
external String get base;
external String get name;
external String get ext;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/stream.dart | // Copyright (c) 2018, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node.js "stream" module bindings.
@JS()
library node_interop.stream;
import 'dart:js_util';
import 'package:js/js.dart';
import 'events.dart';
import 'node.dart';
/// The "stream" module's object as returned from [require] call.
StreamModule get stream => _stream ??= require('stream');
StreamModule _stream;
@JS()
@anonymous
abstract class StreamModule {
/// Reference to constructor function of [Writable].
Function get Writable;
/// Reference to constructor function of [Readable].
Function get Readable;
}
/// Creates custom [Writable] stream with provided [options].
///
/// This is the same as `callConstructor(stream.Writable, [options]);`.
Writable createWritable(WritableOptions options) {
return callConstructor(stream.Writable, [options]);
}
/// Creates custom [Readable] stream with provided [options].
///
/// This is the same as `callConstructor(stream.Readable, [options]);`.
Readable createReadable(ReadableOptions options) {
return callConstructor(stream.Readable, [options]);
}
@JS()
@anonymous
abstract class Readable implements EventEmitter {
external bool isPaused();
external Readable pause();
external Writable pipe(Writable destination, [options]);
external int get readableHighWaterMark;
external dynamic read([int size]);
external int get readableLength;
external Readable resume();
external void setEncoding(String encoding);
external void unpipe([Writable destination]);
external void unshift(chunk);
external void wrap(stream);
external void destroy([error]);
external bool push(chunk, [encoding]);
}
@JS()
@anonymous
abstract class Writable implements EventEmitter {
external void cork();
external void end([data, encodingOrCallback, void Function() callback]);
external void setDefaultEncoding(String encoding);
external void uncork();
external int get writableHighWaterMark;
external int get writableLength;
external /*bool*/ dynamic write(chunk,
[encodingOrCallback, void Function() callback]);
external Writable destroy([error]);
}
/// Duplex streams are streams that implement both the [Readable] and [Writable]
/// interfaces.
@JS()
@anonymous
abstract class Duplex implements Readable, Writable {}
/// Transform streams are [Duplex] streams where the output is in some way
/// related to the input.
@JS()
@anonymous
abstract class Transform implements Duplex {}
@JS()
@anonymous
abstract class WritableOptions {
external factory WritableOptions({
int highWaterMark,
bool decodeStrings,
bool objectMode,
Function write,
Function writev,
Function destroy,
});
int get highWaterMark;
bool get decodeStrings;
bool get objectMode;
Function get write;
Function get writev;
Function get destroy;
// Function get final; // Unsupported: final is reserved word in Dart.
}
@JS()
@anonymous
abstract class ReadableOptions {
external factory ReadableOptions({
int highWaterMark,
String encoding,
bool objectMode,
Function read,
Function destroy,
});
int get highWaterMark;
String get encoding;
bool get objectMode;
Function get read;
Function get destroy;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/util.dart | // Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Utility functions for Dart <> JS interoperability.
@JS()
library node_interop.util;
import 'dart:async';
import 'dart:js';
import 'package:js/js.dart';
import 'package:js/js_util.dart' as js_util;
import 'node.dart';
export 'package:js/js_util.dart' hide jsify;
Util get util => _util ??= require('util');
Util _util;
@JS()
@anonymous
abstract class Util {
/// Possible signatures:
///
/// inspect(object[, options])
/// inspect(object[, showHidden[, depth[, colors]]])
external dynamic inspect(object, [arg1, arg2, arg3]);
}
/// Returns Dart representation from JS Object.
///
/// Basic types (`num`, `bool`, `String`) are returned as-is. JS arrays
/// are converted into `List` instances. JS objects are converted into
/// `Map` instances. Both arrays and objects are traversed recursively
/// converting nested values.
///
/// Converting JS objects always results in a `Map<String, dynamic>` meaning
/// even if original object had an integer key set, it will be converted into
/// a `String`. This is different from JS semantics where you are allowed to
/// access a key by passing its int value, e.g. `obj[1]` would work in JS,
/// but fail in Dart.
///
/// See also:
/// - [jsify]
T dartify<T>(Object jsObject) {
if (_isBasicType(jsObject)) {
return jsObject as T;
}
if (jsObject is List) {
return jsObject.map(dartify).toList() as T;
}
var keys = objectKeys(jsObject);
var result = <String, dynamic>{};
for (var key in keys) {
result[key] = dartify(js_util.getProperty(jsObject, key));
}
return result as T;
}
/// Returns the JS representation from Dart Object.
///
/// This function is identical to the one from 'dart:js_util' with only
/// difference that it handles basic types ([String], [num], [bool] and [null].
///
/// See also:
/// - [dartify]
dynamic jsify(Object dartObject) {
if (_isBasicType(dartObject)) {
return dartObject;
}
return js_util.jsify(dartObject);
}
/// Returns `true` if the [value] is a very basic built-in type - e.g.
/// [null], [num], [bool] or [String]. It returns `false` in the other case.
bool _isBasicType(value) {
if (value == null || value is num || value is bool || value is String) {
return true;
}
return false;
}
/// Creates Dart `Future` which completes when [promise] is resolved or
/// rejected.
///
/// See also:
/// - [futureToPromise]
Future<T> promiseToFuture<T>(Promise promise) {
var completer = Completer<T>.sync();
promise.then(allowInterop((value) {
completer.complete(value);
}), allowInterop((error) {
completer.completeError(error);
}));
return completer.future;
}
/// Creates JS `Promise` which is resolved when [future] completes.
///
/// See also:
/// - [promiseToFuture]
Promise futureToPromise<T>(Future<T> future) {
return Promise(allowInterop((Function resolve, Function reject) {
future.then(resolve, onError: reject);
}));
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/fs.dart | // Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node.js "fs" module bindings.
///
/// Use library-level [fs] object to access functionality of this module.
@JS()
library node_interop.fs;
import 'package:js/js.dart';
import 'events.dart';
import 'node.dart';
import 'stream.dart';
FS get fs => _fs ??= require('fs');
FS _fs;
@JS()
@anonymous
abstract class FS {
external FSConstants get constants;
external void access(path, [modeOrCallback, callback]);
external void accessSync(path, [int mode]);
external void appendFile(file, data, [options, callback]);
external void appendFileSync(file, data, [options]);
external void chmod(path, int mode, void Function(dynamic error) callback);
external void chmodSync(path, int mode);
external void chown(
path, int uid, gid, void Function(dynamic error) callback);
external void chownSync(path, int uid, gid);
external void close(int fd, void Function(dynamic error) callback);
external void closeSync(int fd);
external void copyFile(
src, dest, num flags, void Function(dynamic error) callback);
external void copyFileSync(src, dest, num flags);
external ReadStream createReadStream(path, [ReadStreamOptions options]);
external WriteStream createWriteStream(path, [WriteStreamOptions options]);
@deprecated
external void exists(path, void Function(bool exists) callback);
external bool existsSync(path);
external void fchmod(int fd, int mode, void Function(dynamic error) callback);
external void fchmodSync(int fd, int mode);
external void fchown(
int fd, int uid, gid, void Function(dynamic error) callback);
external void fchownSync(int fd, int uid, gid);
external void fdatasync(int fd, void Function(dynamic error) callback);
external void fdatasyncSync(int fd);
external void fstat(
int fd, void Function(dynamic error, Stats stats) callback);
external Stats fstatSync(int fd);
external void fsync(int fd, void Function(dynamic error) callback);
external void fsyncSync(int fd);
external void ftruncate(int fd, [lenOrCallback, callback]);
external void ftruncateSync(int fd, [len]);
external void futimes(
int fd, atime, mtime, void Function(dynamic error) callback);
external void futimesSync(int fd, atime, mtime);
external void lchmod(path, int mode, void Function(dynamic error) callback);
external void lchmodSync(path, int mode);
external void lchown(
path, int uid, gid, void Function(dynamic error) callback);
external void lchownSync(path, int uid, gid);
external void link(
existingPath, newPath, void Function(dynamic error) callback);
external void linkSync(existingPath, newPath);
external void lstat(path, void Function(dynamic error, Stats stats) callback);
external Stats lstatSync(path);
external void mkdir(path,
[modeOrCallback, void Function(dynamic error) callback]);
external void mkdirSync(path, [int mode]);
external void mkdtemp(String prefix,
[optionsOrCallback,
void Function(dynamic error, String folder) callback]);
external String mkdtempSync(prefix, [options]);
external void open(path, flags,
[modeOrCallback, void Function(dynamic err, int fd) callback]);
external int openSync(path, flags, [int mode]);
external void read(int fd, buffer, int offset, int length, int position,
void Function(dynamic error, int bytesRead, Buffer buffer) callback);
external void readdir(path,
[optionsOrCallback, void Function(dynamic err, List files) callback]);
external List readdirSync(path, [options]);
external void readFile(path,
[optionsOrCallback, void Function(dynamic error, dynamic data) callback]);
external dynamic readFileSync(path, [options]);
external void readlink(path,
[optionsOrCallback,
void Function(dynamic error, dynamic linkString) callback]);
external dynamic readlinkSync(path, [options]);
external int readSync(int fd, buffer, int offset, int length, int position);
external void realpath(path,
[optionsOrCallback,
void Function(dynamic error, dynamic resolvedPath) callback]);
// TODO: realpath.native(path[, options], callback)
external String realpathSync(path, [options]);
// TODO: realpathSync.native(path[, options])
external void rename(oldPath, newPath, void Function(dynamic error) callback);
external void renameSync(oldPath, newPath);
external void rmdir(path, void Function(dynamic error) callback);
external void rmdirSync(path);
external void stat(path, void Function(dynamic error, Stats stats) callback);
external Stats statSync(path);
external void symlink(target, path,
[typeOrCallback, void Function(dynamic error) callback]);
external void symlinkSync(target, path, [type]);
external void truncate(path, [lenOrCallback, callback]);
external void truncateSync(path, [int len]);
external void unlink(path, [void Function(dynamic error) callback]);
external void unlinkSync(path);
external void unwatchFile(filename, [Function listener]);
external void utimes(
path, atime, mtime, void Function(dynamic error) callback);
external void utimesSync(path, atime, mtime);
external void watch(filename,
[options, void Function(String eventType, dynamic filename) listener]);
external void watchFile(filename,
[optionsOrListener,
void Function(Stats current, Stats previous) listener]);
/// See official documentation on all possible argument combinations:
/// - https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback
external void write(int fd, data, [arg1, arg2, arg3, Function callback]);
external void writeFile(file, data,
[optionsOrCallback, void Function(dynamic error) callback]);
external void writeFileSync(file, data, [options]);
/// See official documentation on all possible argument combinations:
/// - https://nodejs.org/api/fs.html#fs_fs_writesync_fd_buffer_offset_length_position
external int writeSync(int fd, data, [arg1, arg2, arg3]);
}
@JS()
@anonymous
abstract class FSConstants {
/// File Access Constants for use with [FS.access].
external int get F_OK;
external int get R_OK;
external int get W_OK;
external int get X_OK;
/// File Open Constants for use with [FS.open].
external int get O_RDONLY;
external int get O_WRONLY;
external int get O_RDWR;
external int get O_CREAT;
external int get O_EXCL;
external int get O_NOCTTY;
external int get O_TRUNC;
external int get O_APPEND;
external int get O_DIRECTORY;
external int get O_NOATIME;
external int get O_NOFOLLOW;
external int get O_SYNC;
external int get O_DSYNC;
external int get O_SYMLINK;
external int get O_DIRECT;
external int get O_NONBLOCK;
/// File Type Constants for use with [Stats.mode].
external int get S_IFMT;
external int get S_IFREG;
external int get S_IFDIR;
external int get S_IFCHR;
external int get S_IFBLK;
external int get S_IFIFO;
external int get S_IFLNK;
external int get S_IFSOCK;
/// File Mode Constants for use with [Stats.mode].
external int get S_IRWXU;
external int get S_IRUSR;
external int get S_IWUSR;
external int get S_IXUSR;
external int get S_IRWXG;
external int get S_IRGRP;
external int get S_IWGRP;
external int get S_IXGRP;
external int get S_IRWXO;
external int get S_IROTH;
external int get S_IWOTH;
external int get S_IXOTH;
}
@JS()
@anonymous
abstract class FSWatcher implements EventEmitter {
external void close();
}
@JS()
@anonymous
abstract class ReadStream implements Readable {
external num get bytesRead;
external dynamic get path;
}
@JS()
@anonymous
abstract class ReadStreamOptions {
external String get flags;
external String get encoding;
external int get fd;
external int get mode;
external bool get autoClose;
external int get start;
external set start(int value);
external int get end;
external set end(int value);
external factory ReadStreamOptions({
String flags,
String encoding,
int fd,
int mode,
bool autoClose,
int start,
int end,
});
}
@JS()
@anonymous
abstract class WriteStream implements Writable {
external num get bytesWritten;
external dynamic get path;
}
@JS()
@anonymous
abstract class WriteStreamOptions {
external String get flags;
external String get encoding;
external int get fd;
external int get mode;
external bool get autoClose;
external int get start;
external factory WriteStreamOptions({
String flags,
String encoding,
int fd,
int mode,
bool autoClose,
int start,
});
}
@JS()
@anonymous
abstract class Stats {
external bool isBlockDevice();
external bool isCharacterDevice();
external bool isDirectory();
external bool isFIFO();
external bool isFile();
external bool isSocket();
external bool isSymbolicLink();
external num get dev;
external num get ino;
external num get mode;
external num get nlink;
external num get uid;
external num get gid;
external num get rdev;
external num get blksize;
external num get blocks;
external num get atimeMs; // since 8.1.0
external num get ctimeMs; // since 8.1.0
external num get mtimeMs; // since 8.1.0
external num get birthtimeMs; // since 8.1.0
external Date get atime;
external Date get ctime;
external Date get mtime;
external Date get birthtime;
external int get size;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/node.dart | // Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node.js globals bindings.
@JS()
library node_interop.node;
import 'package:js/js.dart';
import 'package:js/js_util.dart';
import 'console.dart';
import 'js.dart';
import 'module.dart';
import 'process.dart';
export 'buffer.dart';
export 'js.dart';
export 'process.dart';
export 'timers.dart';
/// Loads module with specified [id].
///
/// Note that this is not actually a global variable and when compiled to
/// JavaScript proxies all calls to the `require` function of main application
/// module.
external dynamic require(String id);
/// Reference to the main module's `exports` object.
///
/// Note that this is not actually a global variable and currently only
/// works for the application's main module, meaning it should only be used
/// from inside the `main` function of a Dart application.
///
/// Consider using [setExport] to register exports inside your `main` function.
external dynamic get exports;
/// Registers property with [key] and [value] in the module [exports] object.
void setExport(String key, Object value) {
setProperty(exports, key, value);
}
external Console get console;
/// Reference to the main module's [Module] object.
///
/// Note that this is not actually a global variable and currently only
/// works for the application's main module, meaning it should only be used
/// from inside the `main` function of a Dart application.
external Module get module;
external Process get process;
@JS()
@anonymous
abstract class NodeJsError implements JsError {
external String get code;
}
@JS('AssertionError')
abstract class JsAssertionError extends NodeJsError {}
@JS('RangeError')
abstract class JsRangeError extends NodeJsError {}
@JS('ReferenceError')
abstract class JsReferenceError extends NodeJsError {}
@JS('SyntaxError')
abstract class JsSyntaxError extends NodeJsError {}
@JS('TypeError')
abstract class JsTypeError extends NodeJsError {}
@JS('SystemError')
abstract class JsSystemError extends NodeJsError {
static const String EACCES = 'EACCES';
static const String EADDRINUSE = 'EADDRINUSE';
static const String ECONNREFUSED = 'ECONNREFUSED';
static const String ECONNRESET = 'ECONNRESET';
static const String EEXIST = 'EEXIST';
static const String EISDIR = 'EISDIR';
static const String EMFILE = 'EMFILE';
static const String ENOENT = 'ENOENT';
static const String ENOTDIR = 'ENOTDIR';
static const String ENOTEMPTY = 'ENOTEMPTY';
static const String EPERM = 'EPERM';
static const String EPIPE = 'EPIPE';
static const String ETIMEDOUT = 'ETIMEDOUT';
external dynamic get errno;
external String get syscall;
external String get path;
external String get address;
external num get port;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/node_interop/console.dart | // Copyright (c) 2018, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
/// Node.js "console" module bindings.
@JS()
library node_interop.console;
import 'dart:js_util';
import 'package:js/js.dart';
import 'stream.dart';
import 'node.dart';
ConsoleModule get console => _console ??= require('console');
ConsoleModule _console;
Console createConsole(Writable stdout, [Writable stderr]) {
if (stderr == null) {
return callConstructor(console.Console, [stdout]);
} else {
return callConstructor(console.Console, [stdout, stderr]);
}
}
@JS()
@anonymous
abstract class ConsoleModule {
dynamic get Console;
}
@JS()
@anonymous
abstract class Console {
external void clear();
external void count([String label]);
external void countReset([String label]);
// Unsupported: "assert" is a reserved word in Dart.
// external void assert(String data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void debug(data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void dir(object, [options]);
external void dirxml([arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void error(data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void group([label1, label2, label3, label4, label5, label6]);
external void groupCollapsed();
external void groupEnd();
external void info(data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void log(data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void time(String label);
external void timeEnd(String label);
external void trace(message, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
external void warn(data, [arg1, arg2, arg3, arg4, arg5, arg6, arg7]);
// Inspector only methods:
external void markTimeline(String label);
external void profile([String label]);
external void profileEnd();
external void table(array, [columns]);
external void timeStamp([String label]);
external void timeline([String label]);
external void timelineEnd([String label]);
}
| 0 |
Subsets and Splits