id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
0 | Microsoft/vscode | build/lib/treeshaking.js | discoverAndReadFiles | function discoverAndReadFiles(options) {
const FILES = {};
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue;
}
const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
let ts_filename;
if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
}
else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
}
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
}
enqueue(importedModuleId);
}
FILES[`${moduleId}.ts`] = ts_filecontents;
}
return FILES;
} | javascript | function discoverAndReadFiles(options) {
const FILES = {};
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue;
}
const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
let ts_filename;
if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
}
else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
}
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
}
enqueue(importedModuleId);
}
FILES[`${moduleId}.ts`] = ts_filecontents;
}
return FILES;
} | [
"function",
"discoverAndReadFiles",
"(",
"options",
")",
"{",
"const",
"FILES",
"=",
"{",
"}",
";",
"const",
"in_queue",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"const",
"queue",
"=",
"[",
"]",
";",
"const",
"enqueue",
"=",
"(",
"moduleId",
")",
"=>",
"{",
"if",
"(",
"in_queue",
"[",
"moduleId",
"]",
")",
"{",
"return",
";",
"}",
"in_queue",
"[",
"moduleId",
"]",
"=",
"true",
";",
"queue",
".",
"push",
"(",
"moduleId",
")",
";",
"}",
";",
"options",
".",
"entryPoints",
".",
"forEach",
"(",
"(",
"entryPoint",
")",
"=>",
"enqueue",
"(",
"entryPoint",
")",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"const",
"moduleId",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"const",
"dts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.d.ts'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"dts_filename",
")",
")",
"{",
"const",
"dts_filecontents",
"=",
"fs",
".",
"readFileSync",
"(",
"dts_filename",
")",
".",
"toString",
"(",
")",
";",
"FILES",
"[",
"`",
"${",
"moduleId",
"}",
"`",
"]",
"=",
"dts_filecontents",
";",
"continue",
";",
"}",
"const",
"js_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.js'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"js_filename",
")",
")",
"{",
"// This is an import for a .js file, so ignore it...",
"continue",
";",
"}",
"let",
"ts_filename",
";",
"if",
"(",
"options",
".",
"redirects",
"[",
"moduleId",
"]",
")",
"{",
"ts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"options",
".",
"redirects",
"[",
"moduleId",
"]",
"+",
"'.ts'",
")",
";",
"}",
"else",
"{",
"ts_filename",
"=",
"path",
".",
"join",
"(",
"options",
".",
"sourcesRoot",
",",
"moduleId",
"+",
"'.ts'",
")",
";",
"}",
"const",
"ts_filecontents",
"=",
"fs",
".",
"readFileSync",
"(",
"ts_filename",
")",
".",
"toString",
"(",
")",
";",
"const",
"info",
"=",
"ts",
".",
"preProcessFile",
"(",
"ts_filecontents",
")",
";",
"for",
"(",
"let",
"i",
"=",
"info",
".",
"importedFiles",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"importedFileName",
"=",
"info",
".",
"importedFiles",
"[",
"i",
"]",
".",
"fileName",
";",
"if",
"(",
"options",
".",
"importIgnorePattern",
".",
"test",
"(",
"importedFileName",
")",
")",
"{",
"// Ignore vs/css! imports",
"continue",
";",
"}",
"let",
"importedModuleId",
"=",
"importedFileName",
";",
"if",
"(",
"/",
"(^\\.\\/)|(^\\.\\.\\/)",
"/",
".",
"test",
"(",
"importedModuleId",
")",
")",
"{",
"importedModuleId",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"moduleId",
")",
",",
"importedModuleId",
")",
";",
"}",
"enqueue",
"(",
"importedModuleId",
")",
";",
"}",
"FILES",
"[",
"`",
"${",
"moduleId",
"}",
"`",
"]",
"=",
"ts_filecontents",
";",
"}",
"return",
"FILES",
";",
"}"
] | Read imports and follow them until all files have been handled | [
"Read",
"imports",
"and",
"follow",
"them",
"until",
"all",
"files",
"have",
"been",
"handled"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/treeshaking.js#L79-L128 |
1 | Microsoft/vscode | build/lib/watch/index.js | handleDeletions | function handleDeletions() {
return es.mapSync(f => {
if (/\.ts$/.test(f.relative) && !f.contents) {
f.contents = Buffer.from('');
f.stat = { mtime: new Date() };
}
return f;
});
} | javascript | function handleDeletions() {
return es.mapSync(f => {
if (/\.ts$/.test(f.relative) && !f.contents) {
f.contents = Buffer.from('');
f.stat = { mtime: new Date() };
}
return f;
});
} | [
"function",
"handleDeletions",
"(",
")",
"{",
"return",
"es",
".",
"mapSync",
"(",
"f",
"=>",
"{",
"if",
"(",
"/",
"\\.ts$",
"/",
".",
"test",
"(",
"f",
".",
"relative",
")",
"&&",
"!",
"f",
".",
"contents",
")",
"{",
"f",
".",
"contents",
"=",
"Buffer",
".",
"from",
"(",
"''",
")",
";",
"f",
".",
"stat",
"=",
"{",
"mtime",
":",
"new",
"Date",
"(",
")",
"}",
";",
"}",
"return",
"f",
";",
"}",
")",
";",
"}"
] | Ugly hack for gulp-tsb | [
"Ugly",
"hack",
"for",
"gulp",
"-",
"tsb"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/watch/index.js#L9-L18 |
2 | Microsoft/vscode | build/lib/optimize.js | uglifyWithCopyrights | function uglifyWithCopyrights() {
const preserveComments = (f) => {
return (_node, comment) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const minify = composer(uglifyes);
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream.pipe(minify({
output: {
comments: preserveComments(f),
max_line_len: 1024
}
}));
}));
return es.duplex(input, output);
} | javascript | function uglifyWithCopyrights() {
const preserveComments = (f) => {
return (_node, comment) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const minify = composer(uglifyes);
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream.pipe(minify({
output: {
comments: preserveComments(f),
max_line_len: 1024
}
}));
}));
return es.duplex(input, output);
} | [
"function",
"uglifyWithCopyrights",
"(",
")",
"{",
"const",
"preserveComments",
"=",
"(",
"f",
")",
"=>",
"{",
"return",
"(",
"_node",
",",
"comment",
")",
"=>",
"{",
"const",
"text",
"=",
"comment",
".",
"value",
";",
"const",
"type",
"=",
"comment",
".",
"type",
";",
"if",
"(",
"/",
"@minifier_do_not_preserve",
"/",
".",
"test",
"(",
"text",
")",
")",
"{",
"return",
"false",
";",
"}",
"const",
"isOurCopyright",
"=",
"IS_OUR_COPYRIGHT_REGEXP",
".",
"test",
"(",
"text",
")",
";",
"if",
"(",
"isOurCopyright",
")",
"{",
"if",
"(",
"f",
".",
"__hasOurCopyright",
")",
"{",
"return",
"false",
";",
"}",
"f",
".",
"__hasOurCopyright",
"=",
"true",
";",
"return",
"true",
";",
"}",
"if",
"(",
"'comment2'",
"===",
"type",
")",
"{",
"// check for /*!. Note that text doesn't contain leading /*",
"return",
"(",
"text",
".",
"length",
">",
"0",
"&&",
"text",
"[",
"0",
"]",
"===",
"'!'",
")",
"||",
"/",
"@preserve|license|@cc_on|copyright",
"/",
"i",
".",
"test",
"(",
"text",
")",
";",
"}",
"else",
"if",
"(",
"'comment1'",
"===",
"type",
")",
"{",
"return",
"/",
"license|copyright",
"/",
"i",
".",
"test",
"(",
"text",
")",
";",
"}",
"return",
"false",
";",
"}",
";",
"}",
";",
"const",
"minify",
"=",
"composer",
"(",
"uglifyes",
")",
";",
"const",
"input",
"=",
"es",
".",
"through",
"(",
")",
";",
"const",
"output",
"=",
"input",
".",
"pipe",
"(",
"flatmap",
"(",
"(",
"stream",
",",
"f",
")",
"=>",
"{",
"return",
"stream",
".",
"pipe",
"(",
"minify",
"(",
"{",
"output",
":",
"{",
"comments",
":",
"preserveComments",
"(",
"f",
")",
",",
"max_line_len",
":",
"1024",
"}",
"}",
")",
")",
";",
"}",
")",
")",
";",
"return",
"es",
".",
"duplex",
"(",
"input",
",",
"output",
")",
";",
"}"
] | Wrap around uglify and allow the preserveComments function
to have a file "context" to include our copyright only once per file. | [
"Wrap",
"around",
"uglify",
"and",
"allow",
"the",
"preserveComments",
"function",
"to",
"have",
"a",
"file",
"context",
"to",
"include",
"our",
"copyright",
"only",
"once",
"per",
"file",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/optimize.js#L169-L207 |
3 | Microsoft/vscode | build/lib/extensions.js | sequence | function sequence(streamProviders) {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
} | javascript | function sequence(streamProviders) {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
} | [
"function",
"sequence",
"(",
"streamProviders",
")",
"{",
"const",
"result",
"=",
"es",
".",
"through",
"(",
")",
";",
"function",
"pop",
"(",
")",
"{",
"if",
"(",
"streamProviders",
".",
"length",
"===",
"0",
")",
"{",
"result",
".",
"emit",
"(",
"'end'",
")",
";",
"}",
"else",
"{",
"const",
"fn",
"=",
"streamProviders",
".",
"shift",
"(",
")",
";",
"fn",
"(",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"setTimeout",
"(",
"pop",
",",
"0",
")",
";",
"}",
")",
".",
"pipe",
"(",
"result",
",",
"{",
"end",
":",
"false",
"}",
")",
";",
"}",
"}",
"pop",
"(",
")",
";",
"return",
"result",
";",
"}"
] | We're doing way too much stuff at once, with webpack et al. So much stuff
that while downloading extensions from the marketplace, node js doesn't get enough
stack frames to complete the download in under 2 minutes, at which point the
marketplace server cuts off the http request. So, we sequentialize the extensino tasks. | [
"We",
"re",
"doing",
"way",
"too",
"much",
"stuff",
"at",
"once",
"with",
"webpack",
"et",
"al",
".",
"So",
"much",
"stuff",
"that",
"while",
"downloading",
"extensions",
"from",
"the",
"marketplace",
"node",
"js",
"doesn",
"t",
"get",
"enough",
"stack",
"frames",
"to",
"complete",
"the",
"download",
"in",
"under",
"2",
"minutes",
"at",
"which",
"point",
"the",
"marketplace",
"server",
"cuts",
"off",
"the",
"http",
"request",
".",
"So",
"we",
"sequentialize",
"the",
"extensino",
"tasks",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/extensions.js#L194-L209 |
4 | Microsoft/vscode | src/vs/loader.js | function (what) {
moduleManager.getRecorder().record(33 /* NodeBeginNativeRequire */, what);
try {
return _nodeRequire_1(what);
}
finally {
moduleManager.getRecorder().record(34 /* NodeEndNativeRequire */, what);
}
} | javascript | function (what) {
moduleManager.getRecorder().record(33 /* NodeBeginNativeRequire */, what);
try {
return _nodeRequire_1(what);
}
finally {
moduleManager.getRecorder().record(34 /* NodeEndNativeRequire */, what);
}
} | [
"function",
"(",
"what",
")",
"{",
"moduleManager",
".",
"getRecorder",
"(",
")",
".",
"record",
"(",
"33",
"/* NodeBeginNativeRequire */",
",",
"what",
")",
";",
"try",
"{",
"return",
"_nodeRequire_1",
"(",
"what",
")",
";",
"}",
"finally",
"{",
"moduleManager",
".",
"getRecorder",
"(",
")",
".",
"record",
"(",
"34",
"/* NodeEndNativeRequire */",
",",
"what",
")",
";",
"}",
"}"
] | re-expose node's require function | [
"re",
"-",
"expose",
"node",
"s",
"require",
"function"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/src/vs/loader.js#L1705-L1713 |
|
5 | Microsoft/vscode | build/lib/nls.js | nls | function nls() {
const input = event_stream_1.through();
const output = input.pipe(event_stream_1.through(function (f) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return event_stream_1.duplex(input, output);
} | javascript | function nls() {
const input = event_stream_1.through();
const output = input.pipe(event_stream_1.through(function (f) {
if (!f.sourceMap) {
return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
}
let source = f.sourceMap.sources[0];
if (!source) {
return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
}
const root = f.sourceMap.sourceRoot;
if (root) {
source = path.join(root, source);
}
const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) {
return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
}
nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
}));
return event_stream_1.duplex(input, output);
} | [
"function",
"nls",
"(",
")",
"{",
"const",
"input",
"=",
"event_stream_1",
".",
"through",
"(",
")",
";",
"const",
"output",
"=",
"input",
".",
"pipe",
"(",
"event_stream_1",
".",
"through",
"(",
"function",
"(",
"f",
")",
"{",
"if",
"(",
"!",
"f",
".",
"sourceMap",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"let",
"source",
"=",
"f",
".",
"sourceMap",
".",
"sources",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"source",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"const",
"root",
"=",
"f",
".",
"sourceMap",
".",
"sourceRoot",
";",
"if",
"(",
"root",
")",
"{",
"source",
"=",
"path",
".",
"join",
"(",
"root",
",",
"source",
")",
";",
"}",
"const",
"typescript",
"=",
"f",
".",
"sourceMap",
".",
"sourcesContent",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"typescript",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"`",
"${",
"f",
".",
"relative",
"}",
"`",
")",
")",
";",
"}",
"nls",
".",
"patchFiles",
"(",
"f",
",",
"typescript",
")",
".",
"forEach",
"(",
"f",
"=>",
"this",
".",
"emit",
"(",
"'data'",
",",
"f",
")",
")",
";",
"}",
")",
")",
";",
"return",
"event_stream_1",
".",
"duplex",
"(",
"input",
",",
"output",
")",
";",
"}"
] | Returns a stream containing the patched JavaScript and source maps. | [
"Returns",
"a",
"stream",
"containing",
"the",
"patched",
"JavaScript",
"and",
"source",
"maps",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/nls.js#L54-L75 |
6 | Microsoft/vscode | build/lib/bundle.js | bundle | function bundle(entryPoints, config, callback) {
const entryPointsMap = {};
entryPoints.forEach((module) => {
entryPointsMap[module.name] = module;
});
const allMentionedModulesMap = {};
entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true;
});
(module.exclude || []).forEach(function (excludedModule) {
allMentionedModulesMap[excludedModule] = true;
});
});
const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports);
const loader = loaderModule.exports;
config.isBuild = true;
config.paths = config.paths || {};
if (!config.paths['vs/nls']) {
config.paths['vs/nls'] = 'out-build/vs/nls.build';
}
if (!config.paths['vs/css']) {
config.paths['vs/css'] = 'out-build/vs/css.build';
}
loader.config(config);
loader(['require'], (localRequire) => {
const resolvePath = (path) => {
const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) {
return r + '.js';
}
return r;
};
for (const moduleId in entryPointsMap) {
const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath);
}
if (entryPoint.prepend) {
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
}
}
});
loader(Object.keys(allMentionedModulesMap), () => {
const modules = loader.getBuildInfo();
const partialResult = emitEntryPoints(modules, entryPointsMap);
const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, {
files: partialResult.files,
cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData
});
}, (err) => callback(err, null));
} | javascript | function bundle(entryPoints, config, callback) {
const entryPointsMap = {};
entryPoints.forEach((module) => {
entryPointsMap[module.name] = module;
});
const allMentionedModulesMap = {};
entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true;
});
(module.exclude || []).forEach(function (excludedModule) {
allMentionedModulesMap[excludedModule] = true;
});
});
const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports);
const loader = loaderModule.exports;
config.isBuild = true;
config.paths = config.paths || {};
if (!config.paths['vs/nls']) {
config.paths['vs/nls'] = 'out-build/vs/nls.build';
}
if (!config.paths['vs/css']) {
config.paths['vs/css'] = 'out-build/vs/css.build';
}
loader.config(config);
loader(['require'], (localRequire) => {
const resolvePath = (path) => {
const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) {
return r + '.js';
}
return r;
};
for (const moduleId in entryPointsMap) {
const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath);
}
if (entryPoint.prepend) {
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
}
}
});
loader(Object.keys(allMentionedModulesMap), () => {
const modules = loader.getBuildInfo();
const partialResult = emitEntryPoints(modules, entryPointsMap);
const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, {
files: partialResult.files,
cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData
});
}, (err) => callback(err, null));
} | [
"function",
"bundle",
"(",
"entryPoints",
",",
"config",
",",
"callback",
")",
"{",
"const",
"entryPointsMap",
"=",
"{",
"}",
";",
"entryPoints",
".",
"forEach",
"(",
"(",
"module",
")",
"=>",
"{",
"entryPointsMap",
"[",
"module",
".",
"name",
"]",
"=",
"module",
";",
"}",
")",
";",
"const",
"allMentionedModulesMap",
"=",
"{",
"}",
";",
"entryPoints",
".",
"forEach",
"(",
"(",
"module",
")",
"=>",
"{",
"allMentionedModulesMap",
"[",
"module",
".",
"name",
"]",
"=",
"true",
";",
"(",
"module",
".",
"include",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"includedModule",
")",
"{",
"allMentionedModulesMap",
"[",
"includedModule",
"]",
"=",
"true",
";",
"}",
")",
";",
"(",
"module",
".",
"exclude",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"excludedModule",
")",
"{",
"allMentionedModulesMap",
"[",
"excludedModule",
"]",
"=",
"true",
";",
"}",
")",
";",
"}",
")",
";",
"const",
"code",
"=",
"require",
"(",
"'fs'",
")",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'../../src/vs/loader.js'",
")",
")",
";",
"const",
"r",
"=",
"vm",
".",
"runInThisContext",
"(",
"'(function(require, module, exports) { '",
"+",
"code",
"+",
"'\\n});'",
")",
";",
"const",
"loaderModule",
"=",
"{",
"exports",
":",
"{",
"}",
"}",
";",
"r",
".",
"call",
"(",
"{",
"}",
",",
"require",
",",
"loaderModule",
",",
"loaderModule",
".",
"exports",
")",
";",
"const",
"loader",
"=",
"loaderModule",
".",
"exports",
";",
"config",
".",
"isBuild",
"=",
"true",
";",
"config",
".",
"paths",
"=",
"config",
".",
"paths",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"config",
".",
"paths",
"[",
"'vs/nls'",
"]",
")",
"{",
"config",
".",
"paths",
"[",
"'vs/nls'",
"]",
"=",
"'out-build/vs/nls.build'",
";",
"}",
"if",
"(",
"!",
"config",
".",
"paths",
"[",
"'vs/css'",
"]",
")",
"{",
"config",
".",
"paths",
"[",
"'vs/css'",
"]",
"=",
"'out-build/vs/css.build'",
";",
"}",
"loader",
".",
"config",
"(",
"config",
")",
";",
"loader",
"(",
"[",
"'require'",
"]",
",",
"(",
"localRequire",
")",
"=>",
"{",
"const",
"resolvePath",
"=",
"(",
"path",
")",
"=>",
"{",
"const",
"r",
"=",
"localRequire",
".",
"toUrl",
"(",
"path",
")",
";",
"if",
"(",
"!",
"/",
"\\.js",
"/",
".",
"test",
"(",
"r",
")",
")",
"{",
"return",
"r",
"+",
"'.js'",
";",
"}",
"return",
"r",
";",
"}",
";",
"for",
"(",
"const",
"moduleId",
"in",
"entryPointsMap",
")",
"{",
"const",
"entryPoint",
"=",
"entryPointsMap",
"[",
"moduleId",
"]",
";",
"if",
"(",
"entryPoint",
".",
"append",
")",
"{",
"entryPoint",
".",
"append",
"=",
"entryPoint",
".",
"append",
".",
"map",
"(",
"resolvePath",
")",
";",
"}",
"if",
"(",
"entryPoint",
".",
"prepend",
")",
"{",
"entryPoint",
".",
"prepend",
"=",
"entryPoint",
".",
"prepend",
".",
"map",
"(",
"resolvePath",
")",
";",
"}",
"}",
"}",
")",
";",
"loader",
"(",
"Object",
".",
"keys",
"(",
"allMentionedModulesMap",
")",
",",
"(",
")",
"=>",
"{",
"const",
"modules",
"=",
"loader",
".",
"getBuildInfo",
"(",
")",
";",
"const",
"partialResult",
"=",
"emitEntryPoints",
"(",
"modules",
",",
"entryPointsMap",
")",
";",
"const",
"cssInlinedResources",
"=",
"loader",
"(",
"'vs/css'",
")",
".",
"getInlinedResources",
"(",
")",
";",
"callback",
"(",
"null",
",",
"{",
"files",
":",
"partialResult",
".",
"files",
",",
"cssInlinedResources",
":",
"cssInlinedResources",
",",
"bundleData",
":",
"partialResult",
".",
"bundleData",
"}",
")",
";",
"}",
",",
"(",
"err",
")",
"=>",
"callback",
"(",
"err",
",",
"null",
")",
")",
";",
"}"
] | Bundle `entryPoints` given config `config`. | [
"Bundle",
"entryPoints",
"given",
"config",
"config",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L13-L70 |
7 | Microsoft/vscode | build/lib/bundle.js | visit | function visit(rootNodes, graph) {
const result = {};
const queue = rootNodes;
rootNodes.forEach((node) => {
result[node] = true;
});
while (queue.length > 0) {
const el = queue.shift();
const myEdges = graph[el] || [];
myEdges.forEach((toNode) => {
if (!result[toNode]) {
result[toNode] = true;
queue.push(toNode);
}
});
}
return result;
} | javascript | function visit(rootNodes, graph) {
const result = {};
const queue = rootNodes;
rootNodes.forEach((node) => {
result[node] = true;
});
while (queue.length > 0) {
const el = queue.shift();
const myEdges = graph[el] || [];
myEdges.forEach((toNode) => {
if (!result[toNode]) {
result[toNode] = true;
queue.push(toNode);
}
});
}
return result;
} | [
"function",
"visit",
"(",
"rootNodes",
",",
"graph",
")",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"const",
"queue",
"=",
"rootNodes",
";",
"rootNodes",
".",
"forEach",
"(",
"(",
"node",
")",
"=>",
"{",
"result",
"[",
"node",
"]",
"=",
"true",
";",
"}",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"const",
"el",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"const",
"myEdges",
"=",
"graph",
"[",
"el",
"]",
"||",
"[",
"]",
";",
"myEdges",
".",
"forEach",
"(",
"(",
"toNode",
")",
"=>",
"{",
"if",
"(",
"!",
"result",
"[",
"toNode",
"]",
")",
"{",
"result",
"[",
"toNode",
"]",
"=",
"true",
";",
"queue",
".",
"push",
"(",
"toNode",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Return a set of reachable nodes in `graph` starting from `rootNodes` | [
"Return",
"a",
"set",
"of",
"reachable",
"nodes",
"in",
"graph",
"starting",
"from",
"rootNodes"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L404-L421 |
8 | Microsoft/vscode | build/lib/bundle.js | topologicalSort | function topologicalSort(graph) {
const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || [];
inverseEdges[toNode].push(fromNode);
});
});
// https://en.wikipedia.org/wiki/Topological_sorting
const S = [], L = [];
Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node];
S.push(node);
}
});
while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs
S.sort();
const n = S.shift();
L.push(n);
const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m];
S.push(m);
}
});
}
if (Object.keys(outgoingEdgeCount).length > 0) {
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
}
return L;
} | javascript | function topologicalSort(graph) {
const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || [];
inverseEdges[toNode].push(fromNode);
});
});
// https://en.wikipedia.org/wiki/Topological_sorting
const S = [], L = [];
Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node];
S.push(node);
}
});
while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs
S.sort();
const n = S.shift();
L.push(n);
const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m];
S.push(m);
}
});
}
if (Object.keys(outgoingEdgeCount).length > 0) {
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
}
return L;
} | [
"function",
"topologicalSort",
"(",
"graph",
")",
"{",
"const",
"allNodes",
"=",
"{",
"}",
",",
"outgoingEdgeCount",
"=",
"{",
"}",
",",
"inverseEdges",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"graph",
")",
".",
"forEach",
"(",
"(",
"fromNode",
")",
"=>",
"{",
"allNodes",
"[",
"fromNode",
"]",
"=",
"true",
";",
"outgoingEdgeCount",
"[",
"fromNode",
"]",
"=",
"graph",
"[",
"fromNode",
"]",
".",
"length",
";",
"graph",
"[",
"fromNode",
"]",
".",
"forEach",
"(",
"(",
"toNode",
")",
"=>",
"{",
"allNodes",
"[",
"toNode",
"]",
"=",
"true",
";",
"outgoingEdgeCount",
"[",
"toNode",
"]",
"=",
"outgoingEdgeCount",
"[",
"toNode",
"]",
"||",
"0",
";",
"inverseEdges",
"[",
"toNode",
"]",
"=",
"inverseEdges",
"[",
"toNode",
"]",
"||",
"[",
"]",
";",
"inverseEdges",
"[",
"toNode",
"]",
".",
"push",
"(",
"fromNode",
")",
";",
"}",
")",
";",
"}",
")",
";",
"// https://en.wikipedia.org/wiki/Topological_sorting",
"const",
"S",
"=",
"[",
"]",
",",
"L",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"allNodes",
")",
".",
"forEach",
"(",
"(",
"node",
")",
"=>",
"{",
"if",
"(",
"outgoingEdgeCount",
"[",
"node",
"]",
"===",
"0",
")",
"{",
"delete",
"outgoingEdgeCount",
"[",
"node",
"]",
";",
"S",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
")",
";",
"while",
"(",
"S",
".",
"length",
">",
"0",
")",
"{",
"// Ensure the exact same order all the time with the same inputs",
"S",
".",
"sort",
"(",
")",
";",
"const",
"n",
"=",
"S",
".",
"shift",
"(",
")",
";",
"L",
".",
"push",
"(",
"n",
")",
";",
"const",
"myInverseEdges",
"=",
"inverseEdges",
"[",
"n",
"]",
"||",
"[",
"]",
";",
"myInverseEdges",
".",
"forEach",
"(",
"(",
"m",
")",
"=>",
"{",
"outgoingEdgeCount",
"[",
"m",
"]",
"--",
";",
"if",
"(",
"outgoingEdgeCount",
"[",
"m",
"]",
"===",
"0",
")",
"{",
"delete",
"outgoingEdgeCount",
"[",
"m",
"]",
";",
"S",
".",
"push",
"(",
"m",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"outgoingEdgeCount",
")",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot do topological sort on cyclic graph, remaining nodes: '",
"+",
"Object",
".",
"keys",
"(",
"outgoingEdgeCount",
")",
")",
";",
"}",
"return",
"L",
";",
"}"
] | Perform a topological sort on `graph` | [
"Perform",
"a",
"topological",
"sort",
"on",
"graph"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/bundle.js#L425-L463 |
9 | Microsoft/vscode | build/lib/git.js | getVersion | function getVersion(repo) {
const git = path.join(repo, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return undefined;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
}
catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
} | javascript | function getVersion(repo) {
const git = path.join(repo, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return undefined;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
}
catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
}
catch (e) {
return undefined;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
} | [
"function",
"getVersion",
"(",
"repo",
")",
"{",
"const",
"git",
"=",
"path",
".",
"join",
"(",
"repo",
",",
"'.git'",
")",
";",
"const",
"headPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"'HEAD'",
")",
";",
"let",
"head",
";",
"try",
"{",
"head",
"=",
"fs",
".",
"readFileSync",
"(",
"headPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"undefined",
";",
"}",
"if",
"(",
"/",
"^[0-9a-f]{40}$",
"/",
"i",
".",
"test",
"(",
"head",
")",
")",
"{",
"return",
"head",
";",
"}",
"const",
"refMatch",
"=",
"/",
"^ref: (.*)$",
"/",
".",
"exec",
"(",
"head",
")",
";",
"if",
"(",
"!",
"refMatch",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"ref",
"=",
"refMatch",
"[",
"1",
"]",
";",
"const",
"refPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"ref",
")",
";",
"try",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"refPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// noop",
"}",
"const",
"packedRefsPath",
"=",
"path",
".",
"join",
"(",
"git",
",",
"'packed-refs'",
")",
";",
"let",
"refsRaw",
";",
"try",
"{",
"refsRaw",
"=",
"fs",
".",
"readFileSync",
"(",
"packedRefsPath",
",",
"'utf8'",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"refsRegex",
"=",
"/",
"^([0-9a-f]{40})\\s+(.+)$",
"/",
"gm",
";",
"let",
"refsMatch",
";",
"let",
"refs",
"=",
"{",
"}",
";",
"while",
"(",
"refsMatch",
"=",
"refsRegex",
".",
"exec",
"(",
"refsRaw",
")",
")",
"{",
"refs",
"[",
"refsMatch",
"[",
"2",
"]",
"]",
"=",
"refsMatch",
"[",
"1",
"]",
";",
"}",
"return",
"refs",
"[",
"ref",
"]",
";",
"}"
] | Returns the sha1 commit version of a repository or undefined in case of failure. | [
"Returns",
"the",
"sha1",
"commit",
"version",
"of",
"a",
"repository",
"or",
"undefined",
"in",
"case",
"of",
"failure",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/lib/git.js#L12-L52 |
10 | Microsoft/vscode | src/bootstrap-fork.js | safeToArray | function safeToArray(args) {
const seen = [];
const argsArray = [];
let res;
// Massage some arguments with special treatment
if (args.length) {
for (let i = 0; i < args.length; i++) {
// Any argument of type 'undefined' needs to be specially treated because
// JSON.stringify will simply ignore those. We replace them with the string
// 'undefined' which is not 100% right, but good enough to be logged to console
if (typeof args[i] === 'undefined') {
args[i] = 'undefined';
}
// Any argument that is an Error will be changed to be just the error stack/message
// itself because currently cannot serialize the error over entirely.
else if (args[i] instanceof Error) {
const errorObj = args[i];
if (errorObj.stack) {
args[i] = errorObj.stack;
} else {
args[i] = errorObj.toString();
}
}
argsArray.push(args[i]);
}
}
// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames
// to start the stacktrace where the console message was being written
if (process.env.VSCODE_LOG_STACK === 'true') {
const stack = new Error().stack;
argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') });
}
try {
res = JSON.stringify(argsArray, function (key, value) {
// Objects get special treatment to prevent circles
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
} catch (error) {
return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')';
}
if (res && res.length > MAX_LENGTH) {
return 'Output omitted for a large object that exceeds the limits';
}
return res;
} | javascript | function safeToArray(args) {
const seen = [];
const argsArray = [];
let res;
// Massage some arguments with special treatment
if (args.length) {
for (let i = 0; i < args.length; i++) {
// Any argument of type 'undefined' needs to be specially treated because
// JSON.stringify will simply ignore those. We replace them with the string
// 'undefined' which is not 100% right, but good enough to be logged to console
if (typeof args[i] === 'undefined') {
args[i] = 'undefined';
}
// Any argument that is an Error will be changed to be just the error stack/message
// itself because currently cannot serialize the error over entirely.
else if (args[i] instanceof Error) {
const errorObj = args[i];
if (errorObj.stack) {
args[i] = errorObj.stack;
} else {
args[i] = errorObj.toString();
}
}
argsArray.push(args[i]);
}
}
// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames
// to start the stacktrace where the console message was being written
if (process.env.VSCODE_LOG_STACK === 'true') {
const stack = new Error().stack;
argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') });
}
try {
res = JSON.stringify(argsArray, function (key, value) {
// Objects get special treatment to prevent circles
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
} catch (error) {
return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')';
}
if (res && res.length > MAX_LENGTH) {
return 'Output omitted for a large object that exceeds the limits';
}
return res;
} | [
"function",
"safeToArray",
"(",
"args",
")",
"{",
"const",
"seen",
"=",
"[",
"]",
";",
"const",
"argsArray",
"=",
"[",
"]",
";",
"let",
"res",
";",
"// Massage some arguments with special treatment",
"if",
"(",
"args",
".",
"length",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Any argument of type 'undefined' needs to be specially treated because",
"// JSON.stringify will simply ignore those. We replace them with the string",
"// 'undefined' which is not 100% right, but good enough to be logged to console",
"if",
"(",
"typeof",
"args",
"[",
"i",
"]",
"===",
"'undefined'",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"'undefined'",
";",
"}",
"// Any argument that is an Error will be changed to be just the error stack/message",
"// itself because currently cannot serialize the error over entirely.",
"else",
"if",
"(",
"args",
"[",
"i",
"]",
"instanceof",
"Error",
")",
"{",
"const",
"errorObj",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"errorObj",
".",
"stack",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"errorObj",
".",
"stack",
";",
"}",
"else",
"{",
"args",
"[",
"i",
"]",
"=",
"errorObj",
".",
"toString",
"(",
")",
";",
"}",
"}",
"argsArray",
".",
"push",
"(",
"args",
"[",
"i",
"]",
")",
";",
"}",
"}",
"// Add the stack trace as payload if we are told so. We remove the message and the 2 top frames",
"// to start the stacktrace where the console message was being written",
"if",
"(",
"process",
".",
"env",
".",
"VSCODE_LOG_STACK",
"===",
"'true'",
")",
"{",
"const",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
";",
"argsArray",
".",
"push",
"(",
"{",
"__$stack",
":",
"stack",
".",
"split",
"(",
"'\\n'",
")",
".",
"slice",
"(",
"3",
")",
".",
"join",
"(",
"'\\n'",
")",
"}",
")",
";",
"}",
"try",
"{",
"res",
"=",
"JSON",
".",
"stringify",
"(",
"argsArray",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"// Objects get special treatment to prevent circles",
"if",
"(",
"isObject",
"(",
"value",
")",
"||",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"if",
"(",
"seen",
".",
"indexOf",
"(",
"value",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"'[Circular]'",
";",
"}",
"seen",
".",
"push",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"'Output omitted for an object that cannot be inspected ('",
"+",
"error",
".",
"toString",
"(",
")",
"+",
"')'",
";",
"}",
"if",
"(",
"res",
"&&",
"res",
".",
"length",
">",
"MAX_LENGTH",
")",
"{",
"return",
"'Output omitted for a large object that exceeds the limits'",
";",
"}",
"return",
"res",
";",
"}"
] | Prevent circular stringify and convert arguments to real array | [
"Prevent",
"circular",
"stringify",
"and",
"convert",
"arguments",
"to",
"real",
"array"
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/src/bootstrap-fork.js#L50-L112 |
11 | Microsoft/vscode | build/gulpfile.vscode.js | computeChecksums | function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
} | javascript | function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
} | [
"function",
"computeChecksums",
"(",
"out",
",",
"filenames",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"filenames",
".",
"forEach",
"(",
"function",
"(",
"filename",
")",
"{",
"var",
"fullPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"out",
",",
"filename",
")",
";",
"result",
"[",
"filename",
"]",
"=",
"computeChecksum",
"(",
"fullPath",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Compute checksums for some files.
@param {string} out The out folder to read the file from.
@param {string[]} filenames The paths to compute a checksum for.
@return {Object} A map of paths to checksums. | [
"Compute",
"checksums",
"for",
"some",
"files",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/gulpfile.vscode.js#L230-L237 |
12 | Microsoft/vscode | build/gulpfile.vscode.js | computeChecksum | function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
} | javascript | function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
} | [
"function",
"computeChecksum",
"(",
"filename",
")",
"{",
"var",
"contents",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
";",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"contents",
")",
".",
"digest",
"(",
"'base64'",
")",
".",
"replace",
"(",
"/",
"=+$",
"/",
",",
"''",
")",
";",
"return",
"hash",
";",
"}"
] | Compute checksum for a file.
@param {string} filename The absolute path to a filename.
@return {string} The checksum for `filename`. | [
"Compute",
"checksum",
"for",
"a",
"file",
"."
] | 693a13cd32c5be798051edc0cb43e1e39fc456d9 | https://github.com/Microsoft/vscode/blob/693a13cd32c5be798051edc0cb43e1e39fc456d9/build/gulpfile.vscode.js#L245-L255 |
13 | angular/angular | aio/tools/transforms/angular-base-package/rendering/hasValues.js | readProperty | function readProperty(obj, propertySegments, index) {
const value = obj[propertySegments[index]];
return !!value && (index === propertySegments.length - 1 || readProperty(value, propertySegments, index + 1));
} | javascript | function readProperty(obj, propertySegments, index) {
const value = obj[propertySegments[index]];
return !!value && (index === propertySegments.length - 1 || readProperty(value, propertySegments, index + 1));
} | [
"function",
"readProperty",
"(",
"obj",
",",
"propertySegments",
",",
"index",
")",
"{",
"const",
"value",
"=",
"obj",
"[",
"propertySegments",
"[",
"index",
"]",
"]",
";",
"return",
"!",
"!",
"value",
"&&",
"(",
"index",
"===",
"propertySegments",
".",
"length",
"-",
"1",
"||",
"readProperty",
"(",
"value",
",",
"propertySegments",
",",
"index",
"+",
"1",
")",
")",
";",
"}"
] | Search deeply into an object via a collection of property segments, starting at the
indexed segment.
E.g. if `obj = { a: { b: { c: 10 }}}` then
`readProperty(obj, ['a', 'b', 'c'], 0)` will return true;
but
`readProperty(obj, ['a', 'd'], 0)` will return false; | [
"Search",
"deeply",
"into",
"an",
"object",
"via",
"a",
"collection",
"of",
"property",
"segments",
"starting",
"at",
"the",
"indexed",
"segment",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/angular-base-package/rendering/hasValues.js#L20-L23 |
14 | angular/angular | tools/gulp-tasks/cldr/extract.js | generateLocale | function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([
locale,
...getDateTimeTranslations(localeData),
...getDateTimeSettings(localeData),
...getNumberSettings(localeData),
...getCurrencySettings(locale, localeData),
generateLocaleCurrencies(localeData, baseCurrencies)
], true)
// We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
return `${HEADER}
const u = undefined;
${getPluralFunction(locale)}
export default ${data};
`;
} | javascript | function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([
locale,
...getDateTimeTranslations(localeData),
...getDateTimeSettings(localeData),
...getNumberSettings(localeData),
...getCurrencySettings(locale, localeData),
generateLocaleCurrencies(localeData, baseCurrencies)
], true)
// We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
return `${HEADER}
const u = undefined;
${getPluralFunction(locale)}
export default ${data};
`;
} | [
"function",
"generateLocale",
"(",
"locale",
",",
"localeData",
",",
"baseCurrencies",
")",
"{",
"// [ localeId, dateTime, number, currency, pluralCase ]",
"let",
"data",
"=",
"stringify",
"(",
"[",
"locale",
",",
"...",
"getDateTimeTranslations",
"(",
"localeData",
")",
",",
"...",
"getDateTimeSettings",
"(",
"localeData",
")",
",",
"...",
"getNumberSettings",
"(",
"localeData",
")",
",",
"...",
"getCurrencySettings",
"(",
"locale",
",",
"localeData",
")",
",",
"generateLocaleCurrencies",
"(",
"localeData",
",",
"baseCurrencies",
")",
"]",
",",
"true",
")",
"// We remove \"undefined\" added by spreading arrays when there is no value",
".",
"replace",
"(",
"/",
"undefined",
"/",
"g",
",",
"'u'",
")",
";",
"// adding plural function after, because we don't want it as a string",
"data",
"=",
"data",
".",
"substring",
"(",
"0",
",",
"data",
".",
"lastIndexOf",
"(",
"']'",
")",
")",
"+",
"`",
"`",
";",
"return",
"`",
"${",
"HEADER",
"}",
"${",
"getPluralFunction",
"(",
"locale",
")",
"}",
"${",
"data",
"}",
"`",
";",
"}"
] | Generate file that contains basic locale data | [
"Generate",
"file",
"that",
"contains",
"basic",
"locale",
"data"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L94-L117 |
15 | angular/angular | tools/gulp-tasks/cldr/extract.js | generateLocaleCurrencies | function generateLocaleCurrencies(localeData, baseCurrencies) {
const currenciesData = localeData.main('numbers/currencies');
const currencies = {};
Object.keys(currenciesData).forEach(code => {
let symbolsArray = [];
const symbol = currenciesData[code].symbol;
const symbolNarrow = currenciesData[code]['symbol-alt-narrow'];
if (symbol && symbol !== code) {
symbolsArray.push(symbol);
}
if (symbolNarrow && symbolNarrow !== symbol) {
if (symbolsArray.length > 0) {
symbolsArray.push(symbolNarrow);
} else {
symbolsArray = [undefined, symbolNarrow];
}
}
// if locale data are different, set the value
if ((baseCurrencies[code] || []).toString() !== symbolsArray.toString()) {
currencies[code] = symbolsArray;
}
});
return currencies;
} | javascript | function generateLocaleCurrencies(localeData, baseCurrencies) {
const currenciesData = localeData.main('numbers/currencies');
const currencies = {};
Object.keys(currenciesData).forEach(code => {
let symbolsArray = [];
const symbol = currenciesData[code].symbol;
const symbolNarrow = currenciesData[code]['symbol-alt-narrow'];
if (symbol && symbol !== code) {
symbolsArray.push(symbol);
}
if (symbolNarrow && symbolNarrow !== symbol) {
if (symbolsArray.length > 0) {
symbolsArray.push(symbolNarrow);
} else {
symbolsArray = [undefined, symbolNarrow];
}
}
// if locale data are different, set the value
if ((baseCurrencies[code] || []).toString() !== symbolsArray.toString()) {
currencies[code] = symbolsArray;
}
});
return currencies;
} | [
"function",
"generateLocaleCurrencies",
"(",
"localeData",
",",
"baseCurrencies",
")",
"{",
"const",
"currenciesData",
"=",
"localeData",
".",
"main",
"(",
"'numbers/currencies'",
")",
";",
"const",
"currencies",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"currenciesData",
")",
".",
"forEach",
"(",
"code",
"=>",
"{",
"let",
"symbolsArray",
"=",
"[",
"]",
";",
"const",
"symbol",
"=",
"currenciesData",
"[",
"code",
"]",
".",
"symbol",
";",
"const",
"symbolNarrow",
"=",
"currenciesData",
"[",
"code",
"]",
"[",
"'symbol-alt-narrow'",
"]",
";",
"if",
"(",
"symbol",
"&&",
"symbol",
"!==",
"code",
")",
"{",
"symbolsArray",
".",
"push",
"(",
"symbol",
")",
";",
"}",
"if",
"(",
"symbolNarrow",
"&&",
"symbolNarrow",
"!==",
"symbol",
")",
"{",
"if",
"(",
"symbolsArray",
".",
"length",
">",
"0",
")",
"{",
"symbolsArray",
".",
"push",
"(",
"symbolNarrow",
")",
";",
"}",
"else",
"{",
"symbolsArray",
"=",
"[",
"undefined",
",",
"symbolNarrow",
"]",
";",
"}",
"}",
"// if locale data are different, set the value",
"if",
"(",
"(",
"baseCurrencies",
"[",
"code",
"]",
"||",
"[",
"]",
")",
".",
"toString",
"(",
")",
"!==",
"symbolsArray",
".",
"toString",
"(",
")",
")",
"{",
"currencies",
"[",
"code",
"]",
"=",
"symbolsArray",
";",
"}",
"}",
")",
";",
"return",
"currencies",
";",
"}"
] | To minimize the file even more, we only output the differences compared to the base currency | [
"To",
"minimize",
"the",
"file",
"even",
"more",
"we",
"only",
"output",
"the",
"differences",
"compared",
"to",
"the",
"base",
"currency"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L201-L225 |
16 | angular/angular | tools/gulp-tasks/cldr/extract.js | getDayPeriods | function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {};
// cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {};
Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
if (dayPeriodsList.indexOf(key3) !== -1) {
result[key1][key2][key3] = dayPeriods[key1][key2][key3];
}
});
});
});
return result;
} | javascript | function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {};
// cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {};
Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
if (dayPeriodsList.indexOf(key3) !== -1) {
result[key1][key2][key3] = dayPeriods[key1][key2][key3];
}
});
});
});
return result;
} | [
"function",
"getDayPeriods",
"(",
"localeData",
",",
"dayPeriodsList",
")",
"{",
"const",
"dayPeriods",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"result",
"=",
"{",
"}",
";",
"// cleaning up unused keys",
"Object",
".",
"keys",
"(",
"dayPeriods",
")",
".",
"forEach",
"(",
"key1",
"=>",
"{",
"// format / stand-alone",
"result",
"[",
"key1",
"]",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"dayPeriods",
"[",
"key1",
"]",
")",
".",
"forEach",
"(",
"key2",
"=>",
"{",
"// narrow / abbreviated / wide",
"result",
"[",
"key1",
"]",
"[",
"key2",
"]",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"dayPeriods",
"[",
"key1",
"]",
"[",
"key2",
"]",
")",
".",
"forEach",
"(",
"key3",
"=>",
"{",
"if",
"(",
"dayPeriodsList",
".",
"indexOf",
"(",
"key3",
")",
"!==",
"-",
"1",
")",
"{",
"result",
"[",
"key1",
"]",
"[",
"key2",
"]",
"[",
"key3",
"]",
"=",
"dayPeriods",
"[",
"key1",
"]",
"[",
"key2",
"]",
"[",
"key3",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Returns data for the chosen day periods
@returns {format: {narrow / abbreviated / wide: [...]}, stand-alone: {narrow / abbreviated / wide: [...]}} | [
"Returns",
"data",
"for",
"the",
"chosen",
"day",
"periods"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L245-L262 |
17 | angular/angular | tools/gulp-tasks/cldr/extract.js | getDateTimeTranslations | function getDateTimeTranslations(localeData) {
const dayNames = localeData.main(`dates/calendars/gregorian/days`);
const monthNames = localeData.main(`dates/calendars/gregorian/months`);
const erasNames = localeData.main(`dates/calendars/gregorian/eras`);
const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide)
]);
const dayPeriodsStandalone = removeDuplicates([
objectValues(dayPeriods['stand-alone'].narrow),
objectValues(dayPeriods['stand-alone'].abbreviated),
objectValues(dayPeriods['stand-alone'].wide)
]);
const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow),
objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]);
const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow),
objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]);
const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide)
]);
const monthsStandalone = removeDuplicates([
objectValues(monthNames['stand-alone'].narrow),
objectValues(monthNames['stand-alone'].abbreviated),
objectValues(monthNames['stand-alone'].wide)
]);
const eras = removeDuplicates([
[erasNames.eraNarrow['0'], erasNames.eraNarrow['1']],
[erasNames.eraAbbr['0'], erasNames.eraAbbr['1']],
[erasNames.eraNames['0'], erasNames.eraNames['1']]
]);
const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]),
eras
];
return dateTimeTranslations;
} | javascript | function getDateTimeTranslations(localeData) {
const dayNames = localeData.main(`dates/calendars/gregorian/days`);
const monthNames = localeData.main(`dates/calendars/gregorian/months`);
const erasNames = localeData.main(`dates/calendars/gregorian/eras`);
const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide)
]);
const dayPeriodsStandalone = removeDuplicates([
objectValues(dayPeriods['stand-alone'].narrow),
objectValues(dayPeriods['stand-alone'].abbreviated),
objectValues(dayPeriods['stand-alone'].wide)
]);
const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow),
objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]);
const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow),
objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]);
const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide)
]);
const monthsStandalone = removeDuplicates([
objectValues(monthNames['stand-alone'].narrow),
objectValues(monthNames['stand-alone'].abbreviated),
objectValues(monthNames['stand-alone'].wide)
]);
const eras = removeDuplicates([
[erasNames.eraNarrow['0'], erasNames.eraNarrow['1']],
[erasNames.eraAbbr['0'], erasNames.eraAbbr['1']],
[erasNames.eraNames['0'], erasNames.eraNames['1']]
]);
const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]),
eras
];
return dateTimeTranslations;
} | [
"function",
"getDateTimeTranslations",
"(",
"localeData",
")",
"{",
"const",
"dayNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"monthNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"erasNames",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"const",
"dayPeriods",
"=",
"getDayPeriodsAmPm",
"(",
"localeData",
")",
";",
"const",
"dayPeriodsFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayPeriods",
".",
"format",
".",
"wide",
")",
"]",
")",
";",
"const",
"dayPeriodsStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayPeriods",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
"]",
")",
";",
"const",
"daysFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"wide",
")",
",",
"objectValues",
"(",
"dayNames",
".",
"format",
".",
"short",
")",
"]",
")",
";",
"const",
"daysStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
",",
"objectValues",
"(",
"dayNames",
"[",
"'stand-alone'",
"]",
".",
"short",
")",
"]",
")",
";",
"const",
"monthsFormat",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"narrow",
")",
",",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"monthNames",
".",
"format",
".",
"wide",
")",
"]",
")",
";",
"const",
"monthsStandalone",
"=",
"removeDuplicates",
"(",
"[",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"narrow",
")",
",",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"abbreviated",
")",
",",
"objectValues",
"(",
"monthNames",
"[",
"'stand-alone'",
"]",
".",
"wide",
")",
"]",
")",
";",
"const",
"eras",
"=",
"removeDuplicates",
"(",
"[",
"[",
"erasNames",
".",
"eraNarrow",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraNarrow",
"[",
"'1'",
"]",
"]",
",",
"[",
"erasNames",
".",
"eraAbbr",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraAbbr",
"[",
"'1'",
"]",
"]",
",",
"[",
"erasNames",
".",
"eraNames",
"[",
"'0'",
"]",
",",
"erasNames",
".",
"eraNames",
"[",
"'1'",
"]",
"]",
"]",
")",
";",
"const",
"dateTimeTranslations",
"=",
"[",
"...",
"removeDuplicates",
"(",
"[",
"dayPeriodsFormat",
",",
"dayPeriodsStandalone",
"]",
")",
",",
"...",
"removeDuplicates",
"(",
"[",
"daysFormat",
",",
"daysStandalone",
"]",
")",
",",
"...",
"removeDuplicates",
"(",
"[",
"monthsFormat",
",",
"monthsStandalone",
"]",
")",
",",
"eras",
"]",
";",
"return",
"dateTimeTranslations",
";",
"}"
] | Returns date-related translations for a locale
@returns [ dayPeriodsFormat, dayPeriodsStandalone, daysFormat, dayStandalone, monthsFormat, monthsStandalone, eras ]
each value: [ narrow, abbreviated, wide, short? ] | [
"Returns",
"date",
"-",
"related",
"translations",
"for",
"a",
"locale"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L284-L342 |
18 | angular/angular | tools/gulp-tasks/cldr/extract.js | getDateTimeFormats | function getDateTimeFormats(localeData) {
function getFormats(data) {
return removeDuplicates([
data.short._value || data.short,
data.medium._value || data.medium,
data.long._value || data.long,
data.full._value || data.full
]);
}
const dateFormats = localeData.main('dates/calendars/gregorian/dateFormats');
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
} | javascript | function getDateTimeFormats(localeData) {
function getFormats(data) {
return removeDuplicates([
data.short._value || data.short,
data.medium._value || data.medium,
data.long._value || data.long,
data.full._value || data.full
]);
}
const dateFormats = localeData.main('dates/calendars/gregorian/dateFormats');
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
} | [
"function",
"getDateTimeFormats",
"(",
"localeData",
")",
"{",
"function",
"getFormats",
"(",
"data",
")",
"{",
"return",
"removeDuplicates",
"(",
"[",
"data",
".",
"short",
".",
"_value",
"||",
"data",
".",
"short",
",",
"data",
".",
"medium",
".",
"_value",
"||",
"data",
".",
"medium",
",",
"data",
".",
"long",
".",
"_value",
"||",
"data",
".",
"long",
",",
"data",
".",
"full",
".",
"_value",
"||",
"data",
".",
"full",
"]",
")",
";",
"}",
"const",
"dateFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/dateFormats'",
")",
";",
"const",
"timeFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/timeFormats'",
")",
";",
"const",
"dateTimeFormats",
"=",
"localeData",
".",
"main",
"(",
"'dates/calendars/gregorian/dateTimeFormats'",
")",
";",
"return",
"[",
"getFormats",
"(",
"dateFormats",
")",
",",
"getFormats",
"(",
"timeFormats",
")",
",",
"getFormats",
"(",
"dateTimeFormats",
")",
"]",
";",
"}"
] | Returns date, time and dateTime formats for a locale
@returns [dateFormats, timeFormats, dateTimeFormats]
each format: [ short, medium, long, full ] | [
"Returns",
"date",
"time",
"and",
"dateTime",
"formats",
"for",
"a",
"locale"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L349-L368 |
19 | angular/angular | tools/gulp-tasks/cldr/extract.js | getDayPeriodRules | function getDayPeriodRules(localeData) {
const dayPeriodRules = localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`);
const rules = {};
if (dayPeriodRules) {
Object.keys(dayPeriodRules).forEach(key => {
if (dayPeriodRules[key]._at) {
rules[key] = dayPeriodRules[key]._at;
} else {
rules[key] = [dayPeriodRules[key]._from, dayPeriodRules[key]._before];
}
});
}
return rules;
} | javascript | function getDayPeriodRules(localeData) {
const dayPeriodRules = localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`);
const rules = {};
if (dayPeriodRules) {
Object.keys(dayPeriodRules).forEach(key => {
if (dayPeriodRules[key]._at) {
rules[key] = dayPeriodRules[key]._at;
} else {
rules[key] = [dayPeriodRules[key]._from, dayPeriodRules[key]._before];
}
});
}
return rules;
} | [
"function",
"getDayPeriodRules",
"(",
"localeData",
")",
"{",
"const",
"dayPeriodRules",
"=",
"localeData",
".",
"get",
"(",
"`",
"${",
"localeData",
".",
"attributes",
".",
"language",
"}",
"`",
")",
";",
"const",
"rules",
"=",
"{",
"}",
";",
"if",
"(",
"dayPeriodRules",
")",
"{",
"Object",
".",
"keys",
"(",
"dayPeriodRules",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"if",
"(",
"dayPeriodRules",
"[",
"key",
"]",
".",
"_at",
")",
"{",
"rules",
"[",
"key",
"]",
"=",
"dayPeriodRules",
"[",
"key",
"]",
".",
"_at",
";",
"}",
"else",
"{",
"rules",
"[",
"key",
"]",
"=",
"[",
"dayPeriodRules",
"[",
"key",
"]",
".",
"_from",
",",
"dayPeriodRules",
"[",
"key",
"]",
".",
"_before",
"]",
";",
"}",
"}",
")",
";",
"}",
"return",
"rules",
";",
"}"
] | Returns day period rules for a locale
@returns string[] | [
"Returns",
"day",
"period",
"rules",
"for",
"a",
"locale"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L374-L388 |
20 | angular/angular | tools/gulp-tasks/cldr/extract.js | getWeekendRange | function getWeekendRange(localeData) {
const startDay =
localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendStart/001');
const endDay =
localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendEnd/001');
return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)];
} | javascript | function getWeekendRange(localeData) {
const startDay =
localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendStart/001');
const endDay =
localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendEnd/001');
return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)];
} | [
"function",
"getWeekendRange",
"(",
"localeData",
")",
"{",
"const",
"startDay",
"=",
"localeData",
".",
"get",
"(",
"`",
"${",
"localeData",
".",
"attributes",
".",
"territory",
"}",
"`",
")",
"||",
"localeData",
".",
"get",
"(",
"'supplemental/weekData/weekendStart/001'",
")",
";",
"const",
"endDay",
"=",
"localeData",
".",
"get",
"(",
"`",
"${",
"localeData",
".",
"attributes",
".",
"territory",
"}",
"`",
")",
"||",
"localeData",
".",
"get",
"(",
"'supplemental/weekData/weekendEnd/001'",
")",
";",
"return",
"[",
"WEEK_DAYS",
".",
"indexOf",
"(",
"startDay",
")",
",",
"WEEK_DAYS",
".",
"indexOf",
"(",
"endDay",
")",
"]",
";",
"}"
] | Returns week-end range for a locale, based on US week days
@returns [number, number] | [
"Returns",
"week",
"-",
"end",
"range",
"for",
"a",
"locale",
"based",
"on",
"US",
"week",
"days"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L402-L410 |
21 | angular/angular | tools/gulp-tasks/cldr/extract.js | getNumberSettings | function getNumberSettings(localeData) {
const decimalFormat = localeData.main('numbers/decimalFormats-numberSystem-latn/standard');
const percentFormat = localeData.main('numbers/percentFormats-numberSystem-latn/standard');
const scientificFormat = localeData.main('numbers/scientificFormats-numberSystem-latn/standard');
const currencyFormat = localeData.main('numbers/currencyFormats-numberSystem-latn/standard');
const symbols = localeData.main('numbers/symbols-numberSystem-latn');
const symbolValues = [
symbols.decimal,
symbols.group,
symbols.list,
symbols.percentSign,
symbols.plusSign,
symbols.minusSign,
symbols.exponential,
symbols.superscriptingExponent,
symbols.perMille,
symbols.infinity,
symbols.nan,
symbols.timeSeparator,
];
if (symbols.currencyDecimal || symbols.currencyGroup) {
symbolValues.push(symbols.currencyDecimal);
}
if (symbols.currencyGroup) {
symbolValues.push(symbols.currencyGroup);
}
return [
symbolValues,
[decimalFormat, percentFormat, currencyFormat, scientificFormat]
];
} | javascript | function getNumberSettings(localeData) {
const decimalFormat = localeData.main('numbers/decimalFormats-numberSystem-latn/standard');
const percentFormat = localeData.main('numbers/percentFormats-numberSystem-latn/standard');
const scientificFormat = localeData.main('numbers/scientificFormats-numberSystem-latn/standard');
const currencyFormat = localeData.main('numbers/currencyFormats-numberSystem-latn/standard');
const symbols = localeData.main('numbers/symbols-numberSystem-latn');
const symbolValues = [
symbols.decimal,
symbols.group,
symbols.list,
symbols.percentSign,
symbols.plusSign,
symbols.minusSign,
symbols.exponential,
symbols.superscriptingExponent,
symbols.perMille,
symbols.infinity,
symbols.nan,
symbols.timeSeparator,
];
if (symbols.currencyDecimal || symbols.currencyGroup) {
symbolValues.push(symbols.currencyDecimal);
}
if (symbols.currencyGroup) {
symbolValues.push(symbols.currencyGroup);
}
return [
symbolValues,
[decimalFormat, percentFormat, currencyFormat, scientificFormat]
];
} | [
"function",
"getNumberSettings",
"(",
"localeData",
")",
"{",
"const",
"decimalFormat",
"=",
"localeData",
".",
"main",
"(",
"'numbers/decimalFormats-numberSystem-latn/standard'",
")",
";",
"const",
"percentFormat",
"=",
"localeData",
".",
"main",
"(",
"'numbers/percentFormats-numberSystem-latn/standard'",
")",
";",
"const",
"scientificFormat",
"=",
"localeData",
".",
"main",
"(",
"'numbers/scientificFormats-numberSystem-latn/standard'",
")",
";",
"const",
"currencyFormat",
"=",
"localeData",
".",
"main",
"(",
"'numbers/currencyFormats-numberSystem-latn/standard'",
")",
";",
"const",
"symbols",
"=",
"localeData",
".",
"main",
"(",
"'numbers/symbols-numberSystem-latn'",
")",
";",
"const",
"symbolValues",
"=",
"[",
"symbols",
".",
"decimal",
",",
"symbols",
".",
"group",
",",
"symbols",
".",
"list",
",",
"symbols",
".",
"percentSign",
",",
"symbols",
".",
"plusSign",
",",
"symbols",
".",
"minusSign",
",",
"symbols",
".",
"exponential",
",",
"symbols",
".",
"superscriptingExponent",
",",
"symbols",
".",
"perMille",
",",
"symbols",
".",
"infinity",
",",
"symbols",
".",
"nan",
",",
"symbols",
".",
"timeSeparator",
",",
"]",
";",
"if",
"(",
"symbols",
".",
"currencyDecimal",
"||",
"symbols",
".",
"currencyGroup",
")",
"{",
"symbolValues",
".",
"push",
"(",
"symbols",
".",
"currencyDecimal",
")",
";",
"}",
"if",
"(",
"symbols",
".",
"currencyGroup",
")",
"{",
"symbolValues",
".",
"push",
"(",
"symbols",
".",
"currencyGroup",
")",
";",
"}",
"return",
"[",
"symbolValues",
",",
"[",
"decimalFormat",
",",
"percentFormat",
",",
"currencyFormat",
",",
"scientificFormat",
"]",
"]",
";",
"}"
] | Returns the number symbols and formats for a locale
@returns [ symbols, formats ]
symbols: [ decimal, group, list, percentSign, plusSign, minusSign, exponential, superscriptingExponent, perMille, infinity, nan, timeSeparator, currencyDecimal?, currencyGroup? ]
formats: [ currency, decimal, percent, scientific ] | [
"Returns",
"the",
"number",
"symbols",
"and",
"formats",
"for",
"a",
"locale"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L426-L459 |
22 | angular/angular | tools/gulp-tasks/cldr/extract.js | getCurrencySettings | function getCurrencySettings(locale, localeData) {
const currencyInfo = localeData.main(`numbers/currencies`);
let currentCurrency = '';
// find the currency currently used in this country
const currencies =
localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) ||
localeData.get(`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`);
if (currencies) {
currencies.some(currency => {
const keys = Object.keys(currency);
return keys.some(key => {
if (currency[key]._from && !currency[key]._to) {
return currentCurrency = key;
}
});
});
if (!currentCurrency) {
throw new Error(`Unable to find currency for locale "${locale}"`);
}
}
let currencySettings = [undefined, undefined];
if (currentCurrency) {
currencySettings = [currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName];
}
return currencySettings;
} | javascript | function getCurrencySettings(locale, localeData) {
const currencyInfo = localeData.main(`numbers/currencies`);
let currentCurrency = '';
// find the currency currently used in this country
const currencies =
localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) ||
localeData.get(`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`);
if (currencies) {
currencies.some(currency => {
const keys = Object.keys(currency);
return keys.some(key => {
if (currency[key]._from && !currency[key]._to) {
return currentCurrency = key;
}
});
});
if (!currentCurrency) {
throw new Error(`Unable to find currency for locale "${locale}"`);
}
}
let currencySettings = [undefined, undefined];
if (currentCurrency) {
currencySettings = [currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName];
}
return currencySettings;
} | [
"function",
"getCurrencySettings",
"(",
"locale",
",",
"localeData",
")",
"{",
"const",
"currencyInfo",
"=",
"localeData",
".",
"main",
"(",
"`",
"`",
")",
";",
"let",
"currentCurrency",
"=",
"''",
";",
"// find the currency currently used in this country",
"const",
"currencies",
"=",
"localeData",
".",
"get",
"(",
"`",
"${",
"localeData",
".",
"attributes",
".",
"territory",
"}",
"`",
")",
"||",
"localeData",
".",
"get",
"(",
"`",
"${",
"localeData",
".",
"attributes",
".",
"language",
".",
"toUpperCase",
"(",
")",
"}",
"`",
")",
";",
"if",
"(",
"currencies",
")",
"{",
"currencies",
".",
"some",
"(",
"currency",
"=>",
"{",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"currency",
")",
";",
"return",
"keys",
".",
"some",
"(",
"key",
"=>",
"{",
"if",
"(",
"currency",
"[",
"key",
"]",
".",
"_from",
"&&",
"!",
"currency",
"[",
"key",
"]",
".",
"_to",
")",
"{",
"return",
"currentCurrency",
"=",
"key",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"currentCurrency",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"locale",
"}",
"`",
")",
";",
"}",
"}",
"let",
"currencySettings",
"=",
"[",
"undefined",
",",
"undefined",
"]",
";",
"if",
"(",
"currentCurrency",
")",
"{",
"currencySettings",
"=",
"[",
"currencyInfo",
"[",
"currentCurrency",
"]",
".",
"symbol",
",",
"currencyInfo",
"[",
"currentCurrency",
"]",
".",
"displayName",
"]",
";",
"}",
"return",
"currencySettings",
";",
"}"
] | Returns the currency symbol and name for a locale
@returns [ symbol, name ] | [
"Returns",
"the",
"currency",
"symbol",
"and",
"name",
"for",
"a",
"locale"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/extract.js#L465-L496 |
23 | angular/angular | tools/npm/check-node-modules.js | _deleteDir | function _deleteDir(path) {
if (fs.existsSync(path)) {
var subpaths = fs.readdirSync(path);
subpaths.forEach(function(subpath) {
var curPath = path + '/' + subpath;
if (fs.lstatSync(curPath).isDirectory()) {
_deleteDir(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
} | javascript | function _deleteDir(path) {
if (fs.existsSync(path)) {
var subpaths = fs.readdirSync(path);
subpaths.forEach(function(subpath) {
var curPath = path + '/' + subpath;
if (fs.lstatSync(curPath).isDirectory()) {
_deleteDir(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
} | [
"function",
"_deleteDir",
"(",
"path",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
")",
")",
"{",
"var",
"subpaths",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
")",
";",
"subpaths",
".",
"forEach",
"(",
"function",
"(",
"subpath",
")",
"{",
"var",
"curPath",
"=",
"path",
"+",
"'/'",
"+",
"subpath",
";",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"curPath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"_deleteDir",
"(",
"curPath",
")",
";",
"}",
"else",
"{",
"fs",
".",
"unlinkSync",
"(",
"curPath",
")",
";",
"}",
"}",
")",
";",
"fs",
".",
"rmdirSync",
"(",
"path",
")",
";",
"}",
"}"
] | Custom implementation of recursive `rm` because we can't rely on the state of node_modules to
pull in existing module. | [
"Custom",
"implementation",
"of",
"recursive",
"rm",
"because",
"we",
"can",
"t",
"rely",
"on",
"the",
"state",
"of",
"node_modules",
"to",
"pull",
"in",
"existing",
"module",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/npm/check-node-modules.js#L41-L54 |
24 | angular/angular | tools/gulp-tasks/cldr/closure.js | generateAllLocalesFile | function generateAllLocalesFile(LOCALES, ALIASES) {
const existingLocalesAliases = {};
const existingLocalesData = {};
// for each locale, get the data and the list of equivalent locales
LOCALES.forEach(locale => {
const eqLocales = new Set();
eqLocales.add(locale);
if (locale.match(/-/)) {
eqLocales.add(locale.replace(/-/g, '_'));
}
// check for aliases
const alias = ALIASES[locale];
if (alias) {
eqLocales.add(alias);
if (alias.match(/-/)) {
eqLocales.add(alias.replace(/-/g, '_'));
}
// to avoid duplicated "case" we regroup all locales in the same "case"
// the simplest way to do that is to have alias aliases
// e.g. 'no' --> 'nb', 'nb' --> 'no-NO'
// which means that we'll have 'no', 'nb' and 'no-NO' in the same "case"
const aliasKeys = Object.keys(ALIASES);
for (let i = 0; i < aliasKeys.length; i++) {
const aliasValue = ALIASES[alias];
if (aliasKeys.indexOf(alias) !== -1 && !eqLocales.has(aliasValue)) {
eqLocales.add(aliasValue);
if (aliasValue.match(/-/)) {
eqLocales.add(aliasValue.replace(/-/g, '_'));
}
}
}
}
for (let l of eqLocales) {
// find the existing content file
const path = `${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`;
if (fs.existsSync(`${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`)) {
const localeName = formatLocale(locale);
existingLocalesData[locale] =
fs.readFileSync(path, 'utf8')
.replace(`${HEADER}\n`, '')
.replace('export default ', `export const locale_${localeName} = `)
.replace('function plural', `function plural_${localeName}`)
.replace(/,(\n | )plural/, `, plural_${localeName}`)
.replace('const u = undefined;\n\n', '');
}
}
existingLocalesAliases[locale] = eqLocales;
});
function generateCases(locale) {
let str = '';
let locales = [];
const eqLocales = existingLocalesAliases[locale];
for (let l of eqLocales) {
str += `case '${l}':\n`;
locales.push(`'${l}'`);
}
let localesStr = '[' + locales.join(',') + ']';
str += ` l = locale_${formatLocale(locale)};
locales = ${localesStr};
break;\n`;
return str;
}
function formatLocale(locale) { return locale.replace(/-/g, '_'); }
// clang-format off
return `${HEADER}
import {registerLocaleData} from '../src/i18n/locale_data';
const u = undefined;
${LOCALES.map(locale => `${existingLocalesData[locale]}`).join('\n')}
let l: any;
let locales: string[] = [];
switch (goog.LOCALE) {
${LOCALES.map(locale => generateCases(locale)).join('')}}
if(l) {
locales.forEach(locale => registerLocaleData(l, locale));
}
`;
// clang-format on
} | javascript | function generateAllLocalesFile(LOCALES, ALIASES) {
const existingLocalesAliases = {};
const existingLocalesData = {};
// for each locale, get the data and the list of equivalent locales
LOCALES.forEach(locale => {
const eqLocales = new Set();
eqLocales.add(locale);
if (locale.match(/-/)) {
eqLocales.add(locale.replace(/-/g, '_'));
}
// check for aliases
const alias = ALIASES[locale];
if (alias) {
eqLocales.add(alias);
if (alias.match(/-/)) {
eqLocales.add(alias.replace(/-/g, '_'));
}
// to avoid duplicated "case" we regroup all locales in the same "case"
// the simplest way to do that is to have alias aliases
// e.g. 'no' --> 'nb', 'nb' --> 'no-NO'
// which means that we'll have 'no', 'nb' and 'no-NO' in the same "case"
const aliasKeys = Object.keys(ALIASES);
for (let i = 0; i < aliasKeys.length; i++) {
const aliasValue = ALIASES[alias];
if (aliasKeys.indexOf(alias) !== -1 && !eqLocales.has(aliasValue)) {
eqLocales.add(aliasValue);
if (aliasValue.match(/-/)) {
eqLocales.add(aliasValue.replace(/-/g, '_'));
}
}
}
}
for (let l of eqLocales) {
// find the existing content file
const path = `${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`;
if (fs.existsSync(`${RELATIVE_I18N_DATA_FOLDER}/${l}.ts`)) {
const localeName = formatLocale(locale);
existingLocalesData[locale] =
fs.readFileSync(path, 'utf8')
.replace(`${HEADER}\n`, '')
.replace('export default ', `export const locale_${localeName} = `)
.replace('function plural', `function plural_${localeName}`)
.replace(/,(\n | )plural/, `, plural_${localeName}`)
.replace('const u = undefined;\n\n', '');
}
}
existingLocalesAliases[locale] = eqLocales;
});
function generateCases(locale) {
let str = '';
let locales = [];
const eqLocales = existingLocalesAliases[locale];
for (let l of eqLocales) {
str += `case '${l}':\n`;
locales.push(`'${l}'`);
}
let localesStr = '[' + locales.join(',') + ']';
str += ` l = locale_${formatLocale(locale)};
locales = ${localesStr};
break;\n`;
return str;
}
function formatLocale(locale) { return locale.replace(/-/g, '_'); }
// clang-format off
return `${HEADER}
import {registerLocaleData} from '../src/i18n/locale_data';
const u = undefined;
${LOCALES.map(locale => `${existingLocalesData[locale]}`).join('\n')}
let l: any;
let locales: string[] = [];
switch (goog.LOCALE) {
${LOCALES.map(locale => generateCases(locale)).join('')}}
if(l) {
locales.forEach(locale => registerLocaleData(l, locale));
}
`;
// clang-format on
} | [
"function",
"generateAllLocalesFile",
"(",
"LOCALES",
",",
"ALIASES",
")",
"{",
"const",
"existingLocalesAliases",
"=",
"{",
"}",
";",
"const",
"existingLocalesData",
"=",
"{",
"}",
";",
"// for each locale, get the data and the list of equivalent locales",
"LOCALES",
".",
"forEach",
"(",
"locale",
"=>",
"{",
"const",
"eqLocales",
"=",
"new",
"Set",
"(",
")",
";",
"eqLocales",
".",
"add",
"(",
"locale",
")",
";",
"if",
"(",
"locale",
".",
"match",
"(",
"/",
"-",
"/",
")",
")",
"{",
"eqLocales",
".",
"add",
"(",
"locale",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
")",
";",
"}",
"// check for aliases",
"const",
"alias",
"=",
"ALIASES",
"[",
"locale",
"]",
";",
"if",
"(",
"alias",
")",
"{",
"eqLocales",
".",
"add",
"(",
"alias",
")",
";",
"if",
"(",
"alias",
".",
"match",
"(",
"/",
"-",
"/",
")",
")",
"{",
"eqLocales",
".",
"add",
"(",
"alias",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
")",
";",
"}",
"// to avoid duplicated \"case\" we regroup all locales in the same \"case\"",
"// the simplest way to do that is to have alias aliases",
"// e.g. 'no' --> 'nb', 'nb' --> 'no-NO'",
"// which means that we'll have 'no', 'nb' and 'no-NO' in the same \"case\"",
"const",
"aliasKeys",
"=",
"Object",
".",
"keys",
"(",
"ALIASES",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"aliasKeys",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"aliasValue",
"=",
"ALIASES",
"[",
"alias",
"]",
";",
"if",
"(",
"aliasKeys",
".",
"indexOf",
"(",
"alias",
")",
"!==",
"-",
"1",
"&&",
"!",
"eqLocales",
".",
"has",
"(",
"aliasValue",
")",
")",
"{",
"eqLocales",
".",
"add",
"(",
"aliasValue",
")",
";",
"if",
"(",
"aliasValue",
".",
"match",
"(",
"/",
"-",
"/",
")",
")",
"{",
"eqLocales",
".",
"add",
"(",
"aliasValue",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
")",
";",
"}",
"}",
"}",
"}",
"for",
"(",
"let",
"l",
"of",
"eqLocales",
")",
"{",
"// find the existing content file",
"const",
"path",
"=",
"`",
"${",
"RELATIVE_I18N_DATA_FOLDER",
"}",
"${",
"l",
"}",
"`",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"`",
"${",
"RELATIVE_I18N_DATA_FOLDER",
"}",
"${",
"l",
"}",
"`",
")",
")",
"{",
"const",
"localeName",
"=",
"formatLocale",
"(",
"locale",
")",
";",
"existingLocalesData",
"[",
"locale",
"]",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
",",
"'utf8'",
")",
".",
"replace",
"(",
"`",
"${",
"HEADER",
"}",
"\\n",
"`",
",",
"''",
")",
".",
"replace",
"(",
"'export default '",
",",
"`",
"${",
"localeName",
"}",
"`",
")",
".",
"replace",
"(",
"'function plural'",
",",
"`",
"${",
"localeName",
"}",
"`",
")",
".",
"replace",
"(",
"/",
",(\\n | )plural",
"/",
",",
"`",
"${",
"localeName",
"}",
"`",
")",
".",
"replace",
"(",
"'const u = undefined;\\n\\n'",
",",
"''",
")",
";",
"}",
"}",
"existingLocalesAliases",
"[",
"locale",
"]",
"=",
"eqLocales",
";",
"}",
")",
";",
"function",
"generateCases",
"(",
"locale",
")",
"{",
"let",
"str",
"=",
"''",
";",
"let",
"locales",
"=",
"[",
"]",
";",
"const",
"eqLocales",
"=",
"existingLocalesAliases",
"[",
"locale",
"]",
";",
"for",
"(",
"let",
"l",
"of",
"eqLocales",
")",
"{",
"str",
"+=",
"`",
"${",
"l",
"}",
"\\n",
"`",
";",
"locales",
".",
"push",
"(",
"`",
"${",
"l",
"}",
"`",
")",
";",
"}",
"let",
"localesStr",
"=",
"'['",
"+",
"locales",
".",
"join",
"(",
"','",
")",
"+",
"']'",
";",
"str",
"+=",
"`",
"${",
"formatLocale",
"(",
"locale",
")",
"}",
"${",
"localesStr",
"}",
"\\n",
"`",
";",
"return",
"str",
";",
"}",
"function",
"formatLocale",
"(",
"locale",
")",
"{",
"return",
"locale",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
";",
"}",
"// clang-format off",
"return",
"`",
"${",
"HEADER",
"}",
"${",
"LOCALES",
".",
"map",
"(",
"locale",
"=>",
"`",
"${",
"existingLocalesData",
"[",
"locale",
"]",
"}",
"`",
")",
".",
"join",
"(",
"'\\n'",
")",
"}",
"${",
"LOCALES",
".",
"map",
"(",
"locale",
"=>",
"generateCases",
"(",
"locale",
")",
")",
".",
"join",
"(",
"''",
")",
"}",
"`",
";",
"// clang-format on",
"}"
] | Generate a file that contains all locale to import for closure.
Tree shaking will only keep the data for the `goog.LOCALE` locale. | [
"Generate",
"a",
"file",
"that",
"contains",
"all",
"locale",
"to",
"import",
"for",
"closure",
".",
"Tree",
"shaking",
"will",
"only",
"keep",
"the",
"data",
"for",
"the",
"goog",
".",
"LOCALE",
"locale",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/cldr/closure.js#L71-L163 |
25 | angular/angular | aio/tools/transforms/remark-package/services/renderMarkdown.js | inlineTagDefs | function inlineTagDefs() {
const Parser = this.Parser;
const inlineTokenizers = Parser.prototype.inlineTokenizers;
const inlineMethods = Parser.prototype.inlineMethods;
const blockTokenizers = Parser.prototype.blockTokenizers;
const blockMethods = Parser.prototype.blockMethods;
blockTokenizers.inlineTag = tokenizeInlineTag;
blockMethods.splice(blockMethods.indexOf('paragraph'), 0, 'inlineTag');
inlineTokenizers.inlineTag = tokenizeInlineTag;
inlineMethods.splice(blockMethods.indexOf('text'), 0, 'inlineTag');
tokenizeInlineTag.notInLink = true;
tokenizeInlineTag.locator = inlineTagLocator;
function tokenizeInlineTag(eat, value, silent) {
const match = /^\{@[^\s\}]+[^\}]*\}/.exec(value);
if (match) {
if (silent) {
return true;
}
return eat(match[0])({
'type': 'inlineTag',
'value': match[0]
});
}
}
function inlineTagLocator(value, fromIndex) {
return value.indexOf('{@', fromIndex);
}
} | javascript | function inlineTagDefs() {
const Parser = this.Parser;
const inlineTokenizers = Parser.prototype.inlineTokenizers;
const inlineMethods = Parser.prototype.inlineMethods;
const blockTokenizers = Parser.prototype.blockTokenizers;
const blockMethods = Parser.prototype.blockMethods;
blockTokenizers.inlineTag = tokenizeInlineTag;
blockMethods.splice(blockMethods.indexOf('paragraph'), 0, 'inlineTag');
inlineTokenizers.inlineTag = tokenizeInlineTag;
inlineMethods.splice(blockMethods.indexOf('text'), 0, 'inlineTag');
tokenizeInlineTag.notInLink = true;
tokenizeInlineTag.locator = inlineTagLocator;
function tokenizeInlineTag(eat, value, silent) {
const match = /^\{@[^\s\}]+[^\}]*\}/.exec(value);
if (match) {
if (silent) {
return true;
}
return eat(match[0])({
'type': 'inlineTag',
'value': match[0]
});
}
}
function inlineTagLocator(value, fromIndex) {
return value.indexOf('{@', fromIndex);
}
} | [
"function",
"inlineTagDefs",
"(",
")",
"{",
"const",
"Parser",
"=",
"this",
".",
"Parser",
";",
"const",
"inlineTokenizers",
"=",
"Parser",
".",
"prototype",
".",
"inlineTokenizers",
";",
"const",
"inlineMethods",
"=",
"Parser",
".",
"prototype",
".",
"inlineMethods",
";",
"const",
"blockTokenizers",
"=",
"Parser",
".",
"prototype",
".",
"blockTokenizers",
";",
"const",
"blockMethods",
"=",
"Parser",
".",
"prototype",
".",
"blockMethods",
";",
"blockTokenizers",
".",
"inlineTag",
"=",
"tokenizeInlineTag",
";",
"blockMethods",
".",
"splice",
"(",
"blockMethods",
".",
"indexOf",
"(",
"'paragraph'",
")",
",",
"0",
",",
"'inlineTag'",
")",
";",
"inlineTokenizers",
".",
"inlineTag",
"=",
"tokenizeInlineTag",
";",
"inlineMethods",
".",
"splice",
"(",
"blockMethods",
".",
"indexOf",
"(",
"'text'",
")",
",",
"0",
",",
"'inlineTag'",
")",
";",
"tokenizeInlineTag",
".",
"notInLink",
"=",
"true",
";",
"tokenizeInlineTag",
".",
"locator",
"=",
"inlineTagLocator",
";",
"function",
"tokenizeInlineTag",
"(",
"eat",
",",
"value",
",",
"silent",
")",
"{",
"const",
"match",
"=",
"/",
"^\\{@[^\\s\\}]+[^\\}]*\\}",
"/",
".",
"exec",
"(",
"value",
")",
";",
"if",
"(",
"match",
")",
"{",
"if",
"(",
"silent",
")",
"{",
"return",
"true",
";",
"}",
"return",
"eat",
"(",
"match",
"[",
"0",
"]",
")",
"(",
"{",
"'type'",
":",
"'inlineTag'",
",",
"'value'",
":",
"match",
"[",
"0",
"]",
"}",
")",
";",
"}",
"}",
"function",
"inlineTagLocator",
"(",
"value",
",",
"fromIndex",
")",
"{",
"return",
"value",
".",
"indexOf",
"(",
"'{@'",
",",
"fromIndex",
")",
";",
"}",
"}"
] | Teach remark about inline tags, so that it neither wraps block level
tags in paragraphs nor processes the text within the tag. | [
"Teach",
"remark",
"about",
"inline",
"tags",
"so",
"that",
"it",
"neither",
"wraps",
"block",
"level",
"tags",
"in",
"paragraphs",
"nor",
"processes",
"the",
"text",
"within",
"the",
"tag",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/remark-package/services/renderMarkdown.js#L43-L75 |
26 | angular/angular | aio/tools/transforms/remark-package/services/renderMarkdown.js | plainHTMLBlocks | function plainHTMLBlocks() {
const plainBlocks = ['code-example', 'code-tabs'];
// Create matchers for each block
const anyBlockMatcher = new RegExp('^' + createOpenMatcher(`(${plainBlocks.join('|')})`));
const Parser = this.Parser;
const blockTokenizers = Parser.prototype.blockTokenizers;
const blockMethods = Parser.prototype.blockMethods;
blockTokenizers.plainHTMLBlocks = tokenizePlainHTMLBlocks;
blockMethods.splice(blockMethods.indexOf('html'), 0, 'plainHTMLBlocks');
function tokenizePlainHTMLBlocks(eat, value, silent) {
const openMatch = anyBlockMatcher.exec(value);
if (openMatch) {
const blockName = openMatch[1];
try {
const fullMatch = matchRecursiveRegExp(value, createOpenMatcher(blockName), createCloseMatcher(blockName))[0];
if (silent || !fullMatch) {
// either we are not eating (silent) or the match failed
return !!fullMatch;
}
return eat(fullMatch[0])({
type: 'html',
value: fullMatch[0]
});
} catch(e) {
this.file.fail('Unmatched plain HTML block tag ' + e.message);
}
}
}
} | javascript | function plainHTMLBlocks() {
const plainBlocks = ['code-example', 'code-tabs'];
// Create matchers for each block
const anyBlockMatcher = new RegExp('^' + createOpenMatcher(`(${plainBlocks.join('|')})`));
const Parser = this.Parser;
const blockTokenizers = Parser.prototype.blockTokenizers;
const blockMethods = Parser.prototype.blockMethods;
blockTokenizers.plainHTMLBlocks = tokenizePlainHTMLBlocks;
blockMethods.splice(blockMethods.indexOf('html'), 0, 'plainHTMLBlocks');
function tokenizePlainHTMLBlocks(eat, value, silent) {
const openMatch = anyBlockMatcher.exec(value);
if (openMatch) {
const blockName = openMatch[1];
try {
const fullMatch = matchRecursiveRegExp(value, createOpenMatcher(blockName), createCloseMatcher(blockName))[0];
if (silent || !fullMatch) {
// either we are not eating (silent) or the match failed
return !!fullMatch;
}
return eat(fullMatch[0])({
type: 'html',
value: fullMatch[0]
});
} catch(e) {
this.file.fail('Unmatched plain HTML block tag ' + e.message);
}
}
}
} | [
"function",
"plainHTMLBlocks",
"(",
")",
"{",
"const",
"plainBlocks",
"=",
"[",
"'code-example'",
",",
"'code-tabs'",
"]",
";",
"// Create matchers for each block",
"const",
"anyBlockMatcher",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"createOpenMatcher",
"(",
"`",
"${",
"plainBlocks",
".",
"join",
"(",
"'|'",
")",
"}",
"`",
")",
")",
";",
"const",
"Parser",
"=",
"this",
".",
"Parser",
";",
"const",
"blockTokenizers",
"=",
"Parser",
".",
"prototype",
".",
"blockTokenizers",
";",
"const",
"blockMethods",
"=",
"Parser",
".",
"prototype",
".",
"blockMethods",
";",
"blockTokenizers",
".",
"plainHTMLBlocks",
"=",
"tokenizePlainHTMLBlocks",
";",
"blockMethods",
".",
"splice",
"(",
"blockMethods",
".",
"indexOf",
"(",
"'html'",
")",
",",
"0",
",",
"'plainHTMLBlocks'",
")",
";",
"function",
"tokenizePlainHTMLBlocks",
"(",
"eat",
",",
"value",
",",
"silent",
")",
"{",
"const",
"openMatch",
"=",
"anyBlockMatcher",
".",
"exec",
"(",
"value",
")",
";",
"if",
"(",
"openMatch",
")",
"{",
"const",
"blockName",
"=",
"openMatch",
"[",
"1",
"]",
";",
"try",
"{",
"const",
"fullMatch",
"=",
"matchRecursiveRegExp",
"(",
"value",
",",
"createOpenMatcher",
"(",
"blockName",
")",
",",
"createCloseMatcher",
"(",
"blockName",
")",
")",
"[",
"0",
"]",
";",
"if",
"(",
"silent",
"||",
"!",
"fullMatch",
")",
"{",
"// either we are not eating (silent) or the match failed",
"return",
"!",
"!",
"fullMatch",
";",
"}",
"return",
"eat",
"(",
"fullMatch",
"[",
"0",
"]",
")",
"(",
"{",
"type",
":",
"'html'",
",",
"value",
":",
"fullMatch",
"[",
"0",
"]",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"file",
".",
"fail",
"(",
"'Unmatched plain HTML block tag '",
"+",
"e",
".",
"message",
")",
";",
"}",
"}",
"}",
"}"
] | Teach remark that some HTML blocks never include markdown | [
"Teach",
"remark",
"that",
"some",
"HTML",
"blocks",
"never",
"include",
"markdown"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/transforms/remark-package/services/renderMarkdown.js#L80-L113 |
27 | angular/angular | packages/bazel/src/protractor/protractor.conf.js | setConf | function setConf(conf, name, value, msg) {
if (conf[name] && conf[name] !== value) {
console.warn(
`Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`);
}
conf[name] = value;
} | javascript | function setConf(conf, name, value, msg) {
if (conf[name] && conf[name] !== value) {
console.warn(
`Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`);
}
conf[name] = value;
} | [
"function",
"setConf",
"(",
"conf",
",",
"name",
",",
"value",
",",
"msg",
")",
"{",
"if",
"(",
"conf",
"[",
"name",
"]",
"&&",
"conf",
"[",
"name",
"]",
"!==",
"value",
")",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"name",
"}",
"${",
"msg",
"}",
"`",
")",
";",
"}",
"conf",
"[",
"name",
"]",
"=",
"value",
";",
"}"
] | Helper function to warn when a user specified value is being overwritten | [
"Helper",
"function",
"to",
"warn",
"when",
"a",
"user",
"specified",
"value",
"is",
"being",
"overwritten"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/packages/bazel/src/protractor/protractor.conf.js#L24-L30 |
28 | angular/angular | aio/tools/examples/run-example-e2e.js | runProtractorAoT | function runProtractorAoT(appDir, outputFile) {
fs.appendFileSync(outputFile, '++ AoT version ++\n');
const aotBuildSpawnInfo = spawnExt('yarn', ['build:aot'], {cwd: appDir});
let promise = aotBuildSpawnInfo.promise;
const copyFileCmd = 'copy-dist-files.js';
if (fs.existsSync(appDir + '/' + copyFileCmd)) {
promise = promise.then(() => spawnExt('node', [copyFileCmd], {cwd: appDir}).promise);
}
const aotRunSpawnInfo = spawnExt('yarn', ['serve:aot'], {cwd: appDir}, true);
return runProtractorSystemJS(promise, appDir, aotRunSpawnInfo, outputFile);
} | javascript | function runProtractorAoT(appDir, outputFile) {
fs.appendFileSync(outputFile, '++ AoT version ++\n');
const aotBuildSpawnInfo = spawnExt('yarn', ['build:aot'], {cwd: appDir});
let promise = aotBuildSpawnInfo.promise;
const copyFileCmd = 'copy-dist-files.js';
if (fs.existsSync(appDir + '/' + copyFileCmd)) {
promise = promise.then(() => spawnExt('node', [copyFileCmd], {cwd: appDir}).promise);
}
const aotRunSpawnInfo = spawnExt('yarn', ['serve:aot'], {cwd: appDir}, true);
return runProtractorSystemJS(promise, appDir, aotRunSpawnInfo, outputFile);
} | [
"function",
"runProtractorAoT",
"(",
"appDir",
",",
"outputFile",
")",
"{",
"fs",
".",
"appendFileSync",
"(",
"outputFile",
",",
"'++ AoT version ++\\n'",
")",
";",
"const",
"aotBuildSpawnInfo",
"=",
"spawnExt",
"(",
"'yarn'",
",",
"[",
"'build:aot'",
"]",
",",
"{",
"cwd",
":",
"appDir",
"}",
")",
";",
"let",
"promise",
"=",
"aotBuildSpawnInfo",
".",
"promise",
";",
"const",
"copyFileCmd",
"=",
"'copy-dist-files.js'",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"appDir",
"+",
"'/'",
"+",
"copyFileCmd",
")",
")",
"{",
"promise",
"=",
"promise",
".",
"then",
"(",
"(",
")",
"=>",
"spawnExt",
"(",
"'node'",
",",
"[",
"copyFileCmd",
"]",
",",
"{",
"cwd",
":",
"appDir",
"}",
")",
".",
"promise",
")",
";",
"}",
"const",
"aotRunSpawnInfo",
"=",
"spawnExt",
"(",
"'yarn'",
",",
"[",
"'serve:aot'",
"]",
",",
"{",
"cwd",
":",
"appDir",
"}",
",",
"true",
")",
";",
"return",
"runProtractorSystemJS",
"(",
"promise",
",",
"appDir",
",",
"aotRunSpawnInfo",
",",
"outputFile",
")",
";",
"}"
] | Run e2e tests over the AOT build for projects that examples it. | [
"Run",
"e2e",
"tests",
"over",
"the",
"AOT",
"build",
"for",
"projects",
"that",
"examples",
"it",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/run-example-e2e.js#L223-L234 |
29 | angular/angular | aio/tools/examples/run-example-e2e.js | loadExampleConfig | function loadExampleConfig(exampleFolder) {
// Default config.
let config = {build: 'build', run: 'serve:e2e'};
try {
const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`);
Object.assign(config, exampleConfig);
} catch (e) {
}
return config;
} | javascript | function loadExampleConfig(exampleFolder) {
// Default config.
let config = {build: 'build', run: 'serve:e2e'};
try {
const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`);
Object.assign(config, exampleConfig);
} catch (e) {
}
return config;
} | [
"function",
"loadExampleConfig",
"(",
"exampleFolder",
")",
"{",
"// Default config.",
"let",
"config",
"=",
"{",
"build",
":",
"'build'",
",",
"run",
":",
"'serve:e2e'",
"}",
";",
"try",
"{",
"const",
"exampleConfig",
"=",
"fs",
".",
"readJsonSync",
"(",
"`",
"${",
"exampleFolder",
"}",
"${",
"EXAMPLE_CONFIG_FILENAME",
"}",
"`",
")",
";",
"Object",
".",
"assign",
"(",
"config",
",",
"exampleConfig",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"config",
";",
"}"
] | Load configuration for an example. Used for SystemJS | [
"Load",
"configuration",
"for",
"an",
"example",
".",
"Used",
"for",
"SystemJS"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/run-example-e2e.js#L373-L384 |
30 | angular/angular | aio/tools/examples/shared/protractor.config.js | formatOutput | function formatOutput(output) {
var indent = ' ';
var pad = ' ';
var results = [];
results.push('AppDir:' + output.appDir);
output.suites.forEach(function(suite) {
results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status);
pad+=indent;
suite.specs.forEach(function(spec) {
results.push(pad + spec.status + ' - ' + spec.description);
if (spec.failedExpectations) {
pad+=indent;
spec.failedExpectations.forEach(function (fe) {
results.push(pad + 'message: ' + fe.message);
});
pad=pad.substr(2);
}
});
pad = pad.substr(2);
results.push('');
});
results.push('');
return results.join('\n');
} | javascript | function formatOutput(output) {
var indent = ' ';
var pad = ' ';
var results = [];
results.push('AppDir:' + output.appDir);
output.suites.forEach(function(suite) {
results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status);
pad+=indent;
suite.specs.forEach(function(spec) {
results.push(pad + spec.status + ' - ' + spec.description);
if (spec.failedExpectations) {
pad+=indent;
spec.failedExpectations.forEach(function (fe) {
results.push(pad + 'message: ' + fe.message);
});
pad=pad.substr(2);
}
});
pad = pad.substr(2);
results.push('');
});
results.push('');
return results.join('\n');
} | [
"function",
"formatOutput",
"(",
"output",
")",
"{",
"var",
"indent",
"=",
"' '",
";",
"var",
"pad",
"=",
"' '",
";",
"var",
"results",
"=",
"[",
"]",
";",
"results",
".",
"push",
"(",
"'AppDir:'",
"+",
"output",
".",
"appDir",
")",
";",
"output",
".",
"suites",
".",
"forEach",
"(",
"function",
"(",
"suite",
")",
"{",
"results",
".",
"push",
"(",
"pad",
"+",
"'Suite: '",
"+",
"suite",
".",
"description",
"+",
"' -- '",
"+",
"suite",
".",
"status",
")",
";",
"pad",
"+=",
"indent",
";",
"suite",
".",
"specs",
".",
"forEach",
"(",
"function",
"(",
"spec",
")",
"{",
"results",
".",
"push",
"(",
"pad",
"+",
"spec",
".",
"status",
"+",
"' - '",
"+",
"spec",
".",
"description",
")",
";",
"if",
"(",
"spec",
".",
"failedExpectations",
")",
"{",
"pad",
"+=",
"indent",
";",
"spec",
".",
"failedExpectations",
".",
"forEach",
"(",
"function",
"(",
"fe",
")",
"{",
"results",
".",
"push",
"(",
"pad",
"+",
"'message: '",
"+",
"fe",
".",
"message",
")",
";",
"}",
")",
";",
"pad",
"=",
"pad",
".",
"substr",
"(",
"2",
")",
";",
"}",
"}",
")",
";",
"pad",
"=",
"pad",
".",
"substr",
"(",
"2",
")",
";",
"results",
".",
"push",
"(",
"''",
")",
";",
"}",
")",
";",
"results",
".",
"push",
"(",
"''",
")",
";",
"return",
"results",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] | for output file output | [
"for",
"output",
"file",
"output"
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/aio/tools/examples/shared/protractor.config.js#L122-L145 |
31 | angular/angular | tools/gulp-tasks/format.js | gulpStatus | function gulpStatus() {
const Vinyl = require('vinyl');
const path = require('path');
const gulpGit = require('gulp-git');
const through = require('through2');
const srcStream = through.obj();
const opt = {cwd: process.cwd()};
// https://git-scm.com/docs/git-status#_short_format
const RE_STATUS = /((\s\w)|(\w+)|\?{0,2})\s([\w\+\-\/\\\.]+)(\s->\s)?([\w\+\-\/\\\.]+)*\n{0,1}/gm;
gulpGit.status({args: '--porcelain', quiet: true}, function(err, stdout) {
if (err) return srcStream.emit('error', err);
const data = stdout.toString();
let currentMatch;
while ((currentMatch = RE_STATUS.exec(data)) !== null) {
// status
const status = currentMatch[1].trim().toLowerCase();
// We only care about untracked files and renamed files
if (!new RegExp(/r|\?/i).test(status)) {
continue;
}
// file path
const currentFilePath = currentMatch[4];
// new file path in case its been moved
const newFilePath = currentMatch[6];
const filePath = newFilePath || currentFilePath;
srcStream.write(new Vinyl({
path: path.resolve(opt.cwd, filePath),
cwd: opt.cwd,
}));
RE_STATUS.lastIndex++;
}
srcStream.end();
});
return srcStream;
} | javascript | function gulpStatus() {
const Vinyl = require('vinyl');
const path = require('path');
const gulpGit = require('gulp-git');
const through = require('through2');
const srcStream = through.obj();
const opt = {cwd: process.cwd()};
// https://git-scm.com/docs/git-status#_short_format
const RE_STATUS = /((\s\w)|(\w+)|\?{0,2})\s([\w\+\-\/\\\.]+)(\s->\s)?([\w\+\-\/\\\.]+)*\n{0,1}/gm;
gulpGit.status({args: '--porcelain', quiet: true}, function(err, stdout) {
if (err) return srcStream.emit('error', err);
const data = stdout.toString();
let currentMatch;
while ((currentMatch = RE_STATUS.exec(data)) !== null) {
// status
const status = currentMatch[1].trim().toLowerCase();
// We only care about untracked files and renamed files
if (!new RegExp(/r|\?/i).test(status)) {
continue;
}
// file path
const currentFilePath = currentMatch[4];
// new file path in case its been moved
const newFilePath = currentMatch[6];
const filePath = newFilePath || currentFilePath;
srcStream.write(new Vinyl({
path: path.resolve(opt.cwd, filePath),
cwd: opt.cwd,
}));
RE_STATUS.lastIndex++;
}
srcStream.end();
});
return srcStream;
} | [
"function",
"gulpStatus",
"(",
")",
"{",
"const",
"Vinyl",
"=",
"require",
"(",
"'vinyl'",
")",
";",
"const",
"path",
"=",
"require",
"(",
"'path'",
")",
";",
"const",
"gulpGit",
"=",
"require",
"(",
"'gulp-git'",
")",
";",
"const",
"through",
"=",
"require",
"(",
"'through2'",
")",
";",
"const",
"srcStream",
"=",
"through",
".",
"obj",
"(",
")",
";",
"const",
"opt",
"=",
"{",
"cwd",
":",
"process",
".",
"cwd",
"(",
")",
"}",
";",
"// https://git-scm.com/docs/git-status#_short_format",
"const",
"RE_STATUS",
"=",
"/",
"((\\s\\w)|(\\w+)|\\?{0,2})\\s([\\w\\+\\-\\/\\\\\\.]+)(\\s->\\s)?([\\w\\+\\-\\/\\\\\\.]+)*\\n{0,1}",
"/",
"gm",
";",
"gulpGit",
".",
"status",
"(",
"{",
"args",
":",
"'--porcelain'",
",",
"quiet",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"stdout",
")",
"{",
"if",
"(",
"err",
")",
"return",
"srcStream",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"const",
"data",
"=",
"stdout",
".",
"toString",
"(",
")",
";",
"let",
"currentMatch",
";",
"while",
"(",
"(",
"currentMatch",
"=",
"RE_STATUS",
".",
"exec",
"(",
"data",
")",
")",
"!==",
"null",
")",
"{",
"// status",
"const",
"status",
"=",
"currentMatch",
"[",
"1",
"]",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"// We only care about untracked files and renamed files",
"if",
"(",
"!",
"new",
"RegExp",
"(",
"/",
"r|\\?",
"/",
"i",
")",
".",
"test",
"(",
"status",
")",
")",
"{",
"continue",
";",
"}",
"// file path",
"const",
"currentFilePath",
"=",
"currentMatch",
"[",
"4",
"]",
";",
"// new file path in case its been moved",
"const",
"newFilePath",
"=",
"currentMatch",
"[",
"6",
"]",
";",
"const",
"filePath",
"=",
"newFilePath",
"||",
"currentFilePath",
";",
"srcStream",
".",
"write",
"(",
"new",
"Vinyl",
"(",
"{",
"path",
":",
"path",
".",
"resolve",
"(",
"opt",
".",
"cwd",
",",
"filePath",
")",
",",
"cwd",
":",
"opt",
".",
"cwd",
",",
"}",
")",
")",
";",
"RE_STATUS",
".",
"lastIndex",
"++",
";",
"}",
"srcStream",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"return",
"srcStream",
";",
"}"
] | Gulp stream that wraps the gulp-git status,
only returns untracked files, and converts
the stdout into a stream of files. | [
"Gulp",
"stream",
"that",
"wraps",
"the",
"gulp",
"-",
"git",
"status",
"only",
"returns",
"untracked",
"files",
"and",
"converts",
"the",
"stdout",
"into",
"a",
"stream",
"of",
"files",
"."
] | c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c | https://github.com/angular/angular/blob/c016e2c4ecf7529f08fae4ca0f5c8b0170c6b51c/tools/gulp-tasks/format.js#L37-L83 |
32 | facebook/create-react-app | packages/react-scripts/config/modules.js | getAdditionalModulePaths | function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
// We need to explicitly check for null and undefined (and not a falsy value) because
// TypeScript treats an empty string as `.`.
if (baseUrl == null) {
// If there's no baseUrl set we respect NODE_PATH
// Note that NODE_PATH is deprecated and will be removed
// in the next major release of create-react-app.
const nodePath = process.env.NODE_PATH || '';
return nodePath.split(path.delimiter).filter(Boolean);
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
} | javascript | function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
// We need to explicitly check for null and undefined (and not a falsy value) because
// TypeScript treats an empty string as `.`.
if (baseUrl == null) {
// If there's no baseUrl set we respect NODE_PATH
// Note that NODE_PATH is deprecated and will be removed
// in the next major release of create-react-app.
const nodePath = process.env.NODE_PATH || '';
return nodePath.split(path.delimiter).filter(Boolean);
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
} | [
"function",
"getAdditionalModulePaths",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"baseUrl",
"=",
"options",
".",
"baseUrl",
";",
"// We need to explicitly check for null and undefined (and not a falsy value) because",
"// TypeScript treats an empty string as `.`.",
"if",
"(",
"baseUrl",
"==",
"null",
")",
"{",
"// If there's no baseUrl set we respect NODE_PATH",
"// Note that NODE_PATH is deprecated and will be removed",
"// in the next major release of create-react-app.",
"const",
"nodePath",
"=",
"process",
".",
"env",
".",
"NODE_PATH",
"||",
"''",
";",
"return",
"nodePath",
".",
"split",
"(",
"path",
".",
"delimiter",
")",
".",
"filter",
"(",
"Boolean",
")",
";",
"}",
"const",
"baseUrlResolved",
"=",
"path",
".",
"resolve",
"(",
"paths",
".",
"appPath",
",",
"baseUrl",
")",
";",
"// We don't need to do anything if `baseUrl` is set to `node_modules`. This is",
"// the default behavior.",
"if",
"(",
"path",
".",
"relative",
"(",
"paths",
".",
"appNodeModules",
",",
"baseUrlResolved",
")",
"===",
"''",
")",
"{",
"return",
"null",
";",
"}",
"// Allow the user set the `baseUrl` to `appSrc`.",
"if",
"(",
"path",
".",
"relative",
"(",
"paths",
".",
"appSrc",
",",
"baseUrlResolved",
")",
"===",
"''",
")",
"{",
"return",
"[",
"paths",
".",
"appSrc",
"]",
";",
"}",
"// Otherwise, throw an error.",
"throw",
"new",
"Error",
"(",
"chalk",
".",
"red",
".",
"bold",
"(",
"\"Your project's `baseUrl` can only be set to `src` or `node_modules`.\"",
"+",
"' Create React App does not support other values at this time.'",
")",
")",
";",
"}"
] | Get the baseUrl of a compilerOptions object.
@param {Object} options | [
"Get",
"the",
"baseUrl",
"of",
"a",
"compilerOptions",
"object",
"."
] | 57ef103440c24e41b0d7dc82b7ad7fc1dc817eca | https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-scripts/config/modules.js#L21-L55 |
33 | facebook/create-react-app | packages/react-dev-utils/webpackHotDevClient.js | handleSuccess | function handleSuccess() {
clearOutdatedErrors();
var isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess() {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay();
});
}
} | javascript | function handleSuccess() {
clearOutdatedErrors();
var isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess() {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay();
});
}
} | [
"function",
"handleSuccess",
"(",
")",
"{",
"clearOutdatedErrors",
"(",
")",
";",
"var",
"isHotUpdate",
"=",
"!",
"isFirstCompilation",
";",
"isFirstCompilation",
"=",
"false",
";",
"hasCompileErrors",
"=",
"false",
";",
"// Attempt to apply hot updates or reload.",
"if",
"(",
"isHotUpdate",
")",
"{",
"tryApplyUpdates",
"(",
"function",
"onHotUpdateSuccess",
"(",
")",
"{",
"// Only dismiss it when we're sure it's a hot update.",
"// Otherwise it would flicker right before the reload.",
"tryDismissErrorOverlay",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | Successful compilation. | [
"Successful",
"compilation",
"."
] | 57ef103440c24e41b0d7dc82b7ad7fc1dc817eca | https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/webpackHotDevClient.js#L97-L112 |
34 | facebook/create-react-app | packages/react-dev-utils/FileSizeReporter.js | printFileSizesAfterBuild | function printFileSizesAfterBuild(
webpackStats,
previousSizeMap,
buildFolder,
maxBundleGzipSize,
maxChunkGzipSize
) {
var root = previousSizeMap.root;
var sizes = previousSizeMap.sizes;
var assets = (webpackStats.stats || [webpackStats])
.map(stats =>
stats
.toJson({ all: false, assets: true })
.assets.filter(asset => canReadAsset(asset.name))
.map(asset => {
var fileContents = fs.readFileSync(path.join(root, asset.name));
var size = gzipSize(fileContents);
var previousSize = sizes[removeFileNameHash(root, asset.name)];
var difference = getDifferenceLabel(size, previousSize);
return {
folder: path.join(
path.basename(buildFolder),
path.dirname(asset.name)
),
name: path.basename(asset.name),
size: size,
sizeLabel:
filesize(size) + (difference ? ' (' + difference + ')' : ''),
};
})
)
.reduce((single, all) => all.concat(single), []);
assets.sort((a, b) => b.size - a.size);
var longestSizeLabelLength = Math.max.apply(
null,
assets.map(a => stripAnsi(a.sizeLabel).length)
);
var suggestBundleSplitting = false;
assets.forEach(asset => {
var sizeLabel = asset.sizeLabel;
var sizeLength = stripAnsi(sizeLabel).length;
if (sizeLength < longestSizeLabelLength) {
var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
sizeLabel += rightPadding;
}
var isMainBundle = asset.name.indexOf('main.') === 0;
var maxRecommendedSize = isMainBundle
? maxBundleGzipSize
: maxChunkGzipSize;
var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
if (isLarge && path.extname(asset.name) === '.js') {
suggestBundleSplitting = true;
}
console.log(
' ' +
(isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
' ' +
chalk.dim(asset.folder + path.sep) +
chalk.cyan(asset.name)
);
});
if (suggestBundleSplitting) {
console.log();
console.log(
chalk.yellow('The bundle size is significantly larger than recommended.')
);
console.log(
chalk.yellow(
'Consider reducing it with code splitting: https://goo.gl/9VhYWB'
)
);
console.log(
chalk.yellow(
'You can also analyze the project dependencies: https://goo.gl/LeUzfb'
)
);
}
} | javascript | function printFileSizesAfterBuild(
webpackStats,
previousSizeMap,
buildFolder,
maxBundleGzipSize,
maxChunkGzipSize
) {
var root = previousSizeMap.root;
var sizes = previousSizeMap.sizes;
var assets = (webpackStats.stats || [webpackStats])
.map(stats =>
stats
.toJson({ all: false, assets: true })
.assets.filter(asset => canReadAsset(asset.name))
.map(asset => {
var fileContents = fs.readFileSync(path.join(root, asset.name));
var size = gzipSize(fileContents);
var previousSize = sizes[removeFileNameHash(root, asset.name)];
var difference = getDifferenceLabel(size, previousSize);
return {
folder: path.join(
path.basename(buildFolder),
path.dirname(asset.name)
),
name: path.basename(asset.name),
size: size,
sizeLabel:
filesize(size) + (difference ? ' (' + difference + ')' : ''),
};
})
)
.reduce((single, all) => all.concat(single), []);
assets.sort((a, b) => b.size - a.size);
var longestSizeLabelLength = Math.max.apply(
null,
assets.map(a => stripAnsi(a.sizeLabel).length)
);
var suggestBundleSplitting = false;
assets.forEach(asset => {
var sizeLabel = asset.sizeLabel;
var sizeLength = stripAnsi(sizeLabel).length;
if (sizeLength < longestSizeLabelLength) {
var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
sizeLabel += rightPadding;
}
var isMainBundle = asset.name.indexOf('main.') === 0;
var maxRecommendedSize = isMainBundle
? maxBundleGzipSize
: maxChunkGzipSize;
var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
if (isLarge && path.extname(asset.name) === '.js') {
suggestBundleSplitting = true;
}
console.log(
' ' +
(isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
' ' +
chalk.dim(asset.folder + path.sep) +
chalk.cyan(asset.name)
);
});
if (suggestBundleSplitting) {
console.log();
console.log(
chalk.yellow('The bundle size is significantly larger than recommended.')
);
console.log(
chalk.yellow(
'Consider reducing it with code splitting: https://goo.gl/9VhYWB'
)
);
console.log(
chalk.yellow(
'You can also analyze the project dependencies: https://goo.gl/LeUzfb'
)
);
}
} | [
"function",
"printFileSizesAfterBuild",
"(",
"webpackStats",
",",
"previousSizeMap",
",",
"buildFolder",
",",
"maxBundleGzipSize",
",",
"maxChunkGzipSize",
")",
"{",
"var",
"root",
"=",
"previousSizeMap",
".",
"root",
";",
"var",
"sizes",
"=",
"previousSizeMap",
".",
"sizes",
";",
"var",
"assets",
"=",
"(",
"webpackStats",
".",
"stats",
"||",
"[",
"webpackStats",
"]",
")",
".",
"map",
"(",
"stats",
"=>",
"stats",
".",
"toJson",
"(",
"{",
"all",
":",
"false",
",",
"assets",
":",
"true",
"}",
")",
".",
"assets",
".",
"filter",
"(",
"asset",
"=>",
"canReadAsset",
"(",
"asset",
".",
"name",
")",
")",
".",
"map",
"(",
"asset",
"=>",
"{",
"var",
"fileContents",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"root",
",",
"asset",
".",
"name",
")",
")",
";",
"var",
"size",
"=",
"gzipSize",
"(",
"fileContents",
")",
";",
"var",
"previousSize",
"=",
"sizes",
"[",
"removeFileNameHash",
"(",
"root",
",",
"asset",
".",
"name",
")",
"]",
";",
"var",
"difference",
"=",
"getDifferenceLabel",
"(",
"size",
",",
"previousSize",
")",
";",
"return",
"{",
"folder",
":",
"path",
".",
"join",
"(",
"path",
".",
"basename",
"(",
"buildFolder",
")",
",",
"path",
".",
"dirname",
"(",
"asset",
".",
"name",
")",
")",
",",
"name",
":",
"path",
".",
"basename",
"(",
"asset",
".",
"name",
")",
",",
"size",
":",
"size",
",",
"sizeLabel",
":",
"filesize",
"(",
"size",
")",
"+",
"(",
"difference",
"?",
"' ('",
"+",
"difference",
"+",
"')'",
":",
"''",
")",
",",
"}",
";",
"}",
")",
")",
".",
"reduce",
"(",
"(",
"single",
",",
"all",
")",
"=>",
"all",
".",
"concat",
"(",
"single",
")",
",",
"[",
"]",
")",
";",
"assets",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"b",
".",
"size",
"-",
"a",
".",
"size",
")",
";",
"var",
"longestSizeLabelLength",
"=",
"Math",
".",
"max",
".",
"apply",
"(",
"null",
",",
"assets",
".",
"map",
"(",
"a",
"=>",
"stripAnsi",
"(",
"a",
".",
"sizeLabel",
")",
".",
"length",
")",
")",
";",
"var",
"suggestBundleSplitting",
"=",
"false",
";",
"assets",
".",
"forEach",
"(",
"asset",
"=>",
"{",
"var",
"sizeLabel",
"=",
"asset",
".",
"sizeLabel",
";",
"var",
"sizeLength",
"=",
"stripAnsi",
"(",
"sizeLabel",
")",
".",
"length",
";",
"if",
"(",
"sizeLength",
"<",
"longestSizeLabelLength",
")",
"{",
"var",
"rightPadding",
"=",
"' '",
".",
"repeat",
"(",
"longestSizeLabelLength",
"-",
"sizeLength",
")",
";",
"sizeLabel",
"+=",
"rightPadding",
";",
"}",
"var",
"isMainBundle",
"=",
"asset",
".",
"name",
".",
"indexOf",
"(",
"'main.'",
")",
"===",
"0",
";",
"var",
"maxRecommendedSize",
"=",
"isMainBundle",
"?",
"maxBundleGzipSize",
":",
"maxChunkGzipSize",
";",
"var",
"isLarge",
"=",
"maxRecommendedSize",
"&&",
"asset",
".",
"size",
">",
"maxRecommendedSize",
";",
"if",
"(",
"isLarge",
"&&",
"path",
".",
"extname",
"(",
"asset",
".",
"name",
")",
"===",
"'.js'",
")",
"{",
"suggestBundleSplitting",
"=",
"true",
";",
"}",
"console",
".",
"log",
"(",
"' '",
"+",
"(",
"isLarge",
"?",
"chalk",
".",
"yellow",
"(",
"sizeLabel",
")",
":",
"sizeLabel",
")",
"+",
"' '",
"+",
"chalk",
".",
"dim",
"(",
"asset",
".",
"folder",
"+",
"path",
".",
"sep",
")",
"+",
"chalk",
".",
"cyan",
"(",
"asset",
".",
"name",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"suggestBundleSplitting",
")",
"{",
"console",
".",
"log",
"(",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'The bundle size is significantly larger than recommended.'",
")",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'Consider reducing it with code splitting: https://goo.gl/9VhYWB'",
")",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'You can also analyze the project dependencies: https://goo.gl/LeUzfb'",
")",
")",
";",
"}",
"}"
] | Prints a detailed summary of build files. | [
"Prints",
"a",
"detailed",
"summary",
"of",
"build",
"files",
"."
] | 57ef103440c24e41b0d7dc82b7ad7fc1dc817eca | https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/FileSizeReporter.js#L27-L104 |
35 | facebook/create-react-app | packages/react-dev-utils/openBrowser.js | openBrowser | function openBrowser(url) {
const { action, value } = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url);
default:
throw new Error('Not implemented.');
}
} | javascript | function openBrowser(url) {
const { action, value } = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url);
default:
throw new Error('Not implemented.');
}
} | [
"function",
"openBrowser",
"(",
"url",
")",
"{",
"const",
"{",
"action",
",",
"value",
"}",
"=",
"getBrowserEnv",
"(",
")",
";",
"switch",
"(",
"action",
")",
"{",
"case",
"Actions",
".",
"NONE",
":",
"// Special case: BROWSER=\"none\" will prevent opening completely.",
"return",
"false",
";",
"case",
"Actions",
".",
"SCRIPT",
":",
"return",
"executeNodeScript",
"(",
"value",
",",
"url",
")",
";",
"case",
"Actions",
".",
"BROWSER",
":",
"return",
"startBrowserProcess",
"(",
"value",
",",
"url",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Not implemented.'",
")",
";",
"}",
"}"
] | Reads the BROWSER environment variable and decides what to do with it. Returns
true if it opened a browser or ran a node.js script, otherwise false. | [
"Reads",
"the",
"BROWSER",
"environment",
"variable",
"and",
"decides",
"what",
"to",
"do",
"with",
"it",
".",
"Returns",
"true",
"if",
"it",
"opened",
"a",
"browser",
"or",
"ran",
"a",
"node",
".",
"js",
"script",
"otherwise",
"false",
"."
] | 57ef103440c24e41b0d7dc82b7ad7fc1dc817eca | https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/openBrowser.js#L111-L124 |
36 | facebook/create-react-app | packages/react-dev-utils/WebpackDevServerUtils.js | onProxyError | function onProxyError(proxy) {
return (err, req, res) => {
const host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') +
' Could not proxy request ' +
chalk.cyan(req.url) +
' from ' +
chalk.cyan(host) +
' to ' +
chalk.cyan(proxy) +
'.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) +
').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end(
'Proxy error: Could not proxy request ' +
req.url +
' from ' +
host +
' to ' +
proxy +
' (' +
err.code +
').'
);
};
} | javascript | function onProxyError(proxy) {
return (err, req, res) => {
const host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') +
' Could not proxy request ' +
chalk.cyan(req.url) +
' from ' +
chalk.cyan(host) +
' to ' +
chalk.cyan(proxy) +
'.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) +
').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end(
'Proxy error: Could not proxy request ' +
req.url +
' from ' +
host +
' to ' +
proxy +
' (' +
err.code +
').'
);
};
} | [
"function",
"onProxyError",
"(",
"proxy",
")",
"{",
"return",
"(",
"err",
",",
"req",
",",
"res",
")",
"=>",
"{",
"const",
"host",
"=",
"req",
".",
"headers",
"&&",
"req",
".",
"headers",
".",
"host",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Proxy error:'",
")",
"+",
"' Could not proxy request '",
"+",
"chalk",
".",
"cyan",
"(",
"req",
".",
"url",
")",
"+",
"' from '",
"+",
"chalk",
".",
"cyan",
"(",
"host",
")",
"+",
"' to '",
"+",
"chalk",
".",
"cyan",
"(",
"proxy",
")",
"+",
"'.'",
")",
";",
"console",
".",
"log",
"(",
"'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information ('",
"+",
"chalk",
".",
"cyan",
"(",
"err",
".",
"code",
")",
"+",
"').'",
")",
";",
"console",
".",
"log",
"(",
")",
";",
"// And immediately send the proper error response to the client.",
"// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.",
"if",
"(",
"res",
".",
"writeHead",
"&&",
"!",
"res",
".",
"headersSent",
")",
"{",
"res",
".",
"writeHead",
"(",
"500",
")",
";",
"}",
"res",
".",
"end",
"(",
"'Proxy error: Could not proxy request '",
"+",
"req",
".",
"url",
"+",
"' from '",
"+",
"host",
"+",
"' to '",
"+",
"proxy",
"+",
"' ('",
"+",
"err",
".",
"code",
"+",
"').'",
")",
";",
"}",
";",
"}"
] | We need to provide a custom onError function for httpProxyMiddleware. It allows us to log custom error messages on the console. | [
"We",
"need",
"to",
"provide",
"a",
"custom",
"onError",
"function",
"for",
"httpProxyMiddleware",
".",
"It",
"allows",
"us",
"to",
"log",
"custom",
"error",
"messages",
"on",
"the",
"console",
"."
] | 57ef103440c24e41b0d7dc82b7ad7fc1dc817eca | https://github.com/facebook/create-react-app/blob/57ef103440c24e41b0d7dc82b7ad7fc1dc817eca/packages/react-dev-utils/WebpackDevServerUtils.js#L307-L344 |
37 | ant-design/ant-design | .antd-tools.config.js | finalizeCompile | function finalizeCompile() {
if (fs.existsSync(path.join(__dirname, './lib'))) {
// Build package.json version to lib/version/index.js
// prevent json-loader needing in user-side
const versionFilePath = path.join(process.cwd(), 'lib', 'version', 'index.js');
const versionFileContent = fs.readFileSync(versionFilePath).toString();
fs.writeFileSync(
versionFilePath,
versionFileContent.replace(
/require\(('|")\.\.\/\.\.\/package\.json('|")\)/,
`{ version: '${packageInfo.version}' }`,
),
);
// eslint-disable-next-line
console.log('Wrote version into lib/version/index.js');
// Build package.json version to lib/version/index.d.ts
// prevent https://github.com/ant-design/ant-design/issues/4935
const versionDefPath = path.join(process.cwd(), 'lib', 'version', 'index.d.ts');
fs.writeFileSync(
versionDefPath,
`declare var _default: "${packageInfo.version}";\nexport default _default;\n`,
);
// eslint-disable-next-line
console.log('Wrote version into lib/version/index.d.ts');
// Build a entry less file to dist/antd.less
const componentsPath = path.join(process.cwd(), 'components');
let componentsLessContent = '';
// Build components in one file: lib/style/components.less
fs.readdir(componentsPath, (err, files) => {
files.forEach(file => {
if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) {
componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`;
}
});
fs.writeFileSync(
path.join(process.cwd(), 'lib', 'style', 'components.less'),
componentsLessContent,
);
});
}
} | javascript | function finalizeCompile() {
if (fs.existsSync(path.join(__dirname, './lib'))) {
// Build package.json version to lib/version/index.js
// prevent json-loader needing in user-side
const versionFilePath = path.join(process.cwd(), 'lib', 'version', 'index.js');
const versionFileContent = fs.readFileSync(versionFilePath).toString();
fs.writeFileSync(
versionFilePath,
versionFileContent.replace(
/require\(('|")\.\.\/\.\.\/package\.json('|")\)/,
`{ version: '${packageInfo.version}' }`,
),
);
// eslint-disable-next-line
console.log('Wrote version into lib/version/index.js');
// Build package.json version to lib/version/index.d.ts
// prevent https://github.com/ant-design/ant-design/issues/4935
const versionDefPath = path.join(process.cwd(), 'lib', 'version', 'index.d.ts');
fs.writeFileSync(
versionDefPath,
`declare var _default: "${packageInfo.version}";\nexport default _default;\n`,
);
// eslint-disable-next-line
console.log('Wrote version into lib/version/index.d.ts');
// Build a entry less file to dist/antd.less
const componentsPath = path.join(process.cwd(), 'components');
let componentsLessContent = '';
// Build components in one file: lib/style/components.less
fs.readdir(componentsPath, (err, files) => {
files.forEach(file => {
if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) {
componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`;
}
});
fs.writeFileSync(
path.join(process.cwd(), 'lib', 'style', 'components.less'),
componentsLessContent,
);
});
}
} | [
"function",
"finalizeCompile",
"(",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'./lib'",
")",
")",
")",
"{",
"// Build package.json version to lib/version/index.js",
"// prevent json-loader needing in user-side",
"const",
"versionFilePath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'lib'",
",",
"'version'",
",",
"'index.js'",
")",
";",
"const",
"versionFileContent",
"=",
"fs",
".",
"readFileSync",
"(",
"versionFilePath",
")",
".",
"toString",
"(",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"versionFilePath",
",",
"versionFileContent",
".",
"replace",
"(",
"/",
"require\\(('|\")\\.\\.\\/\\.\\.\\/package\\.json('|\")\\)",
"/",
",",
"`",
"${",
"packageInfo",
".",
"version",
"}",
"`",
",",
")",
",",
")",
";",
"// eslint-disable-next-line",
"console",
".",
"log",
"(",
"'Wrote version into lib/version/index.js'",
")",
";",
"// Build package.json version to lib/version/index.d.ts",
"// prevent https://github.com/ant-design/ant-design/issues/4935",
"const",
"versionDefPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'lib'",
",",
"'version'",
",",
"'index.d.ts'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"versionDefPath",
",",
"`",
"${",
"packageInfo",
".",
"version",
"}",
"\\n",
"\\n",
"`",
",",
")",
";",
"// eslint-disable-next-line",
"console",
".",
"log",
"(",
"'Wrote version into lib/version/index.d.ts'",
")",
";",
"// Build a entry less file to dist/antd.less",
"const",
"componentsPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'components'",
")",
";",
"let",
"componentsLessContent",
"=",
"''",
";",
"// Build components in one file: lib/style/components.less",
"fs",
".",
"readdir",
"(",
"componentsPath",
",",
"(",
"err",
",",
"files",
")",
"=>",
"{",
"files",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"componentsPath",
",",
"file",
",",
"'style'",
",",
"'index.less'",
")",
")",
")",
"{",
"componentsLessContent",
"+=",
"`",
"${",
"path",
".",
"join",
"(",
"file",
",",
"'style'",
",",
"'index.less'",
")",
"}",
"\\n",
"`",
";",
"}",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'lib'",
",",
"'style'",
",",
"'components.less'",
")",
",",
"componentsLessContent",
",",
")",
";",
"}",
")",
";",
"}",
"}"
] | We need compile additional content for antd user | [
"We",
"need",
"compile",
"additional",
"content",
"for",
"antd",
"user"
] | 6d845f60efe9bd50a25c0ce29eb1fee895b9c7b7 | https://github.com/ant-design/ant-design/blob/6d845f60efe9bd50a25c0ce29eb1fee895b9c7b7/.antd-tools.config.js#L6-L48 |
38 | 30-seconds/30-seconds-of-code | scripts/module.js | build | async function build() {
console.time('Packager');
let requires = [];
let esmExportString = '';
let cjsExportString = '';
try {
if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
fs.writeFileSync(ROLLUP_INPUT_FILE, '');
fs.writeFileSync(TEST_MODULE_FILE, '');
// All the snippets that are Node.js-based and will break in a browser
// environment
const nodeSnippets = fs
.readFileSync('tag_database', 'utf8')
.split('\n')
.filter(v => v.search(/:.*node/g) !== -1)
.map(v => v.slice(0, v.indexOf(':')));
const snippets = fs.readdirSync(SNIPPETS_PATH);
const archivedSnippets = fs
.readdirSync(SNIPPETS_ARCHIVE_PATH)
.filter(v => v !== 'README.md');
snippets.forEach(snippet => {
const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
const snippetName = snippet.replace('.md', '');
let code = getCode(rawSnippetString);
if (nodeSnippets.includes(snippetName)) {
requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
}
esmExportString += `export ${code}`;
cjsExportString += code;
});
archivedSnippets.forEach(snippet => {
const rawSnippetString = getRawSnippetString(
SNIPPETS_ARCHIVE_PATH,
snippet
);
cjsExportString += getCode(rawSnippetString);
});
requires = [
...new Set(
requires
.filter(Boolean)
.map(v =>
v[0].replace(
'require(',
'typeof require !== "undefined" && require('
)
)
)
].join('\n');
fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);
const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
.map(v => v.replace('.md', ''))
.join(',')}}`;
fs.writeFileSync(
TEST_MODULE_FILE,
`${requires}\n\n${cjsExportString}\n\n${testExports}`
);
// Check Travis builds - Will skip builds on Travis if not CRON/API
if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
fs.unlink(ROLLUP_INPUT_FILE);
console.log(
`${chalk.green(
'NOBUILD'
)} Module build terminated, not a cron job or a custom build!`
);
console.timeEnd('Packager');
process.exit(0);
}
await doRollup();
// Clean up the temporary input file Rollup used for building the module
fs.unlink(ROLLUP_INPUT_FILE);
console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
console.timeEnd('Packager');
} catch (err) {
console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
process.exit(1);
}
} | javascript | async function build() {
console.time('Packager');
let requires = [];
let esmExportString = '';
let cjsExportString = '';
try {
if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
fs.writeFileSync(ROLLUP_INPUT_FILE, '');
fs.writeFileSync(TEST_MODULE_FILE, '');
// All the snippets that are Node.js-based and will break in a browser
// environment
const nodeSnippets = fs
.readFileSync('tag_database', 'utf8')
.split('\n')
.filter(v => v.search(/:.*node/g) !== -1)
.map(v => v.slice(0, v.indexOf(':')));
const snippets = fs.readdirSync(SNIPPETS_PATH);
const archivedSnippets = fs
.readdirSync(SNIPPETS_ARCHIVE_PATH)
.filter(v => v !== 'README.md');
snippets.forEach(snippet => {
const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
const snippetName = snippet.replace('.md', '');
let code = getCode(rawSnippetString);
if (nodeSnippets.includes(snippetName)) {
requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
}
esmExportString += `export ${code}`;
cjsExportString += code;
});
archivedSnippets.forEach(snippet => {
const rawSnippetString = getRawSnippetString(
SNIPPETS_ARCHIVE_PATH,
snippet
);
cjsExportString += getCode(rawSnippetString);
});
requires = [
...new Set(
requires
.filter(Boolean)
.map(v =>
v[0].replace(
'require(',
'typeof require !== "undefined" && require('
)
)
)
].join('\n');
fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);
const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
.map(v => v.replace('.md', ''))
.join(',')}}`;
fs.writeFileSync(
TEST_MODULE_FILE,
`${requires}\n\n${cjsExportString}\n\n${testExports}`
);
// Check Travis builds - Will skip builds on Travis if not CRON/API
if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
fs.unlink(ROLLUP_INPUT_FILE);
console.log(
`${chalk.green(
'NOBUILD'
)} Module build terminated, not a cron job or a custom build!`
);
console.timeEnd('Packager');
process.exit(0);
}
await doRollup();
// Clean up the temporary input file Rollup used for building the module
fs.unlink(ROLLUP_INPUT_FILE);
console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
console.timeEnd('Packager');
} catch (err) {
console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
process.exit(1);
}
} | [
"async",
"function",
"build",
"(",
")",
"{",
"console",
".",
"time",
"(",
"'Packager'",
")",
";",
"let",
"requires",
"=",
"[",
"]",
";",
"let",
"esmExportString",
"=",
"''",
";",
"let",
"cjsExportString",
"=",
"''",
";",
"try",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"DIST_PATH",
")",
")",
"fs",
".",
"mkdirSync",
"(",
"DIST_PATH",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"ROLLUP_INPUT_FILE",
",",
"''",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"TEST_MODULE_FILE",
",",
"''",
")",
";",
"// All the snippets that are Node.js-based and will break in a browser",
"// environment",
"const",
"nodeSnippets",
"=",
"fs",
".",
"readFileSync",
"(",
"'tag_database'",
",",
"'utf8'",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"filter",
"(",
"v",
"=>",
"v",
".",
"search",
"(",
"/",
":.*node",
"/",
"g",
")",
"!==",
"-",
"1",
")",
".",
"map",
"(",
"v",
"=>",
"v",
".",
"slice",
"(",
"0",
",",
"v",
".",
"indexOf",
"(",
"':'",
")",
")",
")",
";",
"const",
"snippets",
"=",
"fs",
".",
"readdirSync",
"(",
"SNIPPETS_PATH",
")",
";",
"const",
"archivedSnippets",
"=",
"fs",
".",
"readdirSync",
"(",
"SNIPPETS_ARCHIVE_PATH",
")",
".",
"filter",
"(",
"v",
"=>",
"v",
"!==",
"'README.md'",
")",
";",
"snippets",
".",
"forEach",
"(",
"snippet",
"=>",
"{",
"const",
"rawSnippetString",
"=",
"getRawSnippetString",
"(",
"SNIPPETS_PATH",
",",
"snippet",
")",
";",
"const",
"snippetName",
"=",
"snippet",
".",
"replace",
"(",
"'.md'",
",",
"''",
")",
";",
"let",
"code",
"=",
"getCode",
"(",
"rawSnippetString",
")",
";",
"if",
"(",
"nodeSnippets",
".",
"includes",
"(",
"snippetName",
")",
")",
"{",
"requires",
".",
"push",
"(",
"code",
".",
"match",
"(",
"/",
"const.*=.*require\\(([^\\)]*)\\);",
"/",
"g",
")",
")",
";",
"code",
"=",
"code",
".",
"replace",
"(",
"/",
"const.*=.*require\\(([^\\)]*)\\);",
"/",
"g",
",",
"''",
")",
";",
"}",
"esmExportString",
"+=",
"`",
"${",
"code",
"}",
"`",
";",
"cjsExportString",
"+=",
"code",
";",
"}",
")",
";",
"archivedSnippets",
".",
"forEach",
"(",
"snippet",
"=>",
"{",
"const",
"rawSnippetString",
"=",
"getRawSnippetString",
"(",
"SNIPPETS_ARCHIVE_PATH",
",",
"snippet",
")",
";",
"cjsExportString",
"+=",
"getCode",
"(",
"rawSnippetString",
")",
";",
"}",
")",
";",
"requires",
"=",
"[",
"...",
"new",
"Set",
"(",
"requires",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"v",
"=>",
"v",
"[",
"0",
"]",
".",
"replace",
"(",
"'require('",
",",
"'typeof require !== \"undefined\" && require('",
")",
")",
")",
"]",
".",
"join",
"(",
"'\\n'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"ROLLUP_INPUT_FILE",
",",
"`",
"${",
"requires",
"}",
"\\n",
"\\n",
"${",
"esmExportString",
"}",
"`",
")",
";",
"const",
"testExports",
"=",
"`",
"${",
"[",
"...",
"snippets",
",",
"...",
"archivedSnippets",
"]",
".",
"map",
"(",
"v",
"=>",
"v",
".",
"replace",
"(",
"'.md'",
",",
"''",
")",
")",
".",
"join",
"(",
"','",
")",
"}",
"`",
";",
"fs",
".",
"writeFileSync",
"(",
"TEST_MODULE_FILE",
",",
"`",
"${",
"requires",
"}",
"\\n",
"\\n",
"${",
"cjsExportString",
"}",
"\\n",
"\\n",
"${",
"testExports",
"}",
"`",
")",
";",
"// Check Travis builds - Will skip builds on Travis if not CRON/API",
"if",
"(",
"util",
".",
"isTravisCI",
"(",
")",
"&&",
"util",
".",
"isNotTravisCronOrAPI",
"(",
")",
")",
"{",
"fs",
".",
"unlink",
"(",
"ROLLUP_INPUT_FILE",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"green",
"(",
"'NOBUILD'",
")",
"}",
"`",
")",
";",
"console",
".",
"timeEnd",
"(",
"'Packager'",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"await",
"doRollup",
"(",
")",
";",
"// Clean up the temporary input file Rollup used for building the module",
"fs",
".",
"unlink",
"(",
"ROLLUP_INPUT_FILE",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"green",
"(",
"'SUCCESS!'",
")",
"}",
"`",
")",
";",
"console",
".",
"timeEnd",
"(",
"'Packager'",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"red",
"(",
"'ERROR!'",
")",
"}",
"${",
"err",
"}",
"`",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
] | Starts the build process. | [
"Starts",
"the",
"build",
"process",
"."
] | 5ef18713903aaaa5ff5409ef3a6de31dbd878d0c | https://github.com/30-seconds/30-seconds-of-code/blob/5ef18713903aaaa5ff5409ef3a6de31dbd878d0c/scripts/module.js#L74-L165 |
39 | electron/electron | lib/browser/guest-view-manager.js | function (embedder, params) {
if (webViewManager == null) {
webViewManager = process.electronBinding('web_view_manager')
}
const guest = webContents.create({
isGuest: true,
partition: params.partition,
embedder: embedder
})
const guestInstanceId = guest.id
guestInstances[guestInstanceId] = {
guest: guest,
embedder: embedder
}
// Clear the guest from map when it is destroyed.
//
// The guest WebContents is usually destroyed in 2 cases:
// 1. The embedder frame is closed (reloaded or destroyed), and it
// automatically closes the guest frame.
// 2. The guest frame is detached dynamically via JS, and it is manually
// destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST
// message.
// The second case relies on the libcc patch:
// https://github.com/electron/libchromiumcontent/pull/676
// The patch was introduced to work around a bug in Chromium:
// https://github.com/electron/electron/issues/14211
// We should revisit the bug to see if we can remove our libcc patch, the
// patch was introduced in Chrome 66.
guest.once('destroyed', () => {
if (guestInstanceId in guestInstances) {
detachGuest(embedder, guestInstanceId)
}
})
// Init guest web view after attached.
guest.once('did-attach', function (event) {
params = this.attachParams
delete this.attachParams
const previouslyAttached = this.viewInstanceId != null
this.viewInstanceId = params.instanceId
// Only load URL and set size on first attach
if (previouslyAttached) {
return
}
if (params.src) {
const opts = {}
if (params.httpreferrer) {
opts.httpReferrer = params.httpreferrer
}
if (params.useragent) {
opts.userAgent = params.useragent
}
this.loadURL(params.src, opts)
}
guest.allowPopups = params.allowpopups
embedder.emit('did-attach-webview', event, guest)
})
const sendToEmbedder = (channel, ...args) => {
if (!embedder.isDestroyed()) {
embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args)
}
}
// Dispatch events to embedder.
const fn = function (event) {
guest.on(event, function (_, ...args) {
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args)
})
}
for (const event of supportedWebViewEvents) {
fn(event)
}
// Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host', function (_, channel, args) {
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args)
})
// Notify guest of embedder window visibility when it is ready
// FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed
guest.on('dom-ready', function () {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance != null && guestInstance.visibilityState != null) {
guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState)
}
})
// Forward internal web contents event to embedder to handle
// native window.open setup
guest.on('-add-new-contents', (...args) => {
if (guest.getLastWebPreferences().nativeWindowOpen === true) {
const embedder = getEmbedder(guestInstanceId)
if (embedder != null) {
embedder.emit('-add-new-contents', ...args)
}
}
})
return guestInstanceId
} | javascript | function (embedder, params) {
if (webViewManager == null) {
webViewManager = process.electronBinding('web_view_manager')
}
const guest = webContents.create({
isGuest: true,
partition: params.partition,
embedder: embedder
})
const guestInstanceId = guest.id
guestInstances[guestInstanceId] = {
guest: guest,
embedder: embedder
}
// Clear the guest from map when it is destroyed.
//
// The guest WebContents is usually destroyed in 2 cases:
// 1. The embedder frame is closed (reloaded or destroyed), and it
// automatically closes the guest frame.
// 2. The guest frame is detached dynamically via JS, and it is manually
// destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST
// message.
// The second case relies on the libcc patch:
// https://github.com/electron/libchromiumcontent/pull/676
// The patch was introduced to work around a bug in Chromium:
// https://github.com/electron/electron/issues/14211
// We should revisit the bug to see if we can remove our libcc patch, the
// patch was introduced in Chrome 66.
guest.once('destroyed', () => {
if (guestInstanceId in guestInstances) {
detachGuest(embedder, guestInstanceId)
}
})
// Init guest web view after attached.
guest.once('did-attach', function (event) {
params = this.attachParams
delete this.attachParams
const previouslyAttached = this.viewInstanceId != null
this.viewInstanceId = params.instanceId
// Only load URL and set size on first attach
if (previouslyAttached) {
return
}
if (params.src) {
const opts = {}
if (params.httpreferrer) {
opts.httpReferrer = params.httpreferrer
}
if (params.useragent) {
opts.userAgent = params.useragent
}
this.loadURL(params.src, opts)
}
guest.allowPopups = params.allowpopups
embedder.emit('did-attach-webview', event, guest)
})
const sendToEmbedder = (channel, ...args) => {
if (!embedder.isDestroyed()) {
embedder._sendInternal(`${channel}-${guest.viewInstanceId}`, ...args)
}
}
// Dispatch events to embedder.
const fn = function (event) {
guest.on(event, function (_, ...args) {
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT', event, ...args)
})
}
for (const event of supportedWebViewEvents) {
fn(event)
}
// Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host', function (_, channel, args) {
sendToEmbedder('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE', channel, ...args)
})
// Notify guest of embedder window visibility when it is ready
// FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed
guest.on('dom-ready', function () {
const guestInstance = guestInstances[guestInstanceId]
if (guestInstance != null && guestInstance.visibilityState != null) {
guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', guestInstance.visibilityState)
}
})
// Forward internal web contents event to embedder to handle
// native window.open setup
guest.on('-add-new-contents', (...args) => {
if (guest.getLastWebPreferences().nativeWindowOpen === true) {
const embedder = getEmbedder(guestInstanceId)
if (embedder != null) {
embedder.emit('-add-new-contents', ...args)
}
}
})
return guestInstanceId
} | [
"function",
"(",
"embedder",
",",
"params",
")",
"{",
"if",
"(",
"webViewManager",
"==",
"null",
")",
"{",
"webViewManager",
"=",
"process",
".",
"electronBinding",
"(",
"'web_view_manager'",
")",
"}",
"const",
"guest",
"=",
"webContents",
".",
"create",
"(",
"{",
"isGuest",
":",
"true",
",",
"partition",
":",
"params",
".",
"partition",
",",
"embedder",
":",
"embedder",
"}",
")",
"const",
"guestInstanceId",
"=",
"guest",
".",
"id",
"guestInstances",
"[",
"guestInstanceId",
"]",
"=",
"{",
"guest",
":",
"guest",
",",
"embedder",
":",
"embedder",
"}",
"// Clear the guest from map when it is destroyed.",
"//",
"// The guest WebContents is usually destroyed in 2 cases:",
"// 1. The embedder frame is closed (reloaded or destroyed), and it",
"// automatically closes the guest frame.",
"// 2. The guest frame is detached dynamically via JS, and it is manually",
"// destroyed when the renderer sends the GUEST_VIEW_MANAGER_DESTROY_GUEST",
"// message.",
"// The second case relies on the libcc patch:",
"// https://github.com/electron/libchromiumcontent/pull/676",
"// The patch was introduced to work around a bug in Chromium:",
"// https://github.com/electron/electron/issues/14211",
"// We should revisit the bug to see if we can remove our libcc patch, the",
"// patch was introduced in Chrome 66.",
"guest",
".",
"once",
"(",
"'destroyed'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"guestInstanceId",
"in",
"guestInstances",
")",
"{",
"detachGuest",
"(",
"embedder",
",",
"guestInstanceId",
")",
"}",
"}",
")",
"// Init guest web view after attached.",
"guest",
".",
"once",
"(",
"'did-attach'",
",",
"function",
"(",
"event",
")",
"{",
"params",
"=",
"this",
".",
"attachParams",
"delete",
"this",
".",
"attachParams",
"const",
"previouslyAttached",
"=",
"this",
".",
"viewInstanceId",
"!=",
"null",
"this",
".",
"viewInstanceId",
"=",
"params",
".",
"instanceId",
"// Only load URL and set size on first attach",
"if",
"(",
"previouslyAttached",
")",
"{",
"return",
"}",
"if",
"(",
"params",
".",
"src",
")",
"{",
"const",
"opts",
"=",
"{",
"}",
"if",
"(",
"params",
".",
"httpreferrer",
")",
"{",
"opts",
".",
"httpReferrer",
"=",
"params",
".",
"httpreferrer",
"}",
"if",
"(",
"params",
".",
"useragent",
")",
"{",
"opts",
".",
"userAgent",
"=",
"params",
".",
"useragent",
"}",
"this",
".",
"loadURL",
"(",
"params",
".",
"src",
",",
"opts",
")",
"}",
"guest",
".",
"allowPopups",
"=",
"params",
".",
"allowpopups",
"embedder",
".",
"emit",
"(",
"'did-attach-webview'",
",",
"event",
",",
"guest",
")",
"}",
")",
"const",
"sendToEmbedder",
"=",
"(",
"channel",
",",
"...",
"args",
")",
"=>",
"{",
"if",
"(",
"!",
"embedder",
".",
"isDestroyed",
"(",
")",
")",
"{",
"embedder",
".",
"_sendInternal",
"(",
"`",
"${",
"channel",
"}",
"${",
"guest",
".",
"viewInstanceId",
"}",
"`",
",",
"...",
"args",
")",
"}",
"}",
"// Dispatch events to embedder.",
"const",
"fn",
"=",
"function",
"(",
"event",
")",
"{",
"guest",
".",
"on",
"(",
"event",
",",
"function",
"(",
"_",
",",
"...",
"args",
")",
"{",
"sendToEmbedder",
"(",
"'ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT'",
",",
"event",
",",
"...",
"args",
")",
"}",
")",
"}",
"for",
"(",
"const",
"event",
"of",
"supportedWebViewEvents",
")",
"{",
"fn",
"(",
"event",
")",
"}",
"// Dispatch guest's IPC messages to embedder.",
"guest",
".",
"on",
"(",
"'ipc-message-host'",
",",
"function",
"(",
"_",
",",
"channel",
",",
"args",
")",
"{",
"sendToEmbedder",
"(",
"'ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE'",
",",
"channel",
",",
"...",
"args",
")",
"}",
")",
"// Notify guest of embedder window visibility when it is ready",
"// FIXME Remove once https://github.com/electron/electron/issues/6828 is fixed",
"guest",
".",
"on",
"(",
"'dom-ready'",
",",
"function",
"(",
")",
"{",
"const",
"guestInstance",
"=",
"guestInstances",
"[",
"guestInstanceId",
"]",
"if",
"(",
"guestInstance",
"!=",
"null",
"&&",
"guestInstance",
".",
"visibilityState",
"!=",
"null",
")",
"{",
"guest",
".",
"_sendInternal",
"(",
"'ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE'",
",",
"guestInstance",
".",
"visibilityState",
")",
"}",
"}",
")",
"// Forward internal web contents event to embedder to handle",
"// native window.open setup",
"guest",
".",
"on",
"(",
"'-add-new-contents'",
",",
"(",
"...",
"args",
")",
"=>",
"{",
"if",
"(",
"guest",
".",
"getLastWebPreferences",
"(",
")",
".",
"nativeWindowOpen",
"===",
"true",
")",
"{",
"const",
"embedder",
"=",
"getEmbedder",
"(",
"guestInstanceId",
")",
"if",
"(",
"embedder",
"!=",
"null",
")",
"{",
"embedder",
".",
"emit",
"(",
"'-add-new-contents'",
",",
"...",
"args",
")",
"}",
"}",
"}",
")",
"return",
"guestInstanceId",
"}"
] | Create a new guest instance. | [
"Create",
"a",
"new",
"guest",
"instance",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L56-L161 |
|
40 | electron/electron | lib/browser/guest-view-manager.js | function (embedder, guestInstanceId) {
const guestInstance = guestInstances[guestInstanceId]
if (embedder !== guestInstance.embedder) {
return
}
webViewManager.removeGuest(embedder, guestInstanceId)
delete guestInstances[guestInstanceId]
const key = `${embedder.id}-${guestInstance.elementInstanceId}`
delete embedderElementsMap[key]
} | javascript | function (embedder, guestInstanceId) {
const guestInstance = guestInstances[guestInstanceId]
if (embedder !== guestInstance.embedder) {
return
}
webViewManager.removeGuest(embedder, guestInstanceId)
delete guestInstances[guestInstanceId]
const key = `${embedder.id}-${guestInstance.elementInstanceId}`
delete embedderElementsMap[key]
} | [
"function",
"(",
"embedder",
",",
"guestInstanceId",
")",
"{",
"const",
"guestInstance",
"=",
"guestInstances",
"[",
"guestInstanceId",
"]",
"if",
"(",
"embedder",
"!==",
"guestInstance",
".",
"embedder",
")",
"{",
"return",
"}",
"webViewManager",
".",
"removeGuest",
"(",
"embedder",
",",
"guestInstanceId",
")",
"delete",
"guestInstances",
"[",
"guestInstanceId",
"]",
"const",
"key",
"=",
"`",
"${",
"embedder",
".",
"id",
"}",
"${",
"guestInstance",
".",
"elementInstanceId",
"}",
"`",
"delete",
"embedderElementsMap",
"[",
"key",
"]",
"}"
] | Remove an guest-embedder relationship. | [
"Remove",
"an",
"guest",
"-",
"embedder",
"relationship",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L276-L287 |
|
41 | electron/electron | lib/browser/guest-view-manager.js | function (visibilityState) {
for (const guestInstanceId in guestInstances) {
const guestInstance = guestInstances[guestInstanceId]
guestInstance.visibilityState = visibilityState
if (guestInstance.embedder === embedder) {
guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState)
}
}
} | javascript | function (visibilityState) {
for (const guestInstanceId in guestInstances) {
const guestInstance = guestInstances[guestInstanceId]
guestInstance.visibilityState = visibilityState
if (guestInstance.embedder === embedder) {
guestInstance.guest._sendInternal('ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE', visibilityState)
}
}
} | [
"function",
"(",
"visibilityState",
")",
"{",
"for",
"(",
"const",
"guestInstanceId",
"in",
"guestInstances",
")",
"{",
"const",
"guestInstance",
"=",
"guestInstances",
"[",
"guestInstanceId",
"]",
"guestInstance",
".",
"visibilityState",
"=",
"visibilityState",
"if",
"(",
"guestInstance",
".",
"embedder",
"===",
"embedder",
")",
"{",
"guestInstance",
".",
"guest",
".",
"_sendInternal",
"(",
"'ELECTRON_GUEST_INSTANCE_VISIBILITY_CHANGE'",
",",
"visibilityState",
")",
"}",
"}",
"}"
] | Forward embedder window visiblity change events to guest | [
"Forward",
"embedder",
"window",
"visiblity",
"change",
"events",
"to",
"guest"
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L299-L307 |
|
42 | electron/electron | lib/browser/guest-view-manager.js | function (guestInstanceId, contents) {
const guest = getGuest(guestInstanceId)
if (!guest) {
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
}
return guest
} | javascript | function (guestInstanceId, contents) {
const guest = getGuest(guestInstanceId)
if (!guest) {
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
}
return guest
} | [
"function",
"(",
"guestInstanceId",
",",
"contents",
")",
"{",
"const",
"guest",
"=",
"getGuest",
"(",
"guestInstanceId",
")",
"if",
"(",
"!",
"guest",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"guestInstanceId",
"}",
"`",
")",
"}",
"if",
"(",
"guest",
".",
"hostWebContents",
"!==",
"contents",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"guestInstanceId",
"}",
"`",
")",
"}",
"return",
"guest",
"}"
] | Returns WebContents from its guest id hosted in given webContents. | [
"Returns",
"WebContents",
"from",
"its",
"guest",
"id",
"hosted",
"in",
"given",
"webContents",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/browser/guest-view-manager.js#L395-L404 |
|
43 | electron/electron | script/prepare-release.js | changesToRelease | async function changesToRelease () {
const lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g')
const lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir)
return !lastCommitWasRelease.test(lastCommit.stdout)
} | javascript | async function changesToRelease () {
const lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g')
const lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir)
return !lastCommitWasRelease.test(lastCommit.stdout)
} | [
"async",
"function",
"changesToRelease",
"(",
")",
"{",
"const",
"lastCommitWasRelease",
"=",
"new",
"RegExp",
"(",
"`",
"`",
",",
"'g'",
")",
"const",
"lastCommit",
"=",
"await",
"GitProcess",
".",
"exec",
"(",
"[",
"'log'",
",",
"'-n'",
",",
"'1'",
",",
"`",
"`",
"]",
",",
"gitDir",
")",
"return",
"!",
"lastCommitWasRelease",
".",
"test",
"(",
"lastCommit",
".",
"stdout",
")",
"}"
] | function to determine if there have been commits to master since the last release | [
"function",
"to",
"determine",
"if",
"there",
"have",
"been",
"commits",
"to",
"master",
"since",
"the",
"last",
"release"
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/prepare-release.js#L184-L188 |
44 | electron/electron | script/release-notes/notes.js | runRetryable | async function runRetryable (fn, maxRetries) {
let lastError
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error) {
await new Promise((resolve, reject) => setTimeout(resolve, CHECK_INTERVAL))
lastError = error
}
}
// Silently eat 404s.
if (lastError.status !== 404) throw lastError
} | javascript | async function runRetryable (fn, maxRetries) {
let lastError
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error) {
await new Promise((resolve, reject) => setTimeout(resolve, CHECK_INTERVAL))
lastError = error
}
}
// Silently eat 404s.
if (lastError.status !== 404) throw lastError
} | [
"async",
"function",
"runRetryable",
"(",
"fn",
",",
"maxRetries",
")",
"{",
"let",
"lastError",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"maxRetries",
";",
"i",
"++",
")",
"{",
"try",
"{",
"return",
"await",
"fn",
"(",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"await",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"setTimeout",
"(",
"resolve",
",",
"CHECK_INTERVAL",
")",
")",
"lastError",
"=",
"error",
"}",
"}",
"// Silently eat 404s.",
"if",
"(",
"lastError",
".",
"status",
"!==",
"404",
")",
"throw",
"lastError",
"}"
] | helper function to add some resiliency to volatile GH api endpoints | [
"helper",
"function",
"to",
"add",
"some",
"resiliency",
"to",
"volatile",
"GH",
"api",
"endpoints"
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/script/release-notes/notes.js#L305-L317 |
45 | electron/electron | lib/renderer/api/remote.js | wrapArgs | function wrapArgs (args, visited = new Set()) {
const valueToMeta = (value) => {
// Check for circular reference.
if (visited.has(value)) {
return {
type: 'value',
value: null
}
}
if (Array.isArray(value)) {
visited.add(value)
const meta = {
type: 'array',
value: wrapArgs(value, visited)
}
visited.delete(value)
return meta
} else if (bufferUtils.isBuffer(value)) {
return {
type: 'buffer',
value: bufferUtils.bufferToMeta(value)
}
} else if (value instanceof Date) {
return {
type: 'date',
value: value.getTime()
}
} else if ((value != null) && typeof value === 'object') {
if (isPromise(value)) {
return {
type: 'promise',
then: valueToMeta(function (onFulfilled, onRejected) {
value.then(onFulfilled, onRejected)
})
}
} else if (v8Util.getHiddenValue(value, 'atomId')) {
return {
type: 'remote-object',
id: v8Util.getHiddenValue(value, 'atomId')
}
}
const meta = {
type: 'object',
name: value.constructor ? value.constructor.name : '',
members: []
}
visited.add(value)
for (const prop in value) {
meta.members.push({
name: prop,
value: valueToMeta(value[prop])
})
}
visited.delete(value)
return meta
} else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) {
return {
type: 'function-with-return-value',
value: valueToMeta(value())
}
} else if (typeof value === 'function') {
return {
type: 'function',
id: callbacksRegistry.add(value),
location: v8Util.getHiddenValue(value, 'location'),
length: value.length
}
} else {
return {
type: 'value',
value: value
}
}
}
return args.map(valueToMeta)
} | javascript | function wrapArgs (args, visited = new Set()) {
const valueToMeta = (value) => {
// Check for circular reference.
if (visited.has(value)) {
return {
type: 'value',
value: null
}
}
if (Array.isArray(value)) {
visited.add(value)
const meta = {
type: 'array',
value: wrapArgs(value, visited)
}
visited.delete(value)
return meta
} else if (bufferUtils.isBuffer(value)) {
return {
type: 'buffer',
value: bufferUtils.bufferToMeta(value)
}
} else if (value instanceof Date) {
return {
type: 'date',
value: value.getTime()
}
} else if ((value != null) && typeof value === 'object') {
if (isPromise(value)) {
return {
type: 'promise',
then: valueToMeta(function (onFulfilled, onRejected) {
value.then(onFulfilled, onRejected)
})
}
} else if (v8Util.getHiddenValue(value, 'atomId')) {
return {
type: 'remote-object',
id: v8Util.getHiddenValue(value, 'atomId')
}
}
const meta = {
type: 'object',
name: value.constructor ? value.constructor.name : '',
members: []
}
visited.add(value)
for (const prop in value) {
meta.members.push({
name: prop,
value: valueToMeta(value[prop])
})
}
visited.delete(value)
return meta
} else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) {
return {
type: 'function-with-return-value',
value: valueToMeta(value())
}
} else if (typeof value === 'function') {
return {
type: 'function',
id: callbacksRegistry.add(value),
location: v8Util.getHiddenValue(value, 'location'),
length: value.length
}
} else {
return {
type: 'value',
value: value
}
}
}
return args.map(valueToMeta)
} | [
"function",
"wrapArgs",
"(",
"args",
",",
"visited",
"=",
"new",
"Set",
"(",
")",
")",
"{",
"const",
"valueToMeta",
"=",
"(",
"value",
")",
"=>",
"{",
"// Check for circular reference.",
"if",
"(",
"visited",
".",
"has",
"(",
"value",
")",
")",
"{",
"return",
"{",
"type",
":",
"'value'",
",",
"value",
":",
"null",
"}",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"visited",
".",
"add",
"(",
"value",
")",
"const",
"meta",
"=",
"{",
"type",
":",
"'array'",
",",
"value",
":",
"wrapArgs",
"(",
"value",
",",
"visited",
")",
"}",
"visited",
".",
"delete",
"(",
"value",
")",
"return",
"meta",
"}",
"else",
"if",
"(",
"bufferUtils",
".",
"isBuffer",
"(",
"value",
")",
")",
"{",
"return",
"{",
"type",
":",
"'buffer'",
",",
"value",
":",
"bufferUtils",
".",
"bufferToMeta",
"(",
"value",
")",
"}",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Date",
")",
"{",
"return",
"{",
"type",
":",
"'date'",
",",
"value",
":",
"value",
".",
"getTime",
"(",
")",
"}",
"}",
"else",
"if",
"(",
"(",
"value",
"!=",
"null",
")",
"&&",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"if",
"(",
"isPromise",
"(",
"value",
")",
")",
"{",
"return",
"{",
"type",
":",
"'promise'",
",",
"then",
":",
"valueToMeta",
"(",
"function",
"(",
"onFulfilled",
",",
"onRejected",
")",
"{",
"value",
".",
"then",
"(",
"onFulfilled",
",",
"onRejected",
")",
"}",
")",
"}",
"}",
"else",
"if",
"(",
"v8Util",
".",
"getHiddenValue",
"(",
"value",
",",
"'atomId'",
")",
")",
"{",
"return",
"{",
"type",
":",
"'remote-object'",
",",
"id",
":",
"v8Util",
".",
"getHiddenValue",
"(",
"value",
",",
"'atomId'",
")",
"}",
"}",
"const",
"meta",
"=",
"{",
"type",
":",
"'object'",
",",
"name",
":",
"value",
".",
"constructor",
"?",
"value",
".",
"constructor",
".",
"name",
":",
"''",
",",
"members",
":",
"[",
"]",
"}",
"visited",
".",
"add",
"(",
"value",
")",
"for",
"(",
"const",
"prop",
"in",
"value",
")",
"{",
"meta",
".",
"members",
".",
"push",
"(",
"{",
"name",
":",
"prop",
",",
"value",
":",
"valueToMeta",
"(",
"value",
"[",
"prop",
"]",
")",
"}",
")",
"}",
"visited",
".",
"delete",
"(",
"value",
")",
"return",
"meta",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
"&&",
"v8Util",
".",
"getHiddenValue",
"(",
"value",
",",
"'returnValue'",
")",
")",
"{",
"return",
"{",
"type",
":",
"'function-with-return-value'",
",",
"value",
":",
"valueToMeta",
"(",
"value",
"(",
")",
")",
"}",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"{",
"return",
"{",
"type",
":",
"'function'",
",",
"id",
":",
"callbacksRegistry",
".",
"add",
"(",
"value",
")",
",",
"location",
":",
"v8Util",
".",
"getHiddenValue",
"(",
"value",
",",
"'location'",
")",
",",
"length",
":",
"value",
".",
"length",
"}",
"}",
"else",
"{",
"return",
"{",
"type",
":",
"'value'",
",",
"value",
":",
"value",
"}",
"}",
"}",
"return",
"args",
".",
"map",
"(",
"valueToMeta",
")",
"}"
] | Convert the arguments object into an array of meta data. | [
"Convert",
"the",
"arguments",
"object",
"into",
"an",
"array",
"of",
"meta",
"data",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L28-L105 |
46 | electron/electron | lib/renderer/api/remote.js | setObjectMembers | function setObjectMembers (ref, object, metaId, members) {
if (!Array.isArray(members)) return
for (const member of members) {
if (object.hasOwnProperty(member.name)) continue
const descriptor = { enumerable: member.enumerable }
if (member.type === 'method') {
const remoteMemberFunction = function (...args) {
let command
if (this && this.constructor === remoteMemberFunction) {
command = 'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR'
} else {
command = 'ELECTRON_BROWSER_MEMBER_CALL'
}
const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args))
return metaToValue(ret)
}
let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name)
descriptor.get = () => {
descriptorFunction.ref = ref // The member should reference its object.
return descriptorFunction
}
// Enable monkey-patch the method
descriptor.set = (value) => {
descriptorFunction = value
return value
}
descriptor.configurable = true
} else if (member.type === 'get') {
descriptor.get = () => {
const command = 'ELECTRON_BROWSER_MEMBER_GET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name)
return metaToValue(meta)
}
if (member.writable) {
descriptor.set = (value) => {
const args = wrapArgs([value])
const command = 'ELECTRON_BROWSER_MEMBER_SET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args)
if (meta != null) metaToValue(meta)
return value
}
}
}
Object.defineProperty(object, member.name, descriptor)
}
} | javascript | function setObjectMembers (ref, object, metaId, members) {
if (!Array.isArray(members)) return
for (const member of members) {
if (object.hasOwnProperty(member.name)) continue
const descriptor = { enumerable: member.enumerable }
if (member.type === 'method') {
const remoteMemberFunction = function (...args) {
let command
if (this && this.constructor === remoteMemberFunction) {
command = 'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR'
} else {
command = 'ELECTRON_BROWSER_MEMBER_CALL'
}
const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args))
return metaToValue(ret)
}
let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name)
descriptor.get = () => {
descriptorFunction.ref = ref // The member should reference its object.
return descriptorFunction
}
// Enable monkey-patch the method
descriptor.set = (value) => {
descriptorFunction = value
return value
}
descriptor.configurable = true
} else if (member.type === 'get') {
descriptor.get = () => {
const command = 'ELECTRON_BROWSER_MEMBER_GET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name)
return metaToValue(meta)
}
if (member.writable) {
descriptor.set = (value) => {
const args = wrapArgs([value])
const command = 'ELECTRON_BROWSER_MEMBER_SET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args)
if (meta != null) metaToValue(meta)
return value
}
}
}
Object.defineProperty(object, member.name, descriptor)
}
} | [
"function",
"setObjectMembers",
"(",
"ref",
",",
"object",
",",
"metaId",
",",
"members",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"members",
")",
")",
"return",
"for",
"(",
"const",
"member",
"of",
"members",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"member",
".",
"name",
")",
")",
"continue",
"const",
"descriptor",
"=",
"{",
"enumerable",
":",
"member",
".",
"enumerable",
"}",
"if",
"(",
"member",
".",
"type",
"===",
"'method'",
")",
"{",
"const",
"remoteMemberFunction",
"=",
"function",
"(",
"...",
"args",
")",
"{",
"let",
"command",
"if",
"(",
"this",
"&&",
"this",
".",
"constructor",
"===",
"remoteMemberFunction",
")",
"{",
"command",
"=",
"'ELECTRON_BROWSER_MEMBER_CONSTRUCTOR'",
"}",
"else",
"{",
"command",
"=",
"'ELECTRON_BROWSER_MEMBER_CALL'",
"}",
"const",
"ret",
"=",
"ipcRendererInternal",
".",
"sendSync",
"(",
"command",
",",
"contextId",
",",
"metaId",
",",
"member",
".",
"name",
",",
"wrapArgs",
"(",
"args",
")",
")",
"return",
"metaToValue",
"(",
"ret",
")",
"}",
"let",
"descriptorFunction",
"=",
"proxyFunctionProperties",
"(",
"remoteMemberFunction",
",",
"metaId",
",",
"member",
".",
"name",
")",
"descriptor",
".",
"get",
"=",
"(",
")",
"=>",
"{",
"descriptorFunction",
".",
"ref",
"=",
"ref",
"// The member should reference its object.",
"return",
"descriptorFunction",
"}",
"// Enable monkey-patch the method",
"descriptor",
".",
"set",
"=",
"(",
"value",
")",
"=>",
"{",
"descriptorFunction",
"=",
"value",
"return",
"value",
"}",
"descriptor",
".",
"configurable",
"=",
"true",
"}",
"else",
"if",
"(",
"member",
".",
"type",
"===",
"'get'",
")",
"{",
"descriptor",
".",
"get",
"=",
"(",
")",
"=>",
"{",
"const",
"command",
"=",
"'ELECTRON_BROWSER_MEMBER_GET'",
"const",
"meta",
"=",
"ipcRendererInternal",
".",
"sendSync",
"(",
"command",
",",
"contextId",
",",
"metaId",
",",
"member",
".",
"name",
")",
"return",
"metaToValue",
"(",
"meta",
")",
"}",
"if",
"(",
"member",
".",
"writable",
")",
"{",
"descriptor",
".",
"set",
"=",
"(",
"value",
")",
"=>",
"{",
"const",
"args",
"=",
"wrapArgs",
"(",
"[",
"value",
"]",
")",
"const",
"command",
"=",
"'ELECTRON_BROWSER_MEMBER_SET'",
"const",
"meta",
"=",
"ipcRendererInternal",
".",
"sendSync",
"(",
"command",
",",
"contextId",
",",
"metaId",
",",
"member",
".",
"name",
",",
"args",
")",
"if",
"(",
"meta",
"!=",
"null",
")",
"metaToValue",
"(",
"meta",
")",
"return",
"value",
"}",
"}",
"}",
"Object",
".",
"defineProperty",
"(",
"object",
",",
"member",
".",
"name",
",",
"descriptor",
")",
"}",
"}"
] | Populate object's members from descriptors. The |ref| will be kept referenced by |members|. This matches |getObjectMemebers| in rpc-server. | [
"Populate",
"object",
"s",
"members",
"from",
"descriptors",
".",
"The",
"|ref|",
"will",
"be",
"kept",
"referenced",
"by",
"|members|",
".",
"This",
"matches",
"|getObjectMemebers|",
"in",
"rpc",
"-",
"server",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L110-L161 |
47 | electron/electron | lib/renderer/api/remote.js | setObjectPrototype | function setObjectPrototype (ref, object, metaId, descriptor) {
if (descriptor === null) return
const proto = {}
setObjectMembers(ref, proto, metaId, descriptor.members)
setObjectPrototype(ref, proto, metaId, descriptor.proto)
Object.setPrototypeOf(object, proto)
} | javascript | function setObjectPrototype (ref, object, metaId, descriptor) {
if (descriptor === null) return
const proto = {}
setObjectMembers(ref, proto, metaId, descriptor.members)
setObjectPrototype(ref, proto, metaId, descriptor.proto)
Object.setPrototypeOf(object, proto)
} | [
"function",
"setObjectPrototype",
"(",
"ref",
",",
"object",
",",
"metaId",
",",
"descriptor",
")",
"{",
"if",
"(",
"descriptor",
"===",
"null",
")",
"return",
"const",
"proto",
"=",
"{",
"}",
"setObjectMembers",
"(",
"ref",
",",
"proto",
",",
"metaId",
",",
"descriptor",
".",
"members",
")",
"setObjectPrototype",
"(",
"ref",
",",
"proto",
",",
"metaId",
",",
"descriptor",
".",
"proto",
")",
"Object",
".",
"setPrototypeOf",
"(",
"object",
",",
"proto",
")",
"}"
] | Populate object's prototype from descriptor. This matches |getObjectPrototype| in rpc-server. | [
"Populate",
"object",
"s",
"prototype",
"from",
"descriptor",
".",
"This",
"matches",
"|getObjectPrototype|",
"in",
"rpc",
"-",
"server",
"."
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L165-L171 |
48 | electron/electron | lib/renderer/api/remote.js | proxyFunctionProperties | function proxyFunctionProperties (remoteMemberFunction, metaId, name) {
let loaded = false
// Lazily load function properties
const loadRemoteProperties = () => {
if (loaded) return
loaded = true
const command = 'ELECTRON_BROWSER_MEMBER_GET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name)
setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members)
}
return new Proxy(remoteMemberFunction, {
set: (target, property, value, receiver) => {
if (property !== 'ref') loadRemoteProperties()
target[property] = value
return true
},
get: (target, property, receiver) => {
if (!target.hasOwnProperty(property)) loadRemoteProperties()
const value = target[property]
if (property === 'toString' && typeof value === 'function') {
return value.bind(target)
}
return value
},
ownKeys: (target) => {
loadRemoteProperties()
return Object.getOwnPropertyNames(target)
},
getOwnPropertyDescriptor: (target, property) => {
const descriptor = Object.getOwnPropertyDescriptor(target, property)
if (descriptor) return descriptor
loadRemoteProperties()
return Object.getOwnPropertyDescriptor(target, property)
}
})
} | javascript | function proxyFunctionProperties (remoteMemberFunction, metaId, name) {
let loaded = false
// Lazily load function properties
const loadRemoteProperties = () => {
if (loaded) return
loaded = true
const command = 'ELECTRON_BROWSER_MEMBER_GET'
const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name)
setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members)
}
return new Proxy(remoteMemberFunction, {
set: (target, property, value, receiver) => {
if (property !== 'ref') loadRemoteProperties()
target[property] = value
return true
},
get: (target, property, receiver) => {
if (!target.hasOwnProperty(property)) loadRemoteProperties()
const value = target[property]
if (property === 'toString' && typeof value === 'function') {
return value.bind(target)
}
return value
},
ownKeys: (target) => {
loadRemoteProperties()
return Object.getOwnPropertyNames(target)
},
getOwnPropertyDescriptor: (target, property) => {
const descriptor = Object.getOwnPropertyDescriptor(target, property)
if (descriptor) return descriptor
loadRemoteProperties()
return Object.getOwnPropertyDescriptor(target, property)
}
})
} | [
"function",
"proxyFunctionProperties",
"(",
"remoteMemberFunction",
",",
"metaId",
",",
"name",
")",
"{",
"let",
"loaded",
"=",
"false",
"// Lazily load function properties",
"const",
"loadRemoteProperties",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"loaded",
")",
"return",
"loaded",
"=",
"true",
"const",
"command",
"=",
"'ELECTRON_BROWSER_MEMBER_GET'",
"const",
"meta",
"=",
"ipcRendererInternal",
".",
"sendSync",
"(",
"command",
",",
"contextId",
",",
"metaId",
",",
"name",
")",
"setObjectMembers",
"(",
"remoteMemberFunction",
",",
"remoteMemberFunction",
",",
"meta",
".",
"id",
",",
"meta",
".",
"members",
")",
"}",
"return",
"new",
"Proxy",
"(",
"remoteMemberFunction",
",",
"{",
"set",
":",
"(",
"target",
",",
"property",
",",
"value",
",",
"receiver",
")",
"=>",
"{",
"if",
"(",
"property",
"!==",
"'ref'",
")",
"loadRemoteProperties",
"(",
")",
"target",
"[",
"property",
"]",
"=",
"value",
"return",
"true",
"}",
",",
"get",
":",
"(",
"target",
",",
"property",
",",
"receiver",
")",
"=>",
"{",
"if",
"(",
"!",
"target",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"loadRemoteProperties",
"(",
")",
"const",
"value",
"=",
"target",
"[",
"property",
"]",
"if",
"(",
"property",
"===",
"'toString'",
"&&",
"typeof",
"value",
"===",
"'function'",
")",
"{",
"return",
"value",
".",
"bind",
"(",
"target",
")",
"}",
"return",
"value",
"}",
",",
"ownKeys",
":",
"(",
"target",
")",
"=>",
"{",
"loadRemoteProperties",
"(",
")",
"return",
"Object",
".",
"getOwnPropertyNames",
"(",
"target",
")",
"}",
",",
"getOwnPropertyDescriptor",
":",
"(",
"target",
",",
"property",
")",
"=>",
"{",
"const",
"descriptor",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"target",
",",
"property",
")",
"if",
"(",
"descriptor",
")",
"return",
"descriptor",
"loadRemoteProperties",
"(",
")",
"return",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"target",
",",
"property",
")",
"}",
"}",
")",
"}"
] | Wrap function in Proxy for accessing remote properties | [
"Wrap",
"function",
"in",
"Proxy",
"for",
"accessing",
"remote",
"properties"
] | 6e29611788277729647acf465f10db1ea6f15788 | https://github.com/electron/electron/blob/6e29611788277729647acf465f10db1ea6f15788/lib/renderer/api/remote.js#L174-L211 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 142