code
stringlengths
31
2.05k
label_name
stringclasses
5 values
label
int64
0
4
public handleUpgrade( req: IncomingMessage, socket: Duplex, upgradeHead: Buffer ) { this.prepare(req); const res = new WebSocketResponse(req, socket); const callback = (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code: errorCode, message: Server.errorMessages[errorCode], context: errorContext, }); abortUpgrade(socket, errorCode, errorContext); return; } const head = Buffer.from(upgradeHead); upgradeHead = null; // some middlewares (like express-session) wait for the writeHead() call to flush their headers // see https://github.com/expressjs/session/blob/1010fadc2f071ddf2add94235d72224cf65159c6/index.js#L220-L244 res.writeHead(); // delegate to ws this.ws.handleUpgrade(req, socket, head, (websocket) => { this.onWebSocket(req, socket, websocket); }); }; this._applyMiddlewares(req, res as unknown as ServerResponse, (err) => { if (err) { callback(Server.errors.BAD_REQUEST, { name: "MIDDLEWARE_FAILURE" }); } else { this.verify(req, true, callback); } }); }
Base
1
const callback = (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code: errorCode, message: Server.errorMessages[errorCode], context: errorContext, }); abortUpgrade(socket, errorCode, errorContext); return; } const head = Buffer.from(upgradeHead); upgradeHead = null; // some middlewares (like express-session) wait for the writeHead() call to flush their headers // see https://github.com/expressjs/session/blob/1010fadc2f071ddf2add94235d72224cf65159c6/index.js#L220-L244 res.writeHead(); // delegate to ws this.ws.handleUpgrade(req, socket, head, (websocket) => { this.onWebSocket(req, socket, websocket); }); };
Base
1
const callback = async (errorCode, errorContext) => { if (errorCode) { this.emit("connection_error", { req, code: errorCode, message: Server.errorMessages[errorCode], context: errorContext, }); this.abortRequest(res, errorCode, errorContext); return; } const id = req._query.sid; let transport; if (id) { const client = this.clients[id]; if (!client) { debug("upgrade attempt for closed client"); res.close(); } else if (client.upgrading) { debug("transport has already been trying to upgrade"); res.close(); } else if (client.upgraded) { debug("transport had already been upgraded"); res.close(); } else { debug("upgrading existing transport"); transport = this.createTransport(req._query.transport, req); client.maybeUpgrade(transport); } } else { transport = await this.handshake( req._query.transport, req, (errorCode, errorContext) => this.abortRequest(res, errorCode, errorContext) ); if (!transport) { return; } } // calling writeStatus() triggers the flushing of any header added in a middleware req.res.writeStatus("101 Switching Protocols"); res.upgrade( { transport, }, req.getHeader("sec-websocket-key"), req.getHeader("sec-websocket-protocol"), req.getHeader("sec-websocket-extensions"), context ); };
Base
1
`export const devPagesDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.dir.pages) : 'null'}` ].join('\n\n') }
Base
1
return function viteServeStaticMiddleware(req, res, next) { // only serve the file if it's not an html request or ends with `/` // so that html requests can fallthrough to our html middleware for // special processing // also skip internal requests `/@fs/ /@vite-client` etc... const cleanedUrl = cleanUrl(req.url!) if ( cleanedUrl[cleanedUrl.length - 1] === '/' || path.extname(cleanedUrl) === '.html' || isInternalRequest(req.url!) ) { return next() } const url = new URL(req.url!, 'http://example.com') const pathname = decodeURIComponent(url.pathname) // apply aliases to static requests as well let redirectedPathname: string | undefined for (const { find, replacement } of server.config.resolve.alias) { const matches = typeof find === 'string' ? pathname.startsWith(find) : find.test(pathname) if (matches) { redirectedPathname = pathname.replace(find, replacement) break } } if (redirectedPathname) { // dir is pre-normalized to posix style if (redirectedPathname.startsWith(dir)) { redirectedPathname = redirectedPathname.slice(dir.length) } } const resolvedPathname = redirectedPathname || pathname let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname)) if ( resolvedPathname[resolvedPathname.length - 1] === '/' && fileUrl[fileUrl.length - 1] !== '/' ) { fileUrl = fileUrl + '/' } if (!ensureServingAccess(fileUrl, server, res, next)) { return } if (redirectedPathname) { url.pathname = encodeURIComponent(redirectedPathname) req.url = url.href.slice(url.origin.length) } serve(req, res, next) }
Class
2
return function viteServeRawFsMiddleware(req, res, next) { const url = new URL(req.url!, 'http://example.com') // In some cases (e.g. linked monorepos) files outside of root will // reference assets that are also out of served root. In such cases // the paths are rewritten to `/@fs/` prefixed paths and must be served by // searching based from fs root. if (url.pathname.startsWith(FS_PREFIX)) { const pathname = decodeURIComponent(url.pathname) // restrict files outside of `fs.allow` if ( !ensureServingAccess( slash(path.resolve(fsPathFromId(pathname))), server, res, next, ) ) { return } let newPathname = pathname.slice(FS_PREFIX.length) if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, '') url.pathname = encodeURIComponent(newPathname) req.url = url.href.slice(url.origin.length) serveFromRoot(req, res, next) } else { next() } }
Class
2
export function serveRawFsMiddleware( server: ViteDevServer, ): Connect.NextHandleFunction { const serveFromRoot = sirv( '/', sirvOptions({ headers: server.config.server.headers }), ) // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function viteServeRawFsMiddleware(req, res, next) { const url = new URL(req.url!, 'http://example.com') // In some cases (e.g. linked monorepos) files outside of root will // reference assets that are also out of served root. In such cases // the paths are rewritten to `/@fs/` prefixed paths and must be served by // searching based from fs root. if (url.pathname.startsWith(FS_PREFIX)) { const pathname = decodeURIComponent(url.pathname) // restrict files outside of `fs.allow` if ( !ensureServingAccess( slash(path.resolve(fsPathFromId(pathname))), server, res, next, ) ) { return } let newPathname = pathname.slice(FS_PREFIX.length) if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, '') url.pathname = encodeURIComponent(newPathname) req.url = url.href.slice(url.origin.length) serveFromRoot(req, res, next) } else { next() } } }
Class
2
getModel() { return { privateAttributes: [], attributes: { title: { type: 'text', private: false, }, }, primaryKey: 'id', options: {}, }; },
Class
2
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }), };
Class
2
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }),
Class
2
global.strapi = { config: createConfig() }; Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeTruthy(); expect(strapi.config.get).toHaveBeenCalledWith('api.responses.privateAttributes', []); }); });
Class
2
Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeFalsy(); expect(strapi.config.get).toHaveBeenCalledWith('api.responses.privateAttributes', []); });
Class
2
export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => { if (!editor.selection) return; const { isUrl, forceSubmit } = getPluginOptions<LinkPlugin, V>( editor, ELEMENT_LINK ); const url = floatingLinkSelectors.url(); const isValid = isUrl?.(url) || forceSubmit;
Base
1
isUrl?: (url: string) => boolean;
Base
1
match: { type: getPluginType(editor, ELEMENT_LINK) }, }); // anchor and focus in link -> insert text if (insertTextInLink && linkAbove) { // we don't want to insert marks in links editor.insertText(url); return true; } if (!isUrl?.(url)) return;
Base
1
export function escape(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, interpolation, shellName } = parseOptions( { options, process }, helpers, ); const argAsString = checkedToString(arg); const escape = helpers.getEscapeFunction(shellName, { interpolation }); const escapedArg = escape(argAsString); if (flagProtection) { const flagProtect = helpers.getFlagProtectionFunction(shellName); return flagProtect(escapedArg); } else { return escapedArg; } }
Variant
0
export function quote(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, shellName } = parseOptions( { options, process }, helpers, ); const argAsString = checkedToString(arg); const [escape, quote] = helpers.getQuoteFunction(shellName); const escapedArg = escape(argAsString); if (flagProtection) { const flagProtect = helpers.getFlagProtectionFunction(shellName); return quote(flagProtect(escapedArg)); } else { return quote(escapedArg); } }
Variant
0
export function resolveExecutable({ executable }, { exists, readlink, which }) { try { executable = which(executable); } catch (_) { // For backwards compatibility return the executable even if its location // cannot be obtained return executable; } if (!exists(executable)) { // For backwards compatibility return the executable even if there exists no // file at the specified path return executable; } try { executable = readlink(executable); } catch (_) { // An error will be thrown if the executable is not a (sym)link, this is not // a problem so the error is ignored } return executable; }
Variant
0
export function parseOptions( { options: { flagProtection, interpolation, shell }, process: { env } }, { getDefaultShell, getShellName }, ) { flagProtection = flagProtection ? true : false; interpolation = interpolation ? true : false; shell = isString(shell) ? shell : getDefaultShell({ env }); const shellName = getShellName({ shell }, { resolveExecutable }); return { flagProtection, interpolation, shellName }; }
Variant
0
export function getShellName({ shell }, { resolveExecutable }) { shell = resolveExecutable( { executable: shell }, { exists: fs.existsSync, readlink: fs.readlinkSync, which: which.sync }, ); const shellName = path.basename(shell); if (getEscapeFunction(shellName, {}) === undefined) { return binBash; } return shellName; }
Variant
0
function getPlatformFixtures() { if (common.isWindows) { return fixturesWindows; } else { return fixturesUnix; } }
Variant
0
export function* platformShells() { if (common.isWindows) { yield* common.shellsWindows; } else { yield* common.shellsUnix; } }
Variant
0
quote: Object.values(fixtures.quote[shell]).flat(), }; }
Variant
0
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), Ext.util.Format.htmlEncode(data.data.key), function () { grid.getStore().removeAt(rowIndex); }.bind(this)); }.bind(this)
Base
1
const htmlPath = `${basePath}/${filename(mdFilePath)}.html`; // if (mdFilename !== 'sanitize_9.md') continue; const mdToHtmlOptions: any = { bodyOnly: true, }; if (mdFilename === 'checkbox_alternative.md') { mdToHtmlOptions.plugins = { checkbox: { checkboxRenderingType: 2, }, }; } const markdown = await shim.fsDriver().readFile(mdFilePath); let expectedHtml = await shim.fsDriver().readFile(htmlPath); const result = await mdToHtml.render(markdown, null, mdToHtmlOptions); let actualHtml = result.html; expectedHtml = expectedHtml.replace(/\r?\n/g, '\n'); actualHtml = actualHtml.replace(/\r?\n/g, '\n'); if (actualHtml !== expectedHtml) { const msg: string[] = [ '', `Error converting file: ${mdFilename}`, '--------------------------------- Got:', actualHtml, '--------------------------------- Raw:', actualHtml.split('\n'), '--------------------------------- Expected:', expectedHtml.split('\n'), '--------------------------------------------', '', ]; // eslint-disable-next-line no-console console.info(msg.join('\n')); expect(false).toBe(true); // return; } else { expect(true).toBe(true); } } }));
Base
1
async updatePlanId(userId: number, planId: number) { const user = await User.findByPk(userId) if (!user) throw Errors.USER_NOT_FOUND if (userId === 6 && planId === 6) { throw Errors.HANDLED_BY_PAYMENT_PROVIDER } await User.update( { planId }, { where: { id: userId } } ) return true }
Class
2
decryptTopicPage(data) { if (!data.currentRouteName?.startsWith("topic.")) { return; } if ( !this.container || this.container.isDestroyed || this.container.isDestroying ) { return; } const topicController = this.container.lookup("controller:topic"); const topic = topicController.get("model"); const topicId = topic.id; if (topic?.encrypted_title) { document.querySelector(".private_message").classList.add("encrypted"); } getTopicTitle(topicId).then((topicTitle) => { // Update fancy title stored in model topicController.model.set("fancy_title", topicTitle); // Update document title const documentTitle = this.container.lookup("service:document-title"); documentTitle.setTitle( documentTitle .getTitle() .replace(topicController.model.title, topicTitle) ); }); },
Base
1
function inbox(ctx: Router.RouterContext) { let signature; try { signature = httpSignature.parseRequest(ctx.req, { 'headers': [] }); } catch (e) { ctx.status = 401; return; } processInbox(ctx.request.body, signature); ctx.status = 202; }
Class
2
function isActivityPubReq(ctx: Router.RouterContext) { ctx.response.vary('Accept'); const accepted = ctx.accepts('html', ACTIVITY_JSON, LD_JSON); return typeof accepted === 'string' && !accepted.match(/html/); }
Class
2
visibility: In(['public' as const, 'home' as const]), localOnly: false, }); if (note == null) { ctx.status = 404; return; } // リモートだったらリダイレクト if (note.userHost != null) { if (note.uri == null || isSelfHost(note.userHost)) { ctx.status = 500; return; } ctx.redirect(note.uri); return; } ctx.body = renderActivity(await renderNote(note, false)); ctx.set('Cache-Control', 'public, max-age=180'); setResponseType(ctx); });
Class
2
host: IsNull(), }); if (user == null) { ctx.status = 404; return; } const keypair = await getUserKeypair(user.id); if (Users.isLocalUser(user)) { ctx.body = renderActivity(renderKey(user, keypair)); ctx.set('Cache-Control', 'public, max-age=180'); setResponseType(ctx); } else { ctx.status = 400; } });
Class
2
async function userInfo(ctx: Router.RouterContext, user: User | null) { if (user == null) { ctx.status = 404; return; } ctx.body = renderActivity(await renderPerson(user as ILocalUser)); ctx.set('Cache-Control', 'public, max-age=180'); setResponseType(ctx); }
Class
2
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
Base
1
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
Base
1
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
Base
1
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
Base
1
cert: fs.readFileSync(sslCert), passphrase: sslKeyPassphrase, }, this.app); } else { log.info("server", "Server Type: HTTP"); this.httpServer = http.createServer(this.app); } try { this.indexHTML = fs.readFileSync("./dist/index.html").toString(); } catch (e) { // "dist/index.html" is not necessary for development if (process.env.NODE_ENV !== "development") { log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); process.exit(1); } } // Set Monitor Types UptimeKumaServer.monitorTypeList["real-browser"] = new RealBrowserMonitorType(); UptimeKumaServer.monitorTypeList["tailscale-ping"] = new TailscalePing(); this.io = new Server(this.httpServer); }
Class
2
static getInstance(args) { if (UptimeKumaServer.instance == null) { UptimeKumaServer.instance = new UptimeKumaServer(args); } return UptimeKumaServer.instance; }
Compound
4
constructor(cfg) { super(); /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ this.cfg = Object.assign( new Base(), { keySize: 128 / 32, hasher: SHA1Algo, iterations: 1, }, cfg, ); }
Class
2
export async function trackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> { const request = new Request(url, init) return await runInSpan( { op: 'fetch', description: `${request.method} ${request.url}`, }, async () => await fetch(url, init) ) }
Base
1
export async function safeTrackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> { const request = new Request(url, init) return await runInSpan( { op: 'fetch', description: `${request.method} ${request.url}`, }, async () => { await raiseIfUserProvidedUrlUnsafe(request.url) return await fetch(url, init) } ) }
Base
1
...(isTestEnv() ? { 'test-utils/write-to-file': writeToFile, } : {}), '@google-cloud/bigquery': bigquery, '@google-cloud/pubsub': pubsub, '@google-cloud/storage': gcs, '@posthog/plugin-contrib': contrib, '@posthog/plugin-scaffold': scaffold, 'aws-sdk': AWS, ethers: ethers, 'generic-pool': genericPool, 'node-fetch': isCloud() && (!hub.fetchHostnameGuardTeams || hub.fetchHostnameGuardTeams.has(teamId)) ? safeTrackedFetch : trackedFetch, 'snowflake-sdk': snowflake, crypto: crypto, jsonwebtoken: jsonwebtoken, faker: faker, pg: pg, stream: { PassThrough }, url: url, zlib: zlib, }
Base
1
person_created_at: DateTime.fromISO(now).toUTC(), } as any) expect(fetch).toHaveBeenCalledWith('https://example.com/', { body: JSON.stringify( { hook: { id: 'id', event: 'foo', target: 'https://example.com/', }, data: { event: 'foo', teamId: hook.team_id, person: { uuid: uuid, properties: { foo: 'bar' }, created_at: now, }, }, }, undefined, 4 ), headers: { 'Content-Type': 'application/json' }, method: 'POST', timeout: 20000, }) }) test('private IP hook allowed on self-hosted', async () => { await hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) expect(fetch).toHaveBeenCalledWith('http://127.0.0.1', expect.anything()) }) test('private IP hook forbidden on Cloud', async () => { jest.mocked(isCloud).mockReturnValue(true) await expect( hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) ).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard')) }) })
Base
1
person_created_at: DateTime.fromISO(now).toUTC(), } as any) expect(fetch).toHaveBeenCalledWith('https://example.com/', { body: JSON.stringify( { hook: { id: 'id', event: 'foo', target: 'https://example.com/', }, data: { event: 'foo', teamId: hook.team_id, person: { uuid: uuid, properties: { foo: 'bar' }, created_at: now, }, }, }, undefined, 4 ), headers: { 'Content-Type': 'application/json' }, method: 'POST', timeout: 20000, }) }) test('private IP hook allowed on self-hosted', async () => { await hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) expect(fetch).toHaveBeenCalledWith('http://127.0.0.1', expect.anything()) }) test('private IP hook forbidden on Cloud', async () => { jest.mocked(isCloud).mockReturnValue(true) await expect( hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) ).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard')) }) }) })
Base
1
const protectRoute = (query, info) => { const savePopulate = protectPopulate(query, info); query.populate = savePopulate.populate; query.fields = savePopulate.fields; query.filters = protectFilters(query.filters, info); return query; };
Class
2
'Content-Length': Buffer.byteLength(body) } }, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { resolve(normaliseResponse(data)) }); }).on('error', (err) => { reject(err) }) req.write(body); req.end(); })
Base
1
markClaimed: async function (inviteId = null, user) { const invite = await this.get(`id = ${inviteId}`); if (!invite) return { success: false, error: "Invite does not exist." }; if (invite.status !== "pending") return { success: false, error: "Invite is not in pending status." }; const db = await this.db(); const { success, message } = await db .run(`UPDATE ${this.tablename} SET status=?,claimedBy=? WHERE id=?`, [ "claimed", user.id, inviteId, ]) .then(() => { return { success: true, message: null }; }) .catch((error) => { return { success: false, message: error.message }; }); db.close(); if (!success) { console.error(message); return { success: false, error: message }; } return { success: true, error: null }; },
Base
1
deactivate: async function (inviteId = null) { const invite = await this.get(`id = ${inviteId}`); if (!invite) return { success: false, error: "Invite does not exist." }; if (invite.status !== "pending") return { success: false, error: "Invite is not in pending status." }; const db = await this.db(); const { success, message } = await db .run(`UPDATE ${this.tablename} SET status=? WHERE id=?`, [ "disabled", inviteId, ]) .then(() => { return { success: true, message: null }; }) .catch((error) => { return { success: false, message: error.message }; }); db.close(); if (!success) { console.error(message); return { success: false, error: message }; } return { success: true, error: null }; },
Base
1
update: async function (userId, updates = {}) { const user = await this.get(`id = ${userId}`); if (!user) return { success: false, error: "User does not exist." }; const { username, password, role, suspended = 0 } = updates; const toUpdate = { suspended }; if (user.username !== username && username?.length > 0) { const usedUsername = !!(await this.get(`username = '${username}'`)); if (usedUsername) return { success: false, error: `${username} is already in use.` }; toUpdate.username = username; } if (!!password) { const bcrypt = require("bcrypt"); toUpdate.password = bcrypt.hashSync(password, 10); } if (user.role !== role && ["admin", "default"].includes(role)) { // If was existing admin and that has been changed // make sure at least one admin exists if (user.role === "admin") { const validAdminCount = (await this.count(`role = 'admin'`)) > 1; if (!validAdminCount) return { success: false, error: `There would be no admins if this action was completed. There must be at least one admin.`, }; } toUpdate.role = role; } if (Object.keys(toUpdate).length !== 0) { const values = Object.values(toUpdate); const template = `UPDATE ${this.tablename} SET ${Object.keys( toUpdate ).map((key) => { return `${key}=?`; })} WHERE id = ?`; const db = await this.db(); const { success, message } = await db .run(template, [...values, userId]) .then(() => { return { success: true, message: null }; }) .catch((error) => { return { success: false, message: error.message }; }); db.close(); if (!success) { console.error(message); return { success: false, error: message }; } } return { success: true, error: null }; },
Base
1
new: async function (name = null, creatorId = null) { if (!name) return { result: null, message: "name cannot be null" }; var slug = slugify(name, { lower: true }); const existingBySlug = await this.get(`slug = '${slug}'`); if (existingBySlug !== null) { const slugSeed = Math.floor(10000000 + Math.random() * 90000000); slug = slugify(`${name}-${slugSeed}`, { lower: true }); } const db = await this.db(); const { id, success, message } = await db .run(`INSERT INTO ${this.tablename} (name, slug) VALUES (?, ?)`, [ name, slug, ]) .then((res) => { return { id: res.lastID, success: true, message: null }; }) .catch((error) => { return { id: null, success: false, message: error.message }; }); if (!success) { db.close(); return { workspace: null, message }; } const workspace = await db.get( `SELECT * FROM ${this.tablename} WHERE id = ${id}` ); db.close(); // If created with a user then we need to create the relationship as well. // If creating with an admin User it wont change anything because admins can // view all workspaces anyway. if (!!creatorId) await WorkspaceUser.create(creatorId, workspace.id); return { workspace, message: null }; },
Base
1
async function validApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json({ error: "No valid api key found.", }); return; } const apiKey = await ApiKey.get(`secret = '${bearerKey}'`); if (!apiKey) { response.status(403).json({ error: "No valid api key found.", }); return; } next(); }
Base
1
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.name } this.methods = [m] } this.patterns = [] }
Base
1
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.name } this.methods = [m] } this.patterns = [] }
Base
1
export const canCreateToken = (userScopes: string[], tokenScopes: string[]) => { return tokenScopes.every((scope) => userScopes.includes(scope)) }
Base
1
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing."); let params; if (args.paramJson) { try { params = JSON.parse(args.paramJson); } catch (e) { return respondWithError("'paramJson' contains malformed JSON string."); } } try { switch (args.action) { case "getAwsLoginUrlForEvent": return getAwsLoginUrlForEvent(params); case "getAwsLoginUrlForLease": return getAwsLoginUrlForLease(params); default: throw new Error("unknown API action '" + args.action + "'"); } } catch (error) { return respondWithError("Internal error while trying to execute login task.", error); } };
Pillar
3
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing."); let params; if (args.paramJson) { try { params = JSON.parse(args.paramJson); } catch (e) { return respondWithError("'paramJson' contains malformed JSON string."); } } try { switch (args.action) { case "getAwsLoginUrlForEvent": return getAwsLoginUrlForEvent(params); case "getAwsLoginUrlForLease": return getAwsLoginUrlForLease(params); default: throw new Error("unknown API action '" + args.action + "'"); } } catch (error) { return respondWithError("Internal error while trying to execute login task.", error); } };
Class
2
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDensity(Density[config.DISPLAY_TEXT_MODE]) },[config]) useEffect(() => { if (authStatus === "authenticated") { dispatch(setCurrentUser(user)); dispatch(fetchConfig()); } }, [dispatch, user, authStatus]); return children; };
Pillar
3
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDensity(Density[config.DISPLAY_TEXT_MODE]) },[config]) useEffect(() => { if (authStatus === "authenticated") { dispatch(setCurrentUser(user)); dispatch(fetchConfig()); } }, [dispatch, user, authStatus]); return children; };
Class
2
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
Pillar
3
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
Class
2
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
Pillar
3
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
Class
2
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event.item.eventHours, "hours") .unix(), maxAccounts: Event.item.maxAccounts, eventId: Event.item.id }) ) } disabled={NotificationItem.visible} > Open AWS Console </Button> <AwsLoginModal /> </> )} <Alert type={NotificationItem.type} header={NotificationItem.header} onDismiss={() => dispatch({ type: "notification/dismiss" })} visible={NotificationItem.visible} dismissAriaLabel="Close error" dismissible > {NotificationItem.content} </Alert> </SpaceBetween> </Container>
Pillar
3
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event.item.eventHours, "hours") .unix(), maxAccounts: Event.item.maxAccounts, eventId: Event.item.id }) ) } disabled={NotificationItem.visible} > Open AWS Console </Button> <AwsLoginModal /> </> )} <Alert type={NotificationItem.type} header={NotificationItem.header} onDismiss={() => dispatch({ type: "notification/dismiss" })} visible={NotificationItem.visible} dismissAriaLabel="Close error" dismissible > {NotificationItem.content} </Alert> </SpaceBetween> </Container>
Class
2
const updateFormValue = (update) => { setValue((prev) => { let newValue = { ...prev, ...update }; validateInputs(newValue, true); let user = newValue.user.replace(/[^a-zA-Z0-9]/g, Config.EVENT_EMAIL_SUBST); if (newValue.eventId !== "") newValue.principalId = newValue.eventId + Config.EVENT_PRINCIPAL_SEPARATOR + user; else newValue.principalId = user; return newValue; }); };
Pillar
3
const updateFormValue = (update) => { setValue((prev) => { let newValue = { ...prev, ...update }; validateInputs(newValue, true); let user = newValue.user.replace(/[^a-zA-Z0-9]/g, Config.EVENT_EMAIL_SUBST); if (newValue.eventId !== "") newValue.principalId = newValue.eventId + Config.EVENT_PRINCIPAL_SEPARATOR + user; else newValue.principalId = user; return newValue; }); };
Class
2
paramJson: JSON.stringify({ budgetAmount: parseInt(budgetAmount), expiresOn, principalId, budgetNotificationEmails, user, budgetCurrency: config.BUDGET_CURRENCY }) }) ).then((response) => {
Pillar
3
paramJson: JSON.stringify({ budgetAmount: parseInt(budgetAmount), expiresOn, principalId, budgetNotificationEmails, user, budgetCurrency: config.BUDGET_CURRENCY }) }) ).then((response) => {
Class
2
eventId: item.principalId.includes(action.config.EVENT_PRINCIPAL_SEPARATOR) ? item.principalId.substring(0, action.config.EVENT_ID_LENGTH) : "" });
Pillar
3
eventId: item.principalId.includes(action.config.EVENT_PRINCIPAL_SEPARATOR) ? item.principalId.substring(0, action.config.EVENT_ID_LENGTH) : "" });
Class
2
value: inputs.json ? value : value.join(inputs.separator), writeOutputFiles: inputs.writeOutputFiles, outputDir: inputs.outputDir, json: inputs.json, shouldEscape: inputs.escapeJson }) }
Class
2
}): Promise<void> => { let cleanedValue if (json) { cleanedValue = jsonOutput({value, shouldEscape}) } else { cleanedValue = value.toString().trim() } // if safeOutput is true, escape special characters for bash shell if (safeOutput) { cleanedValue = cleanedValue.replace(/[$()`|&;]/g, '\\$&') } core.setOutput(key, cleanedValue) if (writeOutputFiles) { const extension = json ? 'json' : 'txt' const outputFilePath = path.join(outputDir, `${key}.${extension}`) if (!(await exists(outputDir))) { await fs.mkdir(outputDir, {recursive: true}) } await fs.writeFile(outputFilePath, cleanedValue.replace(/\\"/g, '"')) } }
Class
2
}): Promise<void> => { let cleanedValue if (json) { cleanedValue = jsonOutput({value, shouldEscape}) } else { cleanedValue = value.toString().trim() } // if safeOutput is true, escape special characters for bash shell if (safeOutput) { cleanedValue = cleanedValue.replace( /[^\x20-\x7E]|[:*?"<>|;`$()&!]/g, '\\$&' ) } core.setOutput(key, cleanedValue) if (writeOutputFiles) { const extension = json ? 'json' : 'txt' const outputFilePath = path.join(outputDir, `${key}.${extension}`) if (!(await exists(outputDir))) { await fs.mkdir(outputDir, {recursive: true}) } await fs.writeFile(outputFilePath, cleanedValue.replace(/\\"/g, '"')) } }
Class
2
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWith(appHostname) || (fastify.config.VRITE_CLOUD && hostname.endsWith("swagger.io")) ) { callback(null, true); return; } callback(new Error("Not allowed"), false); }
Class
2
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWith(appHostname) || (fastify.config.VRITE_CLOUD && hostname.endsWith("swagger.io")) ) { callback(null, true); return; } callback(new Error("Not allowed"), false); }
Base
1
origin(origin, callback) { if (!origin || origin === "null") { callback(null, true); return; } const { hostname } = new URL(origin); const appHostname = new URL(fastify.config.PUBLIC_APP_URL).hostname; if ( hostname === "localhost" || hostname.endsWith(appHostname) || (fastify.config.VRITE_CLOUD && hostname.endsWith("swagger.io")) ) { callback(null, true); return; } callback(new Error("Not allowed"), false); }
Base
1
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_ASSETS_URL, PUBLIC_DISABLE_ANALYTICS: fastify.config.PUBLIC_DISABLE_ANALYTICS, PUBLIC_APP_TYPE: fastify.config.PUBLIC_APP_TYPE }); };
Class
2
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_ASSETS_URL, PUBLIC_DISABLE_ANALYTICS: fastify.config.PUBLIC_DISABLE_ANALYTICS, PUBLIC_APP_TYPE: fastify.config.PUBLIC_APP_TYPE }); };
Base
1
const renderPage = async (reply: FastifyReply): Promise<void> => { return reply.view("index.html", { PUBLIC_APP_URL: fastify.config.PUBLIC_APP_URL, PUBLIC_API_URL: fastify.config.PUBLIC_API_URL, PUBLIC_COLLAB_URL: fastify.config.PUBLIC_COLLAB_URL, PUBLIC_ASSETS_URL: fastify.config.PUBLIC_ASSETS_URL, PUBLIC_DISABLE_ANALYTICS: fastify.config.PUBLIC_DISABLE_ANALYTICS, PUBLIC_APP_TYPE: fastify.config.PUBLIC_APP_TYPE }); };
Base
1
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Class
2
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Base
1
private publishGitDataEvent = createEventPublisher<GitDataEvent>((workspaceId) => { return `gitData:${workspaceId}`; });
Base
1
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); } const { sessionId } = fastify.jwt.verify<{ sessionId: string }>(token); const sessionCache = await fastify.redis.get(`session:${sessionId}`); const sessionData = JSON.parse(sessionCache || "{}") as SessionData; if (sessionData.baseType !== "admin" && !sessionData.permissions.includes("editContent")) { data.connection.readOnly = true; } return sessionData; },
Class
2
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); } const { sessionId } = fastify.jwt.verify<{ sessionId: string }>(token); const sessionCache = await fastify.redis.get(`session:${sessionId}`); const sessionData = JSON.parse(sessionCache || "{}") as SessionData; if (sessionData.baseType !== "admin" && !sessionData.permissions.includes("editContent")) { data.connection.readOnly = true; } return sessionData; },
Base
1
async onAuthenticate(data) { const cookies = fastify.parseCookie(data.requestHeaders.cookie || ""); if (!cookies.accessToken) { throw unauthorized(); } const token = fastify.unsignCookie(cookies.accessToken || "")?.value || ""; if (!token) { throw unauthorized(); } const { sessionId } = fastify.jwt.verify<{ sessionId: string }>(token); const sessionCache = await fastify.redis.get(`session:${sessionId}`); const sessionData = JSON.parse(sessionCache || "{}") as SessionData; if (sessionData.baseType !== "admin" && !sessionData.permissions.includes("editContent")) { data.connection.readOnly = true; } return sessionData; },
Base
1
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Class
2
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Base
1
createContext({ req, res }: { req: FastifyRequest; res: FastifyReply }) { return createContext({ req, res }, fastify); }
Base
1
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphql": return [await import("prettier/plugins/graphql")]; case "html": case "vue": return [await import("prettier/plugins/html")]; case "markdown": return [await import("prettier/plugins/markdown")]; case "yaml": case "json": return [await import("prettier/plugins/yaml")]; case "css": case "less": case "scss": return [await import("prettier/plugins/postcss")]; default: return null; } };
Class
2
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphql": return [await import("prettier/plugins/graphql")]; case "html": case "vue": return [await import("prettier/plugins/html")]; case "markdown": return [await import("prettier/plugins/markdown")]; case "yaml": case "json": return [await import("prettier/plugins/yaml")]; case "css": case "less": case "scss": return [await import("prettier/plugins/postcss")]; default: return null; } };
Base
1
const loadParserPlugins = async (language: string): Promise<Plugin[] | null> => { switch (language as SupportedLanguages) { case "javascript": case "typescript": return [ await import("prettier/plugins/babel"), (await import("prettier/plugins/estree")) as Plugin ]; case "graphql": return [await import("prettier/plugins/graphql")]; case "html": case "vue": return [await import("prettier/plugins/html")]; case "markdown": return [await import("prettier/plugins/markdown")]; case "yaml": case "json": return [await import("prettier/plugins/yaml")]; case "css": case "less": case "scss": return [await import("prettier/plugins/postcss")]; default: return null; } };
Base
1
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Class
2
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Base
1
...(language === "json" && { trailingComma: "none", singleQuote: false }) }); } return code; };
Base
1
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } return (query: string) => { const suggestions = engine.autoSuggest(query, { prefix: true }); return suggestions .filter((v) => v) .map(({ suggestion }) => { return suggestion; }); }; };
Class
2
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } return (query: string) => { const suggestions = engine.autoSuggest(query, { prefix: true }); return suggestions .filter((v) => v) .map(({ suggestion }) => { return suggestion; }); }; };
Base
1
): ((query: string) => string[]) => { const languageIds = getLanguageIds(languages); const engine = searchEngine() || new MiniSearch({ fields: ["id"], searchOptions: { prefix: true } }); if (!searchEngine()) { engine.addAll(languageIds); setSearchEngine(engine); } return (query: string) => { const suggestions = engine.autoSuggest(query, { prefix: true }); return suggestions .filter((v) => v) .map(({ suggestion }) => { return suggestion; }); }; };
Base
1
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Class
2
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Base
1
command({ editor, range }) { return editor.chain().focus().deleteRange(range).setWrapper().run(); }
Base
1