MCPcopy
hub / github.com/ampproject/amphtml / patchShadowDom

Function patchShadowDom

build-system/common/update-packages.js:113–180  ·  view source on GitHub ↗

* Patches Shadow DOM polyfill by wrapping its body into `install` * function. * This gives us an option to control when and how the polyfill is installed. * The polyfill can only be installed on the root context.

()

Source from the content-addressed store, hash-verified

111 * The polyfill can only be installed on the root context.
112 */
113function patchShadowDom() {
114 // Copies webcomponents-sd into a new file that has an export.
115 const patchedName =
116 'node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-sd.install.js';
117
118 let file = '(function() {';
119 // HTMLElement is replaced, but the original needs to be used for the polyfill
120 // since it manipulates "own" properties. See `src/polyfills/custom-element.js`.
121 file += 'var HTMLElementOrig = window.HTMLElementOrig || window.HTMLElement;';
122 file += 'window.HTMLElementOrig = HTMLElementOrig;';
123 file += `
124 (function() {
125 var origContains = document.contains;
126 if (origContains) {
127 Object.defineProperty(document, '__shady_native_contains', {value: origContains});
128 }
129 Object.defineProperty(document, 'contains', {
130 configurable: true,
131 value: function(node) {
132 if (node === this) {
133 return true;
134 }
135 if (this.documentElement) {
136 return this.documentElement.contains(node);
137 }
138 return false;
139 }
140 });
141 })();
142 `;
143
144 /**
145 * @param {string} file
146 * @return {string}
147 */
148 function transformScript(file) {
149 // Use the HTMLElement from above.
150 file = file.replace(/\bHTMLElement\b/g, 'HTMLElementOrig');
151 return file;
152 }
153
154 // Relevant DOM polyfills
155 file += transformScript(
156 fs
157 .readFileSync(
158 'node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-pf_dom.js'
159 )
160 .toString()
161 );
162 file += transformScript(
163 fs
164 .readFileSync(
165 'node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-sd.js'
166 )
167 .toString()
168 );
169 file += '})();';
170

Callers 1

updatePackagesFunction · 0.85

Calls 4

transformScriptFunction · 0.85
writeIfUpdatedFunction · 0.85
toStringMethod · 0.45
replaceMethod · 0.45

Tested by

no test coverage detected