| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 /// Contains logic to initialize polymer apps during development. This | |
| 6 /// implementation uses dart:mirrors to load each library as they are discovered | |
| 7 /// through HTML imports. This is only meant to be during development in | |
| 8 /// dartium, and the polymer transformers replace this implementation with | |
| 9 /// codege generation in the polymer-build steps. | |
| 10 library polymer.src.mirror_loader; | |
| 11 | |
| 12 import 'dart:async'; | |
| 13 import 'dart:html'; | |
| 14 import 'dart:collection' show LinkedHashMap; | |
| 15 | |
| 16 // Technically, we shouldn't need any @MirrorsUsed, since this is for | |
| 17 // development only, but our test bots don't yet run pub-build. See more details | |
| 18 // on the comments of the mirrors import in `lib/polymer.dart`. | |
| 19 @MirrorsUsed(metaTargets: | |
| 20 const [CustomTag, InitMethodAnnotation], | |
| 21 override: const ['smoke.mirrors', 'polymer.src.mirror_loader']) | |
| 22 import 'dart:mirrors'; | |
| 23 | |
| 24 import 'package:logging/logging.dart' show Logger; | |
| 25 import 'package:observe/src/dirty_check.dart'; | |
| 26 import 'package:polymer/polymer.dart'; | |
| 27 | |
| 28 | |
| 29 /// Used by code generated from the experimental polymer bootstrap in boot.js. | |
| 30 void startPolymerInDevelopment(List<String> librariesToLoad) { | |
| 31 dirtyCheckZone()..run(() { | |
| 32 startPolymer(discoverInitializers(librariesToLoad), false); | |
| 33 }); | |
| 34 } | |
| 35 | |
| 36 /// Set of initializers that are invoked by `initPolymer`. This is computed the | |
| 37 /// list by crawling HTML imports, searching for script tags, and including an | |
| 38 /// initializer for each type tagged with a [CustomTag] annotation and for each | |
| 39 /// top-level method annotated with [initMethod]. | |
| 40 List<Function> initializers = discoverInitializers( | |
| 41 discoverLibrariesToLoad(document, window.location.href)); | |
| 42 | |
| 43 /// True if we're in deployment mode. | |
| 44 bool deployMode = false; | |
| 45 | |
| 46 /// Discovers what script tags are loaded from HTML pages and collects the | |
| 47 /// initializers of their corresponding libraries. | |
| 48 // Visible for testing only. | |
| 49 List<Function> discoverInitializers(Iterable<String> librariesToLoad) { | |
| 50 var initializers = []; | |
| 51 for (var lib in librariesToLoad) { | |
| 52 try { | |
| 53 _loadLibrary(lib, initializers); | |
| 54 } catch (e, s) { | |
| 55 // Deliver errors async, so if a single library fails it doesn't prevent | |
| 56 // other things from loading. | |
| 57 new Completer().completeError(e, s); | |
| 58 } | |
| 59 } | |
| 60 return initializers; | |
| 61 } | |
| 62 | |
| 63 /// Walks the HTML import structure to discover all script tags that are | |
| 64 /// implicitly loaded. This code is only used in Dartium and should only be | |
| 65 /// called after all HTML imports are resolved. Polymer ensures this by asking | |
| 66 /// users to put their Dart script tags after all HTML imports (this is checked | |
| 67 /// by the linter, and Dartium will otherwise show an error message). | |
| 68 Iterable<_ScriptInfo> _discoverScripts( | |
| 69 Document doc, String baseUri, [_State state]) { | |
| 70 if (state == null) state = new _State(); | |
| 71 if (doc == null) { | |
| 72 print('warning: $baseUri not found.'); | |
| 73 return state.scripts.values; | |
| 74 } | |
| 75 if (!state.seen.add(doc)) return state.scripts.values; | |
| 76 | |
| 77 for (var node in doc.querySelectorAll('script,link[rel="import"]')) { | |
| 78 if (node is LinkElement) { | |
| 79 _discoverScripts(node.import, node.href, state); | |
| 80 } else if (node is ScriptElement && node.type == 'application/dart') { | |
| 81 var info = _scriptInfoFor(node, baseUri); | |
| 82 if (state.scripts.containsKey(info.resolvedUrl)) { | |
| 83 print('warning: Script `${info.resolvedUrl}` included more than once. ' | |
| 84 'See http://goo.gl/5HPeuP#polymer_44 for more details.'); | |
| 85 } else { | |
| 86 state.scripts[info.resolvedUrl] = info; | |
| 87 } | |
| 88 } | |
| 89 } | |
| 90 return state.scripts.values; | |
| 91 } | |
| 92 | |
| 93 /// Internal state used in [_discoverScripts]. | |
| 94 class _State { | |
| 95 /// Documents that we have visited thus far. | |
| 96 final Set<Document> seen = new Set(); | |
| 97 | |
| 98 /// Scripts that have been discovered, in tree order. | |
| 99 final LinkedHashMap<String, _ScriptInfo> scripts = {}; | |
| 100 } | |
| 101 | |
| 102 /// Holds information about a Dart script tag. | |
| 103 class _ScriptInfo { | |
| 104 /// The original URL seen in the tag fully resolved. | |
| 105 final String resolvedUrl; | |
| 106 | |
| 107 /// Whether there was no URL, but code inlined instead. | |
| 108 bool get isInline => text != null; | |
| 109 | |
| 110 /// Whether it seems to be a 'package:' URL (starts with the package-root). | |
| 111 bool get isPackage => packageUrl != null; | |
| 112 | |
| 113 /// The equivalent 'package:' URL, if any. | |
| 114 final String packageUrl; | |
| 115 | |
| 116 /// The inlined text, if any. | |
| 117 final String text; | |
| 118 | |
| 119 /// Returns a base64 `data:` uri with the contents of [text]. | |
| 120 // TODO(sigmund): change back to application/dart: using text/javascript seems | |
| 121 // wrong but it hides a warning in Dartium (dartbug.com/18000). | |
| 122 String get dataUrl => 'data:text/javascript;base64,${window.btoa(text)}'; | |
| 123 | |
| 124 /// URL to import the contents of the original script from Dart. This is | |
| 125 /// either the source URL if the script tag had a `src` attribute, or a base64 | |
| 126 /// encoded `data:` URL if the script contents are inlined, or a `package:` | |
| 127 /// URL if the script can be resolved via a package URL. | |
| 128 String get importUrl => | |
| 129 isInline ? dataUrl : (isPackage ? packageUrl : resolvedUrl); | |
| 130 | |
| 131 _ScriptInfo(this.resolvedUrl, {this.packageUrl, this.text}); | |
| 132 } | |
| 133 | |
| 134 | |
| 135 // TODO(sigmund): explore other (cheaper) ways to resolve URIs relative to the | |
| 136 // root library (see dartbug.com/12612) | |
| 137 final _rootUri = currentMirrorSystem().isolate.rootLibrary.uri; | |
| 138 | |
| 139 /// Returns [_ScriptInfo] for [script] which was seen in [baseUri]. | |
| 140 _ScriptInfo _scriptInfoFor(script, baseUri) { | |
| 141 var uriString = script.src; | |
| 142 if (uriString != '') { | |
| 143 var uri = _rootUri.resolve(uriString); | |
| 144 if (!_isHttpStylePackageUrl(uri)) return new _ScriptInfo('$uri'); | |
| 145 // Use package: urls if available. This rule here is more permissive than | |
| 146 // how we translate urls in polymer-build, but we expect Dartium to limit | |
| 147 // the cases where there are differences. The polymer-build issues an error | |
| 148 // when using packages/ inside lib without properly stepping out all the way | |
| 149 // to the packages folder. If users don't create symlinks in the source | |
| 150 // tree, then Dartium will also complain because it won't find the file seen | |
| 151 // in an HTML import. | |
| 152 var packagePath = uri.path.substring( | |
| 153 uri.path.lastIndexOf('packages/') + 'packages/'.length); | |
| 154 return new _ScriptInfo('$uri', packageUrl: 'package:$packagePath'); | |
| 155 } | |
| 156 | |
| 157 return new _ScriptInfo(baseUri, text: script.text); | |
| 158 } | |
| 159 | |
| 160 /// Whether [uri] is an http URI that contains a 'packages' segment, and | |
| 161 /// therefore could be converted into a 'package:' URI. | |
| 162 bool _isHttpStylePackageUrl(Uri uri) { | |
| 163 var uriPath = uri.path; | |
| 164 return uri.scheme == _rootUri.scheme && | |
| 165 // Don't process cross-domain uris. | |
| 166 uri.authority == _rootUri.authority && | |
| 167 uriPath.endsWith('.dart') && | |
| 168 (uriPath.contains('/packages/') || uriPath.startsWith('packages/')); | |
| 169 } | |
| 170 | |
| 171 Iterable<String> discoverLibrariesToLoad(Document doc, String baseUri) => | |
| 172 _discoverScripts(doc, baseUri).map( | |
| 173 (info) => _packageUrlExists(info) ? info.packageUrl : info.resolvedUrl); | |
| 174 | |
| 175 bool _packageUrlExists(_ScriptInfo info) => | |
| 176 info.isPackage && _libs[Uri.parse(info.packageUrl)] != null; | |
| 177 | |
| 178 /// All libraries in the current isolate. | |
| 179 final _libs = currentMirrorSystem().libraries; | |
| 180 | |
| 181 final Logger _loaderLog = new Logger('polymer.src.mirror_loader'); | |
| 182 | |
| 183 /// Reads the library at [uriString] (which can be an absolute URI or a relative | |
| 184 /// URI from the root library), and: | |
| 185 /// | |
| 186 /// * If present, invokes any top-level and static functions marked | |
| 187 /// with the [initMethod] annotation (in the order they appear). | |
| 188 /// | |
| 189 /// * Registers any [PolymerElement] that is marked with the [CustomTag] | |
| 190 /// annotation. | |
| 191 void _loadLibrary(String uriString, List<Function> initializers) { | |
| 192 var uri = Uri.parse(uriString); | |
| 193 var lib = _libs[uri]; | |
| 194 | |
| 195 if (lib == null) { | |
| 196 _loaderLog.info('$uri library not found'); | |
| 197 return; | |
| 198 } | |
| 199 | |
| 200 // Search top-level functions marked with @initMethod | |
| 201 for (var f in lib.declarations.values.where((d) => d is MethodMirror)) { | |
| 202 _addInitMethod(lib, f, initializers); | |
| 203 } | |
| 204 | |
| 205 | |
| 206 // Dart note: we don't get back @CustomTags in a reliable order from mirrors, | |
| 207 // at least on Dart VM. So we need to sort them so base classes are registered | |
| 208 // first, which ensures that document.register will work correctly for a | |
| 209 // set of types within in the same library. | |
| 210 var customTags = new LinkedHashMap<Type, Function>(); | |
| 211 for (var c in lib.declarations.values.where((d) => d is ClassMirror)) { | |
| 212 _loadCustomTags(lib, c, customTags); | |
| 213 // TODO(sigmund): check also static methods marked with @initMethod. | |
| 214 // This is blocked on two bugs: | |
| 215 // - dartbug.com/12133 (static methods are incorrectly listed as top-level | |
| 216 // in dart2js, so they end up being called twice) | |
| 217 // - dartbug.com/12134 (sometimes "method.metadata" throws an exception, | |
| 218 // we could wrap and hide those exceptions, but it's not ideal). | |
| 219 } | |
| 220 | |
| 221 initializers.addAll(customTags.values); | |
| 222 } | |
| 223 | |
| 224 void _loadCustomTags(LibraryMirror lib, ClassMirror cls, | |
| 225 LinkedHashMap registerFns) { | |
| 226 if (cls == null) return; | |
| 227 if (cls.hasReflectedType && cls.reflectedType == HtmlElement) return; | |
| 228 | |
| 229 // Register superclass first. | |
| 230 _loadCustomTags(lib, cls.superclass, registerFns); | |
| 231 | |
| 232 if (cls.owner != lib) { | |
| 233 // Don't register classes from different libraries. | |
| 234 // TODO(jmesserly): @CustomTag does not currently respect re-export, because | |
| 235 // LibraryMirror.declarations doesn't include these. | |
| 236 return; | |
| 237 } | |
| 238 | |
| 239 var meta = _getCustomTagMetadata(cls); | |
| 240 if (meta == null) return; | |
| 241 | |
| 242 if (!cls.hasReflectedType) { | |
| 243 var name = MirrorSystem.getName(cls.simpleName); | |
| 244 new Completer().completeError(new UnsupportedError('Custom element classes ' | |
| 245 'cannot have type-parameters: $name')); | |
| 246 return; | |
| 247 } | |
| 248 | |
| 249 registerFns.putIfAbsent(cls.reflectedType, () => | |
| 250 () => Polymer.register(meta.tagName, cls.reflectedType)); | |
| 251 } | |
| 252 | |
| 253 /// Search for @CustomTag on a classemirror | |
| 254 CustomTag _getCustomTagMetadata(ClassMirror c) { | |
| 255 for (var m in c.metadata) { | |
| 256 var meta = m.reflectee; | |
| 257 if (meta is CustomTag) return meta; | |
| 258 } | |
| 259 return null; | |
| 260 } | |
| 261 | |
| 262 void _addInitMethod(ObjectMirror obj, MethodMirror method, | |
| 263 List<Function> initializers) { | |
| 264 var annotationFound = false; | |
| 265 for (var meta in method.metadata) { | |
| 266 if (identical(meta.reflectee, initMethod)) { | |
| 267 annotationFound = true; | |
| 268 break; | |
| 269 } | |
| 270 } | |
| 271 if (!annotationFound) return; | |
| 272 if (!method.isStatic) { | |
| 273 print("warning: methods marked with @initMethod should be static," | |
| 274 " ${method.simpleName} is not."); | |
| 275 return; | |
| 276 } | |
| 277 if (!method.parameters.where((p) => !p.isOptional).isEmpty) { | |
| 278 print("warning: methods marked with @initMethod should take no " | |
| 279 "arguments, ${method.simpleName} expects some."); | |
| 280 return; | |
| 281 } | |
| 282 initializers.add(() => obj.invoke(method.simpleName, const [])); | |
| 283 } | |
| OLD | NEW |