repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
framework | github_2023 | observablehq | typescript | LoaderResolver.getSourceFileHash | getSourceFileHash(name: string): string {
const path = this.getSourceFilePath(name);
const info = getFileInfo(this.root, path);
if (!info) return createHash("sha256").digest("hex");
const {hash} = info;
return path === name ? hash : createHash("sha256").update(hash).update(String(info.mtimeMs)).digest("hex");
} | /**
* Returns the hash of the file with the given name within the source root, or
* if the name refers to a file generated by a data loader, the hash of the
* corresponding data loader source and its modification time. The latter
* ensures that if the data loader is “touched” (even without changing its
* contents) that the data loader will be re-run.
*/ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L292-L298 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | makeFenceRenderer | function makeFenceRenderer(baseRenderer: RenderRule): RenderRule {
return (tokens, idx, options, context: ParseContext, self) => {
const {path, params} = context;
const token = tokens[idx];
const {tag, attributes} = parseInfo(token.info);
token.info = tag;
let html = "";
let source: string | undefined;
try {
source = isFalse(attributes.run) ? undefined : getLiveSource(token.content, tag, attributes);
if (source != null) {
const id = uniqueCodeId(context, source);
// TODO const sourceLine = context.startLine + context.currentLine;
const node = parseJavaScript(source, {path, params});
context.code.push({id, node, mode: tag === "jsx" || tag === "tsx" ? "jsx" : "block"});
html += `<div class="observablehq observablehq--block">${
node.expression ? "<observablehq-loading></observablehq-loading>" : ""
}<!--:${id}:--></div>\n`;
}
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
html += `<div class="observablehq observablehq--block">
<div class="observablehq--inspect observablehq--error">SyntaxError: ${he.escape(error.message)}</div>
</div>\n`;
}
if (attributes.echo == null ? source == null : !isFalse(attributes.echo)) {
html += baseRenderer(tokens, idx, options, context, self);
}
return html;
};
} | // TODO sourceLine and remap syntax error position; consider showing a code | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/markdown.ts#L113-L143 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | findTitle | function findTitle(tokens: ReturnType<MarkdownIt["parse"]>): string | null {
for (const [i, token] of tokens.entries()) {
if (token.type === "heading_open" && token.tag === "h1") {
const next = tokens[i + 1];
if (next?.type === "inline") {
const text = next.children
?.filter((t) => t.type === "text")
.map((t) => t.content)
.join("");
if (text) {
return text;
}
}
}
}
return null;
} | // TODO Make this smarter. | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/markdown.ts#L330-L346 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | isBadCommonJs | function isBadCommonJs(specifier: string): boolean {
const {name} = parseNpmSpecifier(specifier);
return name === "react" || name === "react-dom" || name === "react-is" || name === "scheduler";
} | /**
* React (and its dependencies) are distributed as CommonJS modules, and worse,
* they’re incompatible with cjs-module-lexer; so when we try to import them as
* ES modules we only see a default export. We fix this by creating a shim
* module that exports everything that is visible to require. I hope the React
* team distributes ES modules soon…
*
* https://github.com/facebook/react/issues/11503
*/ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/node.ts#L84-L87 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | walk | function walk(config: Config): Iterable<Iterable<Page>> {
const {pages, loaders, title = "Home"} = config;
const pageGroups = new Map<string, Page[]>();
const visited = new Set<string>();
function visit(page: Page) {
if (visited.has(page.path) || !page.pager) return;
visited.add(page.path);
let pageGroup = pageGroups.get(page.pager);
if (!pageGroup) pageGroups.set(page.pager, (pageGroup = []));
pageGroup.push(page);
}
if (loaders.findPage("/index")) visit({name: title, path: "/index", pager: "main"});
for (const page of pages) {
if (page.path !== null) visit(page as Page);
if ("pages" in page) for (const p of page.pages) visit(p);
}
return pageGroups.values();
} | /**
* Walks the unique pages in the site so as to avoid creating cycles. Implicitly
* adds a link at the beginning to the home page (/index).
*/ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/pager.ts#L47-L68 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | end | function end(req: IncomingMessage, res: ServerResponse, content: string, type: string): void {
const etag = `"${createHash("sha256").update(content).digest("base64")}"`;
const date = new Date().toUTCString();
res.setHeader("Content-Type", `${type}; charset=utf-8`);
res.setHeader("Date", date);
res.setHeader("Last-Modified", date);
res.setHeader("ETag", etag);
if (req.headers["if-none-match"] === etag) {
res.statusCode = 304;
res.end();
} else if (req.method === "HEAD") {
res.end();
} else {
res.end(content);
}
} | // Like send, but for in-memory dynamic content. | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/preview.ts#L265-L280 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | getWatchFiles | function getWatchFiles(resolvers: Resolvers): Iterable<string> {
const files = new Set<string>();
for (const specifier of resolvers.stylesheets) {
if (isPathImport(specifier)) {
files.add(specifier);
}
}
for (const specifier of resolvers.assets) {
files.add(specifier);
}
for (const specifier of resolvers.files) {
files.add(specifier);
}
for (const specifier of resolvers.localImports) {
files.add(specifier);
}
return files;
} | // Note that while we appear to be watching the referenced files here, | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/preview.ts#L285-L302 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | transpileCode | function transpileCode({id, node, mode}: MarkdownCode, resolvers: Resolvers, params?: Params): string {
const hash = createHash("sha256");
for (const f of node.files) hash.update(resolvers.resolveFile(f.name));
return `${transpileJavaScript(node, {id, mode, params, ...resolvers})} // ${hash.digest("hex")}`;
} | // Including the file has as a comment ensures that the code changes when a | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/preview.ts#L483-L487 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | findFreeInputs | function findFreeInputs(page: MarkdownPage): Set<string> {
const outputs = new Set<string>(defaultGlobals).add("display").add("view").add("visibility").add("invalidation");
const inputs = new Set<string>();
// Compute all declared variables.
for (const {node} of page.code) {
if (node.declarations) {
for (const {name} of node.declarations) {
outputs.add(name);
}
}
}
// Compute all unbound references.
for (const {node} of page.code) {
for (const {name} of node.references) {
if (!outputs.has(name)) {
inputs.add(name);
}
}
}
return inputs;
} | // Returns any inputs that are not declared in outputs. These typically refer to | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/resolvers.ts#L527-L550 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | rewriteTypeScriptImports | function rewriteTypeScriptImports(code: string): string {
return code.replace(/(?<=\bimport\(([`'"])[\w./]+)\.ts(?=\1\))/g, ".js");
} | // For reasons not entirely clear (to me), when we resolve a relative import to | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/rollup.ts#L113-L115 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | routeParams | function routeParams(root: string, cwd: string, parts: string[], exts: string[]): RouteResult | undefined {
switch (parts.length) {
case 0:
return;
case 1: {
const [first] = parts;
if (!isParameterized(first)) {
for (const ext of exts) {
const path = join(root, cwd, first + ext);
if (existsSync(path)) {
if (!statSync(path).isFile()) return; // ignore non-files
return {path: join(cwd, first + ext), ext};
}
}
}
if (first) {
for (const ext of exts) {
for (const file of globSync(`*\\[?*\\]*${ext}`, {cwd: join(root, cwd), nodir: true})) {
const params = matchParams(basename(file, ext), first);
if (params) return {path: join(cwd, file), params: {...params}, ext};
}
}
}
return;
}
default: {
const [first, ...rest] = parts;
const path = join(root, cwd, first);
if (existsSync(path)) {
if (!statSync(path).isDirectory()) return; // ignore non-directories
if (!isParameterized(first)) {
const found = routeParams(root, join(cwd, first), rest, exts);
if (found) return found;
}
}
if (first) {
for (const dir of globSync("*\\[?*\\]*/", {cwd: join(root, cwd)})) {
const params = matchParams(dir, first);
if (!params) continue;
const found = routeParams(root, join(cwd, dir), rest, exts);
if (found) return {...found, params: {...found.params, ...params}};
}
}
}
}
} | /**
* Finds a parameterized file (dynamic route) recursively, such that the most
* specific match is returned.
*/ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/route.ts#L59-L104 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | readTemplateToken | function readTemplateToken(parser: any) {
out: for (; parser.pos < parser.input.length; parser.pos++) {
switch (parser.input.charCodeAt(parser.pos)) {
case CODE_BACKSLASH: {
if (parser.pos < parser.input.length - 1) ++parser.pos; // not a terminal slash
break;
}
case CODE_DOLLAR: {
if (parser.input.charCodeAt(parser.pos + 1) === CODE_BRACEL) {
if (parser.pos === parser.start && parser.type === tt.invalidTemplate) {
parser.pos += 2;
return parser.finishToken(tt.dollarBraceL);
}
break out;
}
break;
}
}
}
return parser.finishToken(tt.invalidTemplate, parser.input.slice(parser.start, parser.pos));
} | // This is our custom override for parsing a template that allows backticks. | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/tag.ts#L67-L87 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | stringLength | function stringLength(string: string): number {
return [...new Intl.Segmenter().segment(string)].length;
} | /** Counts the number of graphemes in the specified string. */ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/tree.ts#L71-L73 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | helpArgs | function helpArgs<T extends DescribableParseArgsConfig>(
command: string | undefined,
config: T
): ReturnType<typeof parseArgs<T>> {
const {options = {}} = config;
// Find the boolean --foo options that have a corresponding boolean --no-foo.
const booleanPairs: string[] = [];
for (const key in options) {
if (options[key].type === "boolean" && !key.startsWith("no-") && options[`no-${key}`]?.type === "boolean") {
booleanPairs.push(key);
}
}
let result: ReturnType<typeof parseArgs<T>>;
try {
result = parseArgs<T>({
...config,
tokens: config.tokens || booleanPairs.length > 0,
options: {...options, help: {type: "boolean", short: "h"}, debug: {type: "boolean"}},
args
});
} catch (error: any) {
if (!error.code?.startsWith("ERR_PARSE_ARGS_")) throw error;
console.error(`observable: ${error.message}. See 'observable help${command ? ` ${command}` : ""}'.`);
process.exit(1);
}
// Log automatic help.
if ((result.values as any).help) {
// Omit hidden flags from help.
const publicOptions = Object.fromEntries(Object.entries(options).filter(([, option]) => !option.hidden));
console.log(
`Usage: observable ${command}${command === undefined || command === "help" ? " <command>" : ""}${Object.entries(
publicOptions
)
.map(([name, {default: def}]) => ` [--${name}${def === undefined ? "" : `=${def}`}]`)
.join("")}`
);
if (Object.values(publicOptions).some((spec) => spec.description)) {
console.log();
for (const [long, spec] of Object.entries(publicOptions)) {
if (spec.description) {
const left = ` ${spec.short ? `-${spec.short}, ` : ""}--${long}`.padEnd(20);
console.log(`${left}${spec.description}`);
}
}
console.log();
}
process.exit(0);
}
// Merge --no-foo into --foo based on order
// https://nodejs.org/api/util.html#parseargs-tokens
if ("tokens" in result && result.tokens) {
const {values, tokens} = result;
for (const key of booleanPairs) {
for (const token of tokens) {
if (token.kind !== "option") continue;
const {name} = token;
if (name === `no-${key}`) values[key] = false;
else if (name === key) values[key] = true;
}
}
}
return result;
} | // A wrapper for parseArgs that adds --help functionality with automatic usage. | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/bin/observable.ts#L308-L375 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | isBlockScope | function isBlockScope(node: Node): node is FunctionNode | Program | BlockStatement | ForInStatement | ForOfStatement | ForStatement {
return (
node.type === "BlockStatement" ||
node.type === "SwitchStatement" ||
node.type === "ForInStatement" ||
node.type === "ForOfStatement" ||
node.type === "ForStatement" ||
isScope(node)
);
} | // prettier-ignore | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/javascript/references.ts#L36-L45 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | stringify | function stringify(key: string, value: any): any {
return typeof value === "bigint" ? value.toString() : value instanceof Map ? [...value] : value;
} | // Convert to a serializable representation. | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/test/javascript/parse-test.ts#L20-L22 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | ObservableApiMock.expectFileUpload | expectFileUpload({deployId, path, action = "upload"}: ExpectedFileSpec): ObservableApiMock {
this._expectedFiles.push({deployId, path, action});
return this;
} | /** Register a file that is expected to be uploaded. Also includes that file in
* an automatic interceptor to `/deploy/:deployId/manifest`. If the action is
* "upload", an interceptor for `/deploy/:deployId/file` will be registered.
* If it is set to "skip", that interceptor will not be registered. */ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/test/mocks/observableApi.ts#L278-L281 | 82412a49f495a018367fc569f0407e06bae3479f |
framework | github_2023 | observablehq | typescript | headersMatcher | function headersMatcher(expected: Record<string, string | RegExp>): (headers: Record<string, string>) => boolean {
const lowercaseExpected = Object.fromEntries(Object.entries(expected).map(([key, val]) => [key.toLowerCase(), val]));
return (actual) => {
const lowercaseActual = Object.fromEntries(Object.entries(actual).map(([key, val]) => [key.toLowerCase(), val]));
for (const [key, expected] of Object.entries(lowercaseExpected)) {
if (typeof expected === "string" && lowercaseActual[key] !== expected) return false;
if (expected instanceof RegExp && !lowercaseActual[key].match(expected)) return false;
}
return true;
};
} | /** All headers in `expected` must be present and have the expected value.
*
* If `expected` contains an "undefined" value, then it asserts that the header
* is not present in the actual headers. */ | https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/test/mocks/observableApi.ts#L433-L443 | 82412a49f495a018367fc569f0407e06bae3479f |
EasyTier | github_2023 | EasyTier | typescript | ApiClient.register | public async register(data: RegisterData): Promise<RegisterResponse> {
try {
data.credentials.password = Md5.hashStr(data.credentials.password);
const response = await this.client.post<RegisterResponse>('/auth/register', data);
console.log("register response:", response);
return { success: true, message: 'Register success', };
} catch (error) {
if (error instanceof AxiosError) {
return { success: false, message: 'Failed to register, error: ' + JSON.stringify(error.response?.data), };
}
return { success: false, message: 'Unknown error, error: ' + error, };
}
} | // 注册 | https://github.com/EasyTier/EasyTier/blob/2632c4419520b2b391faa4eda13f00580d75d6ef/easytier-web/frontend-lib/src/modules/api.ts#L97-L109 | 2632c4419520b2b391faa4eda13f00580d75d6ef |
EasyTier | github_2023 | EasyTier | typescript | ApiClient.login | public async login(data: Credential): Promise<LoginResponse> {
try {
data.password = Md5.hashStr(data.password);
const response = await this.client.post<any>('/auth/login', data);
console.log("login response:", response);
return { success: true, message: 'Login success', };
} catch (error) {
if (error instanceof AxiosError) {
if (error.response?.status === 401) {
return { success: false, message: 'Invalid username or password', };
} else {
return { success: false, message: 'Unknown error, status code: ' + error.response?.status, };
}
}
return { success: false, message: 'Unknown error, error: ' + error, };
}
} | // 登录 | https://github.com/EasyTier/EasyTier/blob/2632c4419520b2b391faa4eda13f00580d75d6ef/easytier-web/frontend-lib/src/modules/api.ts#L112-L128 | 2632c4419520b2b391faa4eda13f00580d75d6ef |
aici | github_2023 | microsoft | typescript | Splice.constructor | constructor(
public backtrack: number,
public ffTokens: Token[],
public whenSampled: Token[] = []
) {} | // the field names below are used by native | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L130-L134 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Splice.addSplice | addSplice(other: Splice) {
assert(this.whenSampled.length === 0);
if (other.backtrack >= this.ffTokens.length) {
this.backtrack += other.backtrack - this.ffTokens.length;
this.ffTokens = other.ffTokens.slice();
} else {
if (other.backtrack > 0) this.ffTokens.splice(-other.backtrack);
this.ffTokens.push(...other.ffTokens);
}
} | /**
* Adds a splice to the current splice.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L139-L148 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Branch.isSplice | isSplice(): boolean {
return (
this.splices.length === 1 && this.splices[0].whenSampled.length === 0
);
} | /**
* Checks if the branch is a single splice.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L170-L174 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | MidProcessResult.constructor | constructor(branches: Branch[]) {
assert(Array.isArray(branches));
assert(branches.every((b) => b instanceof Branch));
this.skip_me = false;
this.branches = branches;
} | /**
* Constructs a MidProcessResult object.
* @param branches - The list of branches.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L190-L195 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | MidProcessResult.isSplice | isSplice(): boolean {
return this.branches.length === 1 && this.branches[0].isSplice();
} | /**
* Checks if the result is a single splice.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L200-L202 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | MidProcessResult.stop | static stop(): MidProcessResult {
return new MidProcessResult([]);
} | /**
* Stops the generation process early.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L219-L221 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | NextToken.run | run(): Promise<Token[]> {
assert(!this._resolve);
AiciAsync.instance._nextToken(this);
return new Promise((resolve) => {
this._resolve = resolve;
});
} | /**
* Awaiting this will return generated token (or tokens, if fast-forwarding requested by self.mid_process()).
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L250-L256 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | NextToken.midProcess | midProcess(): MidProcessResult {
return MidProcessResult.bias(allTokens());
} | /**
* This can be overridden to return a bias, fast-forward tokens, backtrack etc.
* ~20ms time limit.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L262-L264 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | NextToken.postProcess | postProcess(backtrack: number, tokens: Token[]) {} | /**
* This can be overridden to do something with generated tokens.
* ~1ms time limit.
* @param tokens tokens generated in the last step
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L271-L271 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | NextToken.isFixed | isFixed() {
return false;
} | /**
* If true, the postProcess() has to be empty and always self.midProcess().isSplice()
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L276-L278 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | NextToken._mid_process | _mid_process(): MidProcessResult {
this.reset();
const spl = this.isFixed();
const r = this.midProcess();
if (spl) assert(r.isSplice());
return r;
} | // | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L284-L290 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Label.constructor | constructor() {
this.ptr = getTokens().length;
} | /**
* Create a new label the indicates the current position in the sequence.
* Can be passed as `following=` argument to `FixedTokens()`.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L676-L678 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Label.tokensSince | tokensSince(): Token[] {
return getTokens().slice(this.ptr);
} | /**
* Return tokens generated since the label.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L683-L685 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Label.textSince | textSince(): string {
return detokenize(this.tokensSince()).decode();
} | /**
* Return text generated since the label.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L690-L692 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
aici | github_2023 | microsoft | typescript | Label.fixedAfter | async fixedAfter(text: string) {
await new FixedTokens(text, this).run();
} | /**
* Generate given prompt text, replacing all text after the current label.
*/ | https://github.com/microsoft/aici/blob/ecc50362fe2c620c3c8487740267f6fae49397d3/controllers/jsctrl/ts/aici.ts#L697-L699 | ecc50362fe2c620c3c8487740267f6fae49397d3 |
kexp | github_2023 | iximiuz | typescript | _set | function _set(obj: any, path: string[], value: unknown): void {
for (let i = 0; i < path.length - 1; i++) {
const key = path[i];
if (!obj[key]) {
obj[key] = {} as object;
}
obj = obj[key];
}
obj[path[path.length - 1]] = value;
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/iximiuz/kexp/blob/bb1bc8e532e1e26a32d135f453bdc0efddab0ef2/ui/src/common/watchers.ts#L200-L210 | bb1bc8e532e1e26a32d135f453bdc0efddab0ef2 |
kexp | github_2023 | iximiuz | typescript | _objectIdent | function _objectIdent(
clusterUID: ClusterUID,
resource: KubeResource,
rawObj: { metadata: { namespace?: string; name: string; }; },
): KubeObjectIdent {
const resIdent = `${clusterUID}/${resource.groupVersion}/${resource.kind}`;
const objIdent = resource.namespaced
? `${rawObj.metadata.namespace}/${rawObj.metadata.name}`
: rawObj.metadata.name;
return `${resIdent}/${objIdent}`;
} | // Ident cannot be based on the object's uid because: | https://github.com/iximiuz/kexp/blob/bb1bc8e532e1e26a32d135f453bdc0efddab0ef2/ui/src/stores/kubeDataStore.ts#L464-L474 | bb1bc8e532e1e26a32d135f453bdc0efddab0ef2 |
clipper.js | github_2023 | philschmid | typescript | getFirstTag | const getFirstTag = (node: Element) =>
node.outerHTML.split('>').shift()! + '>'; | // Simple match where the <pre> has the `highlight-source-js` tags | https://github.com/philschmid/clipper.js/blob/91787087891350d5c15dc0f43ce00c916e307d2f/src/clipper.ts#L20-L21 | 91787087891350d5c15dc0f43ce00c916e307d2f |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | DefaultHandleBar | const DefaultHandleBar = ({ style, ...otherProps }: DefaultHandleBarProps) => (
<View style={materialStyles.dragHandleContainer} {...otherProps}>
<View style={[materialStyles.dragHandle, style]} />
</View>
); | /**
* This is the default handle bar component used when no custom handle bar component is provided
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/components/defaultHandleBar/index.tsx#L8-L12 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | useAnimatedValue | const useAnimatedValue = (initialValue: number = 0): Animated.Value => {
const animatedValue = useRef(new Animated.Value(initialValue)).current;
return animatedValue;
}; | /**
* Convenience hook for abstracting/storing Animated values.
* Pass your initial number value, get an animated value back.
* @param {number} initialValue Initial animated value
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/hooks/useAnimatedValue.ts#L9-L12 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | useHandleAndroidBackButtonClose | const useHandleAndroidBackButtonClose: UseHandleAndroidBackButtonClose = (
shouldClose = true,
closeSheet,
sheetOpen = false
) => {
const handler = useRef<NativeEventSubscription>();
useEffect(() => {
handler.current = BackHandler.addEventListener('hardwareBackPress', () => {
if (sheetOpen) {
if (shouldClose) {
closeSheet?.();
}
return true; // prevent back press event bubbling as long as sheet is open
} else return false; // when sheet is closed allow bubbling
});
return () => {
handler.current?.remove?.();
};
}, [shouldClose, closeSheet, sheetOpen]);
}; | /**
* Handles closing sheet when back button is pressed on
* android and sheet is opened
*
* @param {boolean} shouldClose Whether to close sheet when back button is pressed
* @param {boolean} closeSheet Function to call to close the sheet
* @param {boolean} sheetOpen Determines the visibility of the sheet
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/hooks/useHandleAndroidBackButtonClose/index.ts#L13-L32 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | useHandleKeyboardEvents | const useHandleKeyboardEvents: UseHandleKeyboardEvents = (
keyboardHandlingEnabled: boolean,
sheetHeight: number,
sheetOpen: boolean,
heightAnimationDriver: HeightAnimationDriver,
contentWrapperRef: React.RefObject<View>
) => {
const SCREEN_HEIGHT = useWindowDimensions().height;
const keyboardHideSubscription = useRef<EmitterSubscription>();
const keyboardShowSubscription = useRef<EmitterSubscription>();
const unsubscribe = () => {
keyboardHideSubscription.current?.remove?.();
keyboardShowSubscription.current?.remove?.();
};
useEffect(() => {
if (keyboardHandlingEnabled) {
keyboardShowSubscription.current = Keyboard.addListener(
'keyboardDidShow',
({ endCoordinates: { height: keyboardHeight } }) => {
if (sheetOpen) {
// Exaggeration of the actual height (24) of the autocorrect view
// that appears atop android keyboard
const keyboardAutoCorrectViewHeight = 50;
contentWrapperRef.current?.measure?.((...result) => {
const sheetYOffset = result[5]; // Y offset of the sheet after keyboard is out
const actualSheetHeight = SCREEN_HEIGHT - sheetYOffset; // new height of the sheet (after keyboard offset)
/**
* We determine soft input/keyboard mode based on the difference between the new sheet height and the
* initial height after keyboard is opened. If there's no much difference, it's adjustPan
* (keyboard overlays sheet), else it's adjustResize (sheet is pushed up)
*/
const sheetIsOverlayed =
actualSheetHeight - sheetHeight < keyboardAutoCorrectViewHeight;
const remainingSpace = SCREEN_HEIGHT - keyboardHeight;
/**
* this is 50% of the remaining space (SCREEN_HEIGHT - keyboardHeight) that remains atop the keybaord
*/
const fiftyPercent = 0.5 * remainingSpace;
const minSheetHeight = 50;
// allow very short sheet e.g 10 to increase to 50 and
// very long to clamp withing availablle space;
let newSheetHeight = Math.max(
minSheetHeight,
Math.min(sheetHeight, fiftyPercent)
);
if (sheetIsOverlayed) newSheetHeight += keyboardHeight;
heightAnimationDriver(newSheetHeight, 400).start();
});
}
}
);
keyboardHideSubscription.current = Keyboard.addListener(
'keyboardDidHide',
(_) => {
if (sheetOpen) heightAnimationDriver(sheetHeight, 200).start();
}
);
return unsubscribe;
}
return;
}, [
keyboardHandlingEnabled,
sheetHeight,
SCREEN_HEIGHT,
sheetOpen,
heightAnimationDriver,
contentWrapperRef,
]);
return keyboardHandlingEnabled
? {
removeKeyboardListeners: unsubscribe,
}
: null;
}; | /**
* Handles keyboard pop out by adjusting sheet's layout when a `TextInput` within
* the sheet receives focus.
*
* @param {boolean} keyboardHandlingEnabled Determines whether this hook will go on to handle keyboard
* @param {number} sheetHeight Initial sheet's height before keyboard pop out
* @param {boolean} sheetOpen Indicates whether the sheet is open or closed
* @param {HeightAnimationDriver} heightAnimationDriver Animator function to be called with new
* sheet height when keyboard is out so it can adjust the sheet height with animation
* @param {React.MutableRefObject<View>} contentWrapperRef Reference to the content wrapper view
* @return {{removeKeyboardListeners:Function;} | null} An Object with an unsubscriber function or `null`
* when `keyboardHandlingEnabled` is false
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/hooks/useHandleKeyboardEvents/index.ts#L23-L101 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | convertHeight | const convertHeight = (
height: string | number,
containerHeight: number,
handleBarHidden: boolean
): number => {
const SCREEN_HEIGHT = Dimensions.get('window').height;
let _height = height;
const errorMsg = 'Invalid `height` prop';
if (typeof height === 'number') {
// normalise height
if (height < 0) _height = 0;
if (height >= containerHeight) {
if (containerHeight === SCREEN_HEIGHT && !handleBarHidden) {
_height = containerHeight - DEFAULT_HANDLE_BAR_DEFAULT_HEIGHT;
} else _height = containerHeight;
}
} else if (typeof height === 'string') {
const lastPercentIdx = height.lastIndexOf('%');
// perform checks
if (!height.endsWith('%') || height.length <= 1 || height.length > 4)
throw errorMsg;
let parsedHeight = Math.abs(
parseInt(height.substring(0, lastPercentIdx), 10)
);
if (isNaN(parsedHeight)) throw errorMsg;
// normalise height
if (parsedHeight >= 100) {
parsedHeight = 100;
}
_height = Math.floor((parsedHeight / 100) * containerHeight);
if (containerHeight === SCREEN_HEIGHT && !handleBarHidden) {
_height -= DEFAULT_HANDLE_BAR_DEFAULT_HEIGHT;
}
} else throw errorMsg;
return _height as number;
}; | /**
* converts string `height` from percentage e.g `'50%'` to pixel unit e.g `320` relative to `containerHeight`,
* or also clamps it to not exceed `containerHeight` if it's a number.
*
* _Note: When `height` > `containerHeight` and `containerHeight` === `SCREEN_HEIGHT`, and handle
* bar is visible, we want to set `height` to `SCREEN_HEIGHT`
* but deducting the height of handle bar so it's still visible._
* @param {string | number} height height in number percentage string
* @param {number} containerHeight height to convert and clamp relative to
* @param {boolean} handleBarHidden Used to determine how height clamping is done
* @returns {number} converted height
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/utils/convertHeight.ts#L16-L55 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | normalizeHeight | const normalizeHeight = (height?: number | string): number => {
const DEVICE_SCREEN_HEIGHT = Dimensions.get('window').height;
let clampedHeight = DEVICE_SCREEN_HEIGHT;
if (typeof height === 'number')
clampedHeight =
height < 0
? 0
: height > DEVICE_SCREEN_HEIGHT
? DEVICE_SCREEN_HEIGHT
: height;
return clampedHeight;
}; | /**
* Normalizes height to a number and clamps it
* so it's not bigger that device screen height
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/utils/normalizeHeight.ts#L7-L18 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
react-native-bottom-sheet | github_2023 | stanleyugwu | typescript | separatePaddingStyles | const separatePaddingStyles = (
style: SheetStyleProp | undefined
): Styles | undefined => {
if (!style) return;
const styleKeys = Object.keys(style || {});
if (!styleKeys.length) return;
const styles: Styles = {
paddingStyles: {},
otherStyles: {},
};
for (const key of styleKeys) {
// @ts-ignore
styles[key.startsWith('padding') ? 'paddingStyles' : 'otherStyles'][key] =
// @ts-ignore
style[key];
}
return styles;
}; | /**
* Extracts and separates `padding` styles from
* other styles from the given `style`
*/ | https://github.com/stanleyugwu/react-native-bottom-sheet/blob/65f1c49bcc59732346aa17356e962dec9c8ba45b/src/utils/separatePaddingStyles.ts#L23-L43 | 65f1c49bcc59732346aa17356e962dec9c8ba45b |
openllmetry-js | github_2023 | traceloop | typescript | main | const main = async () => {
traceloop.initialize({
appName: "sample_sampler",
apiKey: process.env.TRACELOOP_API_KEY,
disableBatch: true,
traceloopSyncEnabled: false,
exporter: new ConsoleSpanExporter(),
});
trace
.getTracer("traceloop.tracer")
.startActiveSpan(
"test-span",
{ attributes: { "next.span_name": "anything" } },
context.active(),
async (span: Span) => {
span.end();
},
);
}; | // No spans should be printed to the console when this file runs (it should be filtered out by the sampler) | https://github.com/traceloop/openllmetry-js/blob/485ab84e0db44223854fa858d0439d6d2408c2e2/packages/sample-app/src/sample_sampler.ts#L9-L28 | 485ab84e0db44223854fa858d0439d6d2408c2e2 |
openllmetry-js | github_2023 | traceloop | typescript | callPredictForChat | async function callPredictForChat(
publisher = "google",
model = "chat-bison@001",
) {
// Configure the parent resource
const endpoint = `projects/${project}/locations/${location}/publishers/${publisher}/models/${model}`;
const prompt = {
context:
"My name is Miles. You are an astronomer, knowledgeable about the solar system.",
examples: [
{
input: { content: "How many moons does Mars have?" },
output: {
content: "The planet Mars has two moons, Phobos and Deimos.",
},
},
],
messages: [
{
author: "user",
content: "How many planets are there in the solar system?",
},
],
};
const instanceValue = helpers.toValue(prompt);
const instances = [instanceValue] as google.protobuf.IValue[];
const parameter = {
temperature: 0.2,
maxOutputTokens: 256,
topP: 0.95,
topK: 40,
};
const parameters = helpers.toValue(parameter);
const request = {
endpoint,
instances,
parameters,
};
const [response] = await predictionServiceClient.predict(request);
const predictions = response.predictions;
if (predictions?.length)
for (const prediction of predictions) {
console.log(
JSON.stringify(
prediction.structValue?.fields?.candidates.listValue?.values?.[0]
?.structValue?.fields?.content.stringValue,
),
);
}
} | // Doesn't work currently: | https://github.com/traceloop/openllmetry-js/blob/485ab84e0db44223854fa858d0439d6d2408c2e2/packages/sample-app/src/vertexai/palm2.ts#L97-L150 | 485ab84e0db44223854fa858d0439d6d2408c2e2 |
openllmetry-js | github_2023 | traceloop | typescript | TraceloopClient.constructor | constructor(options: TraceloopClientOptions) {
this.apiKey = options.apiKey;
this.appName = options.appName;
this.baseUrl =
options.baseUrl ||
process.env.TRACELOOP_BASE_URL ||
"https://api.traceloop.com";
} | /**
* Creates a new instance of the TraceloopClient.
*
* @param options - Configuration options for the client
*/ | https://github.com/traceloop/openllmetry-js/blob/485ab84e0db44223854fa858d0439d6d2408c2e2/packages/traceloop-sdk/src/lib/client/traceloop-client.ts#L29-L36 | 485ab84e0db44223854fa858d0439d6d2408c2e2 |
openllmetry-js | github_2023 | traceloop | typescript | BaseAnnotation.create | async create(options: AnnotationCreateOptions) {
return await this.client.post(
`/v2/annotation-tasks/${options.annotationTask}/annotations`,
{
entity_instance_id: options.entity.id,
tags: options.tags,
source: "sdk",
flow: this.flow,
actor: {
type: "service",
id: this.client.appName,
},
},
);
} | /**
* Creates a new annotation.
*
* @param options - The annotation creation options
* @returns Promise resolving to the fetch Response
*/ | https://github.com/traceloop/openllmetry-js/blob/485ab84e0db44223854fa858d0439d6d2408c2e2/packages/traceloop-sdk/src/lib/client/annotation/base-annotation.ts#L22-L36 | 485ab84e0db44223854fa858d0439d6d2408c2e2 |
openllmetry-js | github_2023 | traceloop | typescript | UserFeedback.create | override async create(options: AnnotationCreateOptions) {
return await super.create(options);
} | /**
* Creates a new annotation for a specific task and entity.
*
* @param options - The options for creating an annotation
* @returns Promise resolving to the fetch Response
*
* @example
* ```typescript
* await client.annotation.create({
* annotationTask: 'sample-annotation-task',
* entity: {
* id: '123456',
* },
* tags: {
* sentiment: 'positive',
* score: 0.85,
* tones: ['happy', 'surprised']
* }
* });
* ```
*/ | https://github.com/traceloop/openllmetry-js/blob/485ab84e0db44223854fa858d0439d6d2408c2e2/packages/traceloop-sdk/src/lib/client/annotation/user-feedback.ts#L34-L36 | 485ab84e0db44223854fa858d0439d6d2408c2e2 |
spark | github_2023 | dataflint | typescript | MixpanelService.StartKeepAlive | static StartKeepAlive(interval: number): void {
if (!this.ShouldTrack) return;
setInterval(() => {
if (document.hidden) {
// skip keep alive when tab is not in focus
return;
}
this.Track(MixpanelEvents.KeepAlive, baseProperties);
}, interval);
} | /**
* Sends keep alive every interval if the tab is focused, in order to keep the mixpanel sessions "alive"
* @param interval keep alive interval in ms
*/ | https://github.com/dataflint/spark/blob/9b8809d84b643fb9c60f48e8b4b531ebf1cbfa21/spark-ui/src/services/MixpanelService.tsx#L37-L48 | 9b8809d84b643fb9c60f48e8b4b531ebf1cbfa21 |
moquerie | github_2023 | Akryum | typescript | fetchFactory | async function fetchFactory(id: string) {
const factory = SuperJSON.parse<ResourceFactory>(await $fetch(`/api/factories/${id}`))
// Update in query cache
const item = factories.value.find(i => i.id === id)
if (item) {
Object.assign(item, factory)
}
return factory
} | // Fetch one | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/factory.ts#L26-L36 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | updateInstance | async function updateInstance(options: UpdateInstanceOptions) {
const result = await $fetch(`/api/resources/instances/${options.resourceName}/${options.instanceId}`, {
method: 'PATCH',
body: options.data,
})
const data = SuperJSON.parse(result as string) as ResourceInstance
if (options.refetchAll) {
refreshInstances()
refreshInstance()
}
else {
updateInList(data)
}
instance.value = data
return data
} | // Update instance | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/resourceInstance.ts#L106-L121 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | duplicateInstances | async function duplicateInstances(resourceName: string, ids: string[]) {
const result = SuperJSON.parse(await $fetch(`/api/resources/instances/${resourceName}/duplicate`, {
method: 'POST',
body: {
ids,
},
})) as ResourceInstance[]
refreshInstances()
return result
} | // Duplicate instance | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/resourceInstance.ts#L137-L146 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | deleteInstances | async function deleteInstances(resourceName: string, ids: string[]) {
await $fetch(`/api/resources/instances/${resourceName}/bulk`, {
method: 'DELETE',
body: {
ids,
},
})
await refreshInstances()
} | // Delete instances | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/resourceInstance.ts#L150-L158 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | wait | async function wait() {
await fetchQuery
} | /**
* Wait for resource types to be loaded.
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/resourceType.ts#L46-L48 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | deleteSnapshot | async function deleteSnapshot(id: string) {
await $fetch(`/api/snapshots/${id}`, {
// @ts-expect-error Nuxt types issue
method: 'DELETE',
})
await refreshSnapshots()
} | // Delete | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/app/stores/snapshot.ts#L62-L68 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | onContextChange | async function onContextChange() {
const context = await getContext(mq)
Object.assign(context, await getContextRelatedToConfig(mq))
// Reset resolved context timer so it's re-evaluated
mq.data.resolvedContextTime = 0
} | // Context change | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/context.ts#L91-L96 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | getVariableName | function getVariableName(match: RegExp) {
const variable = variables?.find(({ cleanName }) => cleanName.match(match))
if (variable) {
selectedVariables.push(variable.name)
return `item.${variable.name}`
}
} | /**
* Get the first variable that match the given regex to find related variables.
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/factory/fakerAutoSelect.ts#L45-L51 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | generateObjectParamsCode | function generateObjectParamsCode(params: Record<string, any>): string | undefined {
const validParams: { key: string, value: any }[] = []
for (const key in params) {
const value = params[key]
if (value) {
validParams.push({ key, value })
}
}
if (validParams.length === 0) {
return undefined
}
return `{${validParams.map(({ key, value }) => `${key}: ${value}`).join(', ')}}`
} | /**
* Generate a string of object params code, for example: `{ key1: value1, key2: value2 }`
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/factory/fakerAutoSelect.ts#L236-L248 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | getRepoMetaFactoryStorage | async function getRepoMetaFactoryStorage(mq: MoquerieInstance) {
if (metaStorage) {
return metaStorage
}
if (metaStoragePromise) {
return metaStoragePromise
}
metaStoragePromise = useStorage(mq, {
path: 'factories-repo-meta',
format: 'json',
location: 'local',
})
metaStorage = await metaStoragePromise
return metaStorage
} | /**
* Store metadata about factories stored in the repository that is not explicitly stored in the factory files.
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/factory/storage.ts#L144-L158 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | MockFileHandler.add | add(file: string, data: any) {
// @TODO: Implement
} | // eslint-disable-next-line unused-imports/no-unused-vars | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/mock/mockFileHandler.ts#L25-L27 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | deserializeInstanceValue | async function deserializeInstanceValue<TData>(
mq: MoquerieInstance,
instance: ResourceInstance,
deserializeContext: DeserializeContext = {
store: new Map(),
instancesCache: new Map(),
instancesByIdCache: new Map(),
},
): Promise<TData> {
// Cache
const storeKey = `${instance.resourceName}:${instance.id}`
if (deserializeContext.store.has(storeKey)) {
return deserializeContext.store.get(storeKey) as TData
}
// Resource type
const ctx = await mq.getResolvedContext()
const resourceType = ctx.schema.types[instance.resourceName]
if (resourceType == null) {
throw new Error(`Resource type "${instance.resourceName}" not found`)
}
/**
* Final object returned in the API.
*/
const result = {
__typename: instance.resourceName,
} as Record<string, any>
// Cache
deserializeContext.store.set(storeKey, result)
for (const key in resourceType.fields) {
const field = resourceType.fields[key]
const value = instance.value[key]
if (field.type === 'resource') {
const fieldResourceType = ctx.schema.types[field.resourceName]
if (fieldResourceType.inline) {
result[key] = value
}
else {
const refs = (Array.isArray(value) ? value : [value]).filter(Boolean) as ResourceInstanceReference[]
if (field.array) {
// Get final objects for referenced instances
result[key] = (await Promise.all(refs.map(async (ref) => {
// Get maps of (only) active instances by id
const instancesById = await getInstancesByIdMapCached(mq, deserializeContext.instancesCache, deserializeContext.instancesByIdCache, ref.__resourceName)
const instance = instancesById.get(ref.__id)
if (!instance) {
return null
}
return deserializeInstanceValue(mq, instance, deserializeContext)
}))).filter(Boolean)
}
else {
let refInstance: ResourceInstance | null = null
// We pick the first active referenced instance
for (const ref of refs) {
// Get maps of (only) active instances by id
const instancesById = await getInstancesByIdMapCached(mq, deserializeContext.instancesCache, deserializeContext.instancesByIdCache, ref.__resourceName)
const instance = instancesById.get(ref.__id)
if (instance) {
refInstance = instance
break
}
}
if (refInstance) {
// Get final object for referenced instance
result[key] = await deserializeInstanceValue(mq, refInstance, deserializeContext)
}
else {
result[key] = null
}
}
}
}
else {
result[key] = value
}
}
addInstanceValueTag(result, instance.resourceName, instance.id)
return result as TData
} | /**
* Create final object from resource instance, included referenced resources.
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/resource/queryManager.ts#L134-L225 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | getIdFromValue | function getIdFromValue(idFields: string[], data: any) {
return idFields.map(idField => data[idField]).filter(Boolean).join('|')
} | /* Serialize */ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/resource/queryManager.ts#L229-L231 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | serializeInstanceValue | async function serializeInstanceValue<TType extends ResourceSchemaType>(
mq: MoquerieInstance,
resourceName: string,
valueId: string | null,
data: ResourceInstanceValue<TType> | null,
serializeContext: SerializeContext = {
store: new Map(),
instancesCache: new Map(),
},
createOptions: QueryManagerCreateInstanceOptions = {},
): Promise<ResourceInstanceReference | null> {
if (typeof data !== 'object') {
return null
}
if (isResourceInstanceReference(data)) {
return data
}
// Resource type
const ctx = await mq.getResolvedContext()
const resourceType = ctx.schema.types[resourceName]
if (resourceType == null) {
throw new Error(`Resource type "${resourceName}" not found`)
}
const dataAsObject = data as Record<string, any>
// Id
const idFields = resourceType.idFields ?? ['id', '_id']
const getValueId = getIdFromValue.bind(null, idFields)
if (!valueId) {
valueId = getValueId(data)
}
// Search for existing active instance
const instances = await getInstancesCached(mq, serializeContext.instancesCache, resourceName)
let instance = valueId ? instances.find(i => getValueId(i.value) === valueId) : instances[0]
const getStoreKey = (resourceName: string, id: string) => `${resourceName}:${id}`
if (instance) {
// Already cached
const storeKey = getStoreKey(instance.resourceName, instance.id)
if (serializeContext.store.has(storeKey)) {
return serializeContext.store.get(storeKey)!
}
}
if (data == null) {
return instance ? createResourceInstanceReference(instance.resourceName, instance.id) : null
}
const ref = createResourceInstanceReference(resourceName, instance?.id ?? createOptions.id ?? nanoid())
const storeKey = getStoreKey(ref.__resourceName, ref.__id)
serializeContext.store.set(storeKey, ref)
/**
* Value stored in the database.
*/
const resultValue = {} as Record<string, any>
for (const key in resourceType.fields) {
const field = resourceType.fields[key]
const value = dataAsObject[key] === undefined ? instance?.value[key] : dataAsObject[key]
if (field.type === 'resource') {
const instanceValues = (value == null ? [] : Array.isArray(value) ? value : [value]).filter(Boolean) as Array<string | Record<string, any>>
const fieldResourceType = ctx.schema.types[field.resourceName]
async function processChild(field: ResourceSchemaField & { type: 'resource' }, v: any) {
let r: ResourceInstanceReference | null
if (typeof v === 'string') {
// Just an id
if (fieldResourceType.implementations) {
throw new Error(`Error saving ${v}: Cannot reference interface type "${field.resourceName}" as an object with a __typename property is needed`)
}
r = await serializeInstanceValue(mq, field.resourceName, v, null, serializeContext)
}
else {
let childResourceName = field.resourceName
if (fieldResourceType.implementations) {
if (!v.__typename) {
throw new Error(`Error saving ${JSON.stringify(v)}: Cannot reference interface type "${field.resourceName}" as an object with a __typename property is needed`)
}
childResourceName = v.__typename
}
// An object
r = await serializeInstanceValue(mq, childResourceName, null, v as any, serializeContext)
}
return r
}
if (fieldResourceType.inline) {
if (field.array) {
resultValue[key] = instanceValues.filter(Boolean)
}
else {
resultValue[key] = value
}
}
else {
// Process and save referenced object into database
const refValues = await Promise.all(instanceValues.map(v => processChild(field, v)))
// Put resource instance references on current object
resultValue[key] = refValues.filter(Boolean)
}
}
else {
resultValue[key] = value
}
}
if (instance) {
instance = await updateResourceInstanceById(mq, resourceName, instance.id, { value: resultValue })
}
else {
instance = await createResourceInstance(mq, {
...createOptions,
id: ref.__id,
resourceName,
value: resultValue,
tags: !createOptions
? [
'auto-created',
]
: [],
save: true,
})
}
return ref
} | /**
* Create or update referenced resource instances.
* @param resourceName Name of the resource type.
* @param valueId Id of object, should correspond to the idFields of the resource type.
* @param data Object to serialize.
* @param serializeContext Context used to prevent infinite recursion.
* @param createOptions Options used to create the resource instance.
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/resource/queryManager.ts#L249-L381 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | getReference | function getReference(instanceId: string): ResourceInstanceReference {
return createResourceInstanceReference(options.resourceName, instanceId)
} | /* Reference manager */ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/resource/queryManager.ts#L523-L525 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | destroyAllStorage | function destroyAllStorage(mq: MoquerieInstance) {
for (const s of mq.data.resourceStorages.storage.values()) {
s.destroy()
}
mq.data.resourceStorages.storage.clear()
mq.data.resourceStorages.storagePromise.clear()
} | // Branch support | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/resource/storage.ts#L39-L45 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | predicate | const predicate = (data: any) => {
// Text search
if (query.__search != null) {
const search = query.__search.toLowerCase()
for (const key in data) {
if (key.match(/^(id|_id|slug)$/)) {
continue
}
const value = get(data, key)
if (typeof value === 'string' && value.toLowerCase().includes(search)) {
return true
}
}
return false
}
for (const key in query) {
if (key.startsWith('__')) {
continue
}
// eslint-disable-next-line eqeqeq
if (get(data, key) != query[key]) {
return false
}
}
return true
} | // Query filters | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/rest/server.ts#L214-L240 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | findAll | async function findAll(): Promise<TData[]> {
if (options.lazyLoading) {
throw new Error('findAll() is not supported with lazyLoading')
}
return data
} | // Data access | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L322-L327 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | findById | async function findById(id: string): Promise<TData | undefined> {
if (options.lazyLoading) {
const file = manifest.files[id]
return readFile(id, file)
}
return data.find(item => item.id === id)
} | /**
* Return item by id
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L332-L338 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | save | async function save(item: TData) {
const index = data.findIndex(i => i.id === item.id)
if (index === -1) {
data.push(item)
}
else {
data[index] = item
}
if (mq.data.skipWrites) {
return
}
// Deduplicate filenames
let filename = getFilename(item)
if (options.deduplicateFiles !== false) {
const ext = path.extname(filename)
const files = Object.values(manifest.files)
let testCount = 0
let testFilename = filename
while (files.includes(testFilename)) {
testCount++
testFilename = filename.replace(ext, `-${testCount}${ext}`)
}
if (testCount > 0) {
filename = testFilename
}
}
manifest.files[item.id] = filename
queueWriteFile(item)
queueWriteManifest()
} | /**
* Add or update an item
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L343-L376 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | remove | async function remove(id: string) {
const index = data.findIndex(i => i.id === id)
if (index !== -1) {
data.splice(index, 1)
if (mq.data.skipWrites) {
return
}
const file = manifest.files[id]
if (file) {
removeFile(file)
delete manifest.files[id]
queueWriteManifest()
}
}
} | /**
* Remove an item
*/ | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L381-L396 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | load | async function load() {
const newData: TData[] = []
if (!options.lazyLoading) {
const promises = []
for (const id in manifest.files) {
promises.push((async () => {
const file = manifest.files[id]
try {
const item = await readFile(id, file)
newData.push(item)
if (writeQueue.busy) {
throw new Error('Write queue is busy, aborting load')
}
}
catch (e) {
console.error(e)
}
})())
}
await Promise.all(promises)
}
// Only update data if no write is pending
if (!writeQueue.busy) {
data.length = 0
data.push(...newData)
}
} | // Load | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L400-L428 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
moquerie | github_2023 | Akryum | typescript | destroy | function destroy() {
clearInterval(refreshInterval)
queueWriteManifest()
data.length = 0
} | // Cleanup | https://github.com/Akryum/moquerie/blob/44c70037d22a77dcc17b1c7ab4996d1d7831fe5a/packages/core/src/storage/storage.ts#L434-L438 | 44c70037d22a77dcc17b1c7ab4996d1d7831fe5a |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | createStack | function createStack(stack: typeof BaseStack, props?: BaseStackProps, isUseCase?: boolean) {
const instance = new stack(app, stack.name, props ?? getDefaultBaseStackProps(stack, isUseCase));
cdk.Aspects.of(instance).add(
new AppRegistry(instance, 'AppRegistry', {
solutionID: solutionID,
solutionVersion: version,
solutionName: solutionName,
applicationType: applicationType,
applicationName: isUseCase
? `${applicationName}-${cdk.Fn.ref('UseCaseUUID')}`
: `${applicationName}-Dashboard`
})
);
// adding lambda layer to all lambda functions for injecting user-agent for SDK calls to AWS services.
cdk.Aspects.of(instance).add(
new LambdaAspects(instance, 'AspectInject', {
solutionID: solutionID,
solutionVersion: version
})
);
} | /**
* Method to instantiate a stack
*
* @param stack
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/bin/gen-ai-app-builder.ts#L47-L69 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | getDefaultBaseStackProps | function getDefaultBaseStackProps(stack: typeof BaseStack, isUseCase?: boolean): BaseStackProps {
return {
description: isUseCase
? `(${solutionID})-${stack.name} - ${solutionName} - ${stack.name} - Version ${version}`
: `(${solutionID}) - ${solutionName} - ${stack.name} - Version ${version}`,
synthesizer: new cdk.DefaultStackSynthesizer({
generateBootstrapVersionRule: false
}),
solutionID: solutionID,
solutionVersion: version,
solutionName: `${solutionName}`,
applicationTrademarkName: applicationTrademarkName,
...(isUseCase && {
stackName: `${stack.name}-${crypto.randomUUID().substring(0, 8)}`
})
} as BaseStackProps;
} | /**
* Method that returns default base stack props.
*
* @param stack
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/bin/gen-ai-app-builder.ts#L77-L93 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | BedrockAgent.getWebSocketRoutes | protected getWebSocketRoutes(): Map<string, lambda.Function> {
return new Map().set('invokeAgent', this.chatLlmProviderLambda);
} | /**
* setting websocket route for agent stack
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/bedrock-agent-stack.ts#L80-L82 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | BedrockAgent.withAdditionalResourceSetup | protected withAdditionalResourceSetup(props: BaseStackProps): void {
super.withAdditionalResourceSetup(props);
this.setLlmProviderPermissions();
} | /**
* method to provision additional resources required for agent stack
*
* @param props
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/bedrock-agent-stack.ts#L89-L92 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | BedrockChat.llmProviderSetup | public llmProviderSetup(): void {
// the log retention custom resource is setup in the use-case-stack.ts
const lambdaRole = createDefaultLambdaRole(this, 'ChatLlmProviderLambdaRole', this.deployVpcCondition);
this.chatLlmProviderLambda = new lambda.Function(this, 'ChatLlmProviderLambda', {
code: lambda.Code.fromAsset(
'../lambda/chat',
ApplicationAssetBundler.assetBundlerFactory()
.assetOptions(CHAT_LAMBDA_PYTHON_RUNTIME)
.options(this, '../lambda/chat', {
platform: PYTHON_PIP_BUILD_PLATFORM,
pythonVersion: PYTHON_VERSION,
implementation: PYTHON_PIP_WHEEL_IMPLEMENTATION
})
),
role: lambdaRole,
runtime: LANGCHAIN_LAMBDA_PYTHON_RUNTIME,
handler: 'bedrock_handler.lambda_handler',
timeout: cdk.Duration.minutes(LAMBDA_TIMEOUT_MINS),
memorySize: 256,
environment: {
POWERTOOLS_SERVICE_NAME: 'BEDROCK_CHAT'
},
description: 'Lambda serving the websocket based API for Bedrock chat'
});
const cfnFunction = this.chatLlmProviderLambda.node.defaultChild as lambda.CfnFunction;
cfnFunction.addMetadata(
ADDITIONAL_LLM_LIBRARIES,
[LLM_LIBRARY_LAYER_TYPES.LANGCHAIN_LIB_LAYER, LLM_LIBRARY_LAYER_TYPES.BOTO3_LIB_LAYER].join(',')
);
this.withInferenceProfileSetup();
this.chatLlmProviderLambda.addToRolePolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream'],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${cdk.Aws.REGION}::foundation-model/*`,
`arn:${cdk.Aws.PARTITION}:bedrock:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:provisioned-model/*`
]
})
);
this.chatLlmProviderLambda.addToRolePolicy(
new cdk.aws_iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['bedrock:ApplyGuardrail'],
resources: [`arn:${cdk.Aws.PARTITION}:bedrock:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:guardrail/*`]
})
);
NagSuppressions.addResourceSuppressions(
this.chatLlmProviderLambda.role!.node.tryFindChild('DefaultPolicy') as iam.Policy,
[
{
id: 'AwsSolutions-IAM5',
reason: 'This lambda is granted permissions to invoke any bedrock model, which requires the *.',
appliesTo: [
'Resource::arn:<AWS::Partition>:bedrock:<AWS::Region>::foundation-model/*',
'Resource::arn:<AWS::Partition>:bedrock:<AWS::Region>:<AWS::AccountId>:guardrail/*',
'Resource::arn:<AWS::Partition>:bedrock:<AWS::Region>:<AWS::AccountId>:provisioned-model/*',
'Resource::*'
]
}
]
);
} | /**
* Provisions the llm provider lambda, and sets it to member variable chatLlmProviderLambda
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/bedrock-chat-stack.ts#L65-L132 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | SageMakerChat.llmProviderSetup | public llmProviderSetup(): void {
// the log retention custom resource is setup in the use-case-stack.ts
this.chatLlmProviderLambda = new lambda.Function(this, 'ChatLlmProviderLambda', {
code: lambda.Code.fromAsset(
'../lambda/chat',
ApplicationAssetBundler.assetBundlerFactory()
.assetOptions(CHAT_LAMBDA_PYTHON_RUNTIME)
.options(this, '../lambda/chat', {
platform: PYTHON_PIP_BUILD_PLATFORM,
pythonVersion: PYTHON_VERSION,
implementation: PYTHON_PIP_WHEEL_IMPLEMENTATION
})
),
role: createDefaultLambdaRole(this, 'ChatLlmProviderLambdaRole', this.deployVpcCondition),
runtime: LANGCHAIN_LAMBDA_PYTHON_RUNTIME,
handler: 'sagemaker_handler.lambda_handler',
timeout: cdk.Duration.minutes(LAMBDA_TIMEOUT_MINS),
memorySize: 256,
environment: {
POWERTOOLS_SERVICE_NAME: 'SAGEMAKER_CHAT'
},
description: 'Lambda serving the websocket based API for SageMaker chat'
});
const cfnFunction = this.chatLlmProviderLambda.node.defaultChild as lambda.CfnFunction;
cfnFunction.addMetadata(
ADDITIONAL_LLM_LIBRARIES,
[LLM_LIBRARY_LAYER_TYPES.LANGCHAIN_LIB_LAYER, LLM_LIBRARY_LAYER_TYPES.BOTO3_LIB_LAYER].join(',')
);
this.chatLlmProviderLambda.addToRolePolicy(
new cdk.aws_iam.PolicyStatement({
actions: ['sagemaker:InvokeEndpoint', 'sagemaker:InvokeEndpointWithResponseStream'],
resources: [
`arn:${cdk.Aws.PARTITION}:sagemaker:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:endpoint/*`,
`arn:${cdk.Aws.PARTITION}:sagemaker:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:inference-component/*`
]
})
);
NagSuppressions.addResourceSuppressions(
this.chatLlmProviderLambda.role!.node.tryFindChild('DefaultPolicy') as iam.Policy,
[
{
id: 'AwsSolutions-IAM5',
reason: 'This lambda is granted permissions to invoke any sagemaker endpoint in their account, which requires the *.',
appliesTo: [
'Resource::arn:<AWS::Partition>:sagemaker:<AWS::Region>:<AWS::AccountId>:endpoint/*',
'Resource::arn:<AWS::Partition>:sagemaker:<AWS::Region>:<AWS::AccountId>:inference-component/*'
]
}
]
);
} | /**
* Provisions the llm provider lambda, and sets it to member variable chatLlmProviderLambda
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/sagemaker-chat-stack.ts#L63-L117 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.configureGatewayResponses | private configureGatewayResponses(restApi: api.RestApi) {
new api.GatewayResponse(this, 'BadRequestDefaultResponse', {
restApi: restApi,
type: api.ResponseType.DEFAULT_4XX,
responseHeaders: {
'gatewayresponse.header.Access-Control-Allow-Origin': "'*'",
'gatewayresponse.header.Access-Control-Allow-Headers': "'*'"
}
});
new api.GatewayResponse(this, 'InternalServerErrorDefaultResponse', {
restApi: restApi,
type: api.ResponseType.DEFAULT_5XX,
statusCode: '400',
responseHeaders: {
'gatewayresponse.header.Access-Control-Allow-Origin': "'*'",
'gatewayresponse.header.Access-Control-Allow-Headers': "'*'"
}
});
// templates provide useful info about requests which fail validation
new api.GatewayResponse(this, 'BadRequestBodyResponse', {
restApi: restApi,
type: api.ResponseType.BAD_REQUEST_BODY,
statusCode: '400',
responseHeaders: {
'gatewayresponse.header.Access-Control-Allow-Origin': "'*'",
'gatewayresponse.header.Access-Control-Allow-Headers': "'*'"
},
templates: {
'application/json':
'{"error":{"message":"$context.error.messageString","errors":"$context.error.validationErrorString"}}'
}
});
new api.GatewayResponse(this, 'BadRequestParametersResponse', {
restApi: restApi,
type: api.ResponseType.BAD_REQUEST_PARAMETERS,
statusCode: '400',
responseHeaders: {
'gatewayresponse.header.Access-Control-Allow-Origin': "'*'",
'gatewayresponse.header.Access-Control-Allow-Headers': "'*'"
},
templates: {
'application/json':
'{"error":{"message":"$context.error.messageString","errors":"$context.error.validationErrorString"}}'
}
});
} | /**
* Configure all 4XX and 5XX responses to have CORS headers
* @param restApi
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L206-L254 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.createUseCaseManagementApi | private createUseCaseManagementApi(
props: DeploymentPlatformRestEndpointProps,
apiRoot: cdk.aws_apigateway.IResource,
requestValidator: cdk.aws_apigateway.RequestValidator,
restApi: api.RestApi
) {
const useCaseManagementAPILambdaIntegration = new api.LambdaIntegration(props.useCaseManagementAPILambda, {
passthroughBehavior: api.PassthroughBehavior.NEVER
});
// Paths for the deployment api
const deploymentsResource = apiRoot.addResource('deployments'); // for getting and creating deployments
const deploymentResource = deploymentsResource.addResource('{useCaseId}'); // for updating/deleting specific a specific deployment
deploymentsResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['POST', 'GET', 'OPTIONS']
});
// Listing info about existing use cases
deploymentsResource.addMethod('GET', useCaseManagementAPILambdaIntegration, {
operationName: 'GetUseCases',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.querystring.pageNumber': true,
'method.request.querystring.searchFilter': false,
'method.request.header.authorization': true
}
});
// Deploying a new use case
deploymentsResource.addMethod('POST', useCaseManagementAPILambdaIntegration, {
operationName: 'DeployUseCase',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
},
requestModels: {
'application/json': new api.Model(this, 'DeployUseCaseApiBodyModel', {
restApi: restApi,
contentType: 'application/json',
description: 'Defines the required JSON structure of the POST request to deploy a use case',
modelName: 'DeployUseCaseApiBodyModel',
schema: deployUseCaseBodySchema
})
},
methodResponses: [
{
responseModels: {
'application/json': new api.Model(this, 'DeployUseCaseResponseModel', {
restApi: restApi,
contentType: 'application/json',
description: 'Response model to describe response of deploying a use case',
modelName: 'DeployUseCaseResponseModel',
schema: deployUseCaseResponseSchema
})
},
statusCode: '200'
}
]
});
deploymentResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['PATCH', 'DELETE', 'OPTIONS']
});
// Updating an existing use case deployment (i.e. changing its configuration)
deploymentResource.addMethod('PATCH', useCaseManagementAPILambdaIntegration, {
operationName: 'UpdateUseCase',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
},
requestModels: {
'application/json': new api.Model(this, 'UpdateUseCaseApiBodyModel', {
restApi: restApi,
contentType: 'application/json',
description: 'Defines the required JSON structure of the PUT request to update a use case',
modelName: 'UpdateUseCaseApiBodyModel',
schema: updateUseCaseBodySchema
})
},
methodResponses: [
{
responseModels: {
'application/json': new api.Model(this, 'UpdateUseCaseResponseModel', {
restApi: restApi,
contentType: 'application/json',
description: 'Response model to describe response of updating a use case',
modelName: 'UpdateUseCaseResponseModel',
schema: updateUseCaseResponseSchema
})
},
statusCode: '200'
}
]
});
// deleting (destroying) a deployed use case
deploymentResource.addMethod('DELETE', useCaseManagementAPILambdaIntegration, {
operationName: 'DeleteUseCase',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestParameters: {
'method.request.querystring.permanent': false,
'method.request.header.authorization': true
}
});
} | /**
* Creates all API resources and methods for the use case management API
* @param props
* @param apiRoot
* @param requestValidator
* @param restApi
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L263-L380 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.createModelInfoApi | private createModelInfoApi(
props: DeploymentPlatformRestEndpointProps,
apiRoot: cdk.aws_apigateway.IResource,
requestValidator: cdk.aws_apigateway.RequestValidator
) {
const modelInfoLambdaIntegration = new api.LambdaIntegration(props.modelInfoApiLambda, {
passthroughBehavior: api.PassthroughBehavior.NEVER
});
const modelInfoResource = apiRoot.addResource('model-info');
// Listing the available use case types
const useCaseTypesResource = modelInfoResource.addResource('use-case-types');
useCaseTypesResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['GET', 'OPTIONS']
});
useCaseTypesResource.addMethod('GET', modelInfoLambdaIntegration, {
operationName: 'GetUseCaseTypes',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
}
});
// Listing available model providers for a given use case
const modelInfoByUseCaseResource = modelInfoResource.addResource('{useCaseType}');
const providersResource = modelInfoByUseCaseResource.addResource('providers');
providersResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['GET', 'OPTIONS']
});
providersResource.addMethod('GET', modelInfoLambdaIntegration, {
operationName: 'GetModelProviders',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
}
});
// Getting available models for a given provider/use case
const modelsResource = modelInfoByUseCaseResource.addResource('{providerName}');
modelsResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['GET', 'OPTIONS']
});
modelsResource.addMethod('GET', modelInfoLambdaIntegration, {
operationName: 'GetModels',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
}
});
// Getting model info for a given use case/provider/model
const specificModelInfoResource = modelsResource.addResource('{modelId}');
specificModelInfoResource.addCorsPreflight({
allowOrigins: ['*'],
allowHeaders: ['Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization'],
allowMethods: ['GET', 'OPTIONS']
});
specificModelInfoResource.addMethod('GET', modelInfoLambdaIntegration, {
operationName: 'GetModelInfo',
authorizer: props.deploymentPlatformAuthorizer,
authorizationType: api.AuthorizationType.CUSTOM,
requestValidator: requestValidator,
requestParameters: {
'method.request.header.authorization': true
}
});
} | /**
* Creates all API resources and methods for the use case management API
* @param props
* @param apiRoot
* @param requestValidator
* @param restApi
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L389-L475 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.defineBlockRequestHeadersRule | private defineBlockRequestHeadersRule(): CfnWebACL.RuleProperty {
return {
priority: this.getCustomRulePriority(),
name: 'Custom-BlockRequestHeaders',
action: {
block: {
customResponse: {
responseCode: INVALID_REQUEST_HEADER_RESPONSE_CODE,
customResponseBodyKey: HEADERS_NOT_ALLOWED_KEY
}
}
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'Custom-BlockRequestHeaders',
sampledRequestsEnabled: true
},
statement: {
sizeConstraintStatement: {
fieldToMatch: {
singleHeader: {
'Name': 'x-amzn-requestid'
}
},
comparisonOperator: 'GE',
size: 0,
textTransformations: [
{
type: 'NONE',
priority: 0
}
]
}
}
};
} | /**
* Define WAF rule for blocking any request that contains the `X-Amzn-Requestid` header
* @returns WAF rule
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L481-L516 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.defineBlockOversizedBodyNotInDeployRule | private defineBlockOversizedBodyNotInDeployRule(): CfnWebACL.RuleProperty {
return {
priority: this.getCustomRulePriority(),
name: 'Custom-BlockOversizedBodyNotInDeploy',
action: {
block: {}
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'Custom-BlockOversizedBodyNotInDeploy',
sampledRequestsEnabled: true
},
statement: {
andStatement: {
statements: [
{
labelMatchStatement: {
scope: 'LABEL',
key: 'awswaf:managed:aws:core-rule-set:SizeRestrictions_Body'
}
},
{
notStatement: {
statement: {
byteMatchStatement: {
searchString: '/deployments',
fieldToMatch: {
uriPath: {}
},
textTransformations: [
{
priority: 0,
type: 'NONE'
}
],
positionalConstraint: 'ENDS_WITH'
}
}
}
}
]
}
}
};
} | /**
* Define WAF rule which enforces the SizeRestrictions_Body rule from the core rule set for URIs not in the /deployments path
* @returns WAF rule
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L529-L573 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.defineAWSManagedRulesCommonRuleSetWithBodyOverride | private defineAWSManagedRulesCommonRuleSetWithBodyOverride(priority: number): CfnWebACL.RuleProperty {
return {
name: 'AWS-AWSManagedRulesCommonRuleSet',
priority: priority,
statement: {
managedRuleGroupStatement: {
vendorName: 'AWS',
name: 'AWSManagedRulesCommonRuleSet',
ruleActionOverrides: [
{
name: 'SizeRestrictions_BODY',
actionToUse: {
count: {}
}
}
]
}
},
overrideAction: {
none: {}
},
visibilityConfig: {
sampledRequestsEnabled: true,
cloudWatchMetricsEnabled: true,
metricName: 'AWS-AWSManagedRulesCommonRuleSet'
}
};
} | /**
* Defines a WAF rule which enforces the AWSManagedRulesCommonRuleSet, with an override to only count the SizeRestrictions_BODY.
* @param priority The priority of the rule
* @returns The WAF rule
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L580-L607 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | DeploymentPlatformRestEndpoint.getCustomRulePriority | private getCustomRulePriority(): number {
return this.rulePriorityCounter++;
} | /**
* Gets a unique priority for a custom rule, incrementing an internal counter
* @returns A unique priority for each custom rule
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/api/deployment-platform-rest-endpoint.ts#L613-L615 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.createPolicyTable | protected createPolicyTable() {
const table = new dynamodb.Table(this, 'CognitoGroupPolicyStore', {
encryption: dynamodb.TableEncryption.AWS_MANAGED,
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
partitionKey: {
name: DynamoDBAttributes.COGNITO_TABLE_PARTITION_KEY,
type: dynamodb.AttributeType.STRING
},
removalPolicy: cdk.RemovalPolicy.DESTROY
});
NagSuppressions.addResourceSuppressions(table, [
{
id: 'AwsSolutions-DDB3',
reason: 'Enabling point-in-time recovery is recommended in the implementation guide, but is not enforced'
}
]);
cfn_guard.addCfnSuppressRules(table, [
{
id: 'W77',
reason: 'Enabling point-in-time recovery is recommended in the implementation guide, but is not enforced'
},
{
id: 'W74',
reason: 'DynamoDB table is encrypted using AWS managed encryption'
},
{
id: 'W78',
reason: 'Point-in-time-recovery is not enabled by default, but is recommended in the implementation guide as a post-deployment step'
}
]);
return table;
} | /**
* Creates a new dynamodb table which stores policies that apply to the user group.
*
* @returns A newly created dynamodb table which stores policies that apply to the user group
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L225-L258 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.createUserPool | public createUserPool(props: UserPoolProps) {
const userPool = new cognito.UserPool(this, 'NewUserPool', {
userPoolName: `${cdk.Aws.STACK_NAME}-UserPool`,
selfSignUpEnabled: false,
userVerification: {
emailSubject: `Verify your email to continue using ${props.applicationTrademarkName}`,
emailBody: `Thank you for creating your profile on ${props.applicationTrademarkName}. Your verification code is {####}`,
emailStyle: cognito.VerificationEmailStyle.CODE,
smsMessage: `Thank you for creating your profile on ${props.applicationTrademarkName}! Your verification code is {####}`
},
signInAliases: {
username: true,
email: true
},
mfa: cognito.Mfa.OPTIONAL,
passwordPolicy: {
minLength: 12,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: true,
tempPasswordValidity: cdk.Duration.days(3)
},
removalPolicy: cdk.RemovalPolicy.DESTROY,
userInvitation: {
emailSubject: `Invitation to join ${props.applicationTrademarkName} app!`,
emailBody: `You have been invited to join ${props.applicationTrademarkName} app. Your temporary credentials are:</p> \
<p> \
Username: <strong>{username}</strong><br /> \
Password: <strong>{####}</strong> \
</p> \
<p>\
Please use this temporary password to sign in and change your password. \
Wait until the deployment has completed before accessing the website or api. \
</p> `
}
});
/**
* The below code should be uncommented by users to attach the lambda to map groups from an external idp to cognito.
* Cognito documentation reference - https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html
*
userPool.addTrigger(
cognito.UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG,
const preTokenGenLambda = new lambda.Function(this, 'PreTokenGenerationLambda', {
code: lambda.Code.fromAsset(
'../lambda/ext-idp-group-mapper',
ApplicationAssetBundler.assetBundlerFactory()
.assetOptions(COMMERCIAL_REGION_LAMBDA_PYTHON_RUNTIME)
.options(this, '../lambda/ext-idp-group-mapper')
),
handler: 'lambda_func.handler',
runtime: COMMERCIAL_REGION_LAMBDA_PYTHON_RUNTIME,
description: 'Lambda function to map external identity provider groups to cognito groups',
role: createDefaultLambdaRole(this, 'PreTokenGenerationLambdaRole')
});
createCustomResourceForLambdaLogRetention(
this,
'PreTokenGenLambdaLogRetention',
preTokenGenLambda.functionName,
props.customResourceLambdaArn
);
);
*/
(userPool.node.tryFindChild('Resource') as cognito.CfnUserPool).userPoolAddOns = {
advancedSecurityMode: 'ENFORCED'
};
NagSuppressions.addResourceSuppressions(userPool, [
{
id: 'AwsSolutions-COG2',
reason: 'To enable MFA and what should be used as MFA varies on business case, hence disabling it for customers to take a decision'
}
]);
cfn_guard.addCfnSuppressRules(
userPool.node.tryFindChild('smsRole')?.node.tryFindChild('Resource') as cdk.CfnResource,
[
{
id: 'F10',
reason: 'This role is generated by a CDK L2 construct'
}
]
);
cfn_guard.addCfnSuppressRules(userPool.node.tryFindChild('smsRole') as iam.CfnRole, [
{
id: 'W11',
reason: 'The policy is generated by a CDK L2 construct'
},
{
id: 'W12',
reason: 'The policy is generated by a CDK L2 construct'
},
{
id: 'W13',
reason: 'The policy is generated by a CDK L2 construct'
}
]);
return userPool;
} | /**
* Creates a new user pool.
*
* @param applicationTrademarkName Application name to be used in user verification emails
* @returns A newly created user pool
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L266-L369 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.createUserPoolDomain | public createUserPoolDomain(props: UserPoolProps) {
const domainPrefixNotProvidedCondition = new cdk.CfnCondition(this, 'DomainPrefixNotProvidedCondition', {
expression: cdk.Fn.conditionEquals(props.cognitoDomainPrefix, '')
});
const domainPrefixResource = new cdk.CustomResource(this, 'DomainPrefixResource', {
resourceType: 'Custom::CognitoDomainPrefix',
serviceToken: props.customResourceLambdaArn,
properties: {
Resource: 'GEN_DOMAIN_PREFIX',
STACK_NAME: cdk.Aws.STACK_NAME
}
});
(domainPrefixResource.node.defaultChild as cdk.CfnCustomResource).cfnOptions.condition =
domainPrefixNotProvidedCondition;
const domainPrefix = cdk.Fn.conditionIf(
domainPrefixNotProvidedCondition.logicalId,
domainPrefixResource.getAttString('DomainPrefix'),
props.cognitoDomainPrefix
).toString();
this.generatedUserPoolDomain = new cognito.UserPoolDomain(this, 'UserPoolDomain', {
userPool: this.userPool,
cognitoDomain: {
domainPrefix: domainPrefix
}
});
(this.generatedUserPoolDomain.node.defaultChild as cdk.CfnResource).cfnOptions.condition =
this.createUserPoolCondition;
const userPoolDomainName = cdk.Fn.conditionIf(
this.createUserPoolCondition.logicalId,
this.generatedUserPoolDomain.domainName,
props.cognitoDomainPrefix
).toString();
this.userPoolDomain = cognito.UserPoolDomain.fromDomainName(
this,
'GeneratedUserPoolDomain',
userPoolDomainName
);
} | /**
* Method to create user pool domain
*
* @param props
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L422-L464 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.createUserPoolClient | public createUserPoolClient(props: UserPoolClientProps) {
const cfnUserPoolClient = new cognito.CfnUserPoolClient(this, 'CfnAppClient', {
accessTokenValidity: cdk.Duration.minutes(5).toMinutes(),
idTokenValidity: cdk.Duration.minutes(5).toMinutes(),
refreshTokenValidity: cdk.Duration.days(1).toDays(),
userPoolId: this.userPool.userPoolId,
generateSecret: false,
allowedOAuthFlowsUserPoolClient: cdk.Fn.conditionIf(
this.deployWebAppCondition.logicalId,
true,
cdk.Aws.NO_VALUE
),
allowedOAuthFlows: cdk.Fn.conditionIf(
this.deployWebAppCondition.logicalId,
['code'],
cdk.Aws.NO_VALUE
).toString() as unknown as string[],
explicitAuthFlows: cdk.Fn.conditionIf(
this.deployWebAppCondition.logicalId,
[
'ALLOW_USER_PASSWORD_AUTH',
'ALLOW_ADMIN_USER_PASSWORD_AUTH',
'ALLOW_CUSTOM_AUTH',
'ALLOW_USER_SRP_AUTH',
'ALLOW_REFRESH_TOKEN_AUTH'
],
cdk.Aws.NO_VALUE
).toString() as unknown as string[],
allowedOAuthScopes: cdk.Fn.conditionIf(
this.deployWebAppCondition.logicalId,
[
cognito.OAuthScope.EMAIL.scopeName,
cognito.OAuthScope.COGNITO_ADMIN.scopeName,
cognito.OAuthScope.OPENID.scopeName
],
cdk.Aws.NO_VALUE
).toString() as unknown as string[],
callbackUrLs: [
cdk.Fn.conditionIf(this.deployWebAppCondition.logicalId, props.callbackUrl, cdk.Aws.NO_VALUE).toString()
],
logoutUrLs: [
cdk.Fn.conditionIf(this.deployWebAppCondition.logicalId, props.callbackUrl, cdk.Aws.NO_VALUE).toString()
],
supportedIdentityProviders: ['COGNITO'],
tokenValidityUnits: {
accessToken: 'minutes',
idToken: 'minutes',
refreshToken: 'days'
}
});
const userPoolClient = cognito.UserPoolClient.fromUserPoolClientId(
this,
'AppClient',
cfnUserPoolClient.attrClientId
);
this.createUserPoolClientCondition = new cdk.CfnCondition(this, 'CreateUserPoolClientCondition', {
expression: cdk.Fn.conditionEquals(props.existingCognitoUserPoolClientId, '')
});
(this.node.tryFindChild('CfnAppClient') as cognito.CfnUserPoolClient).cfnOptions.condition =
this.createUserPoolClientCondition;
const userPoolClientId = cdk.Fn.conditionIf(
this.createUserPoolClientCondition.logicalId,
userPoolClient.userPoolClientId,
props.existingCognitoUserPoolClientId
).toString();
this.userPoolClient = cognito.UserPoolClient.fromUserPoolClientId(this, 'UserPoolClient', userPoolClientId);
} | /**
* Creates User Pool Client configuration with OAuth flows, callback urls, and logout urls.
*
* @param props
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L471-L542 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.getOrCreateDeployWebAppCondition | protected getOrCreateDeployWebAppCondition(scope: Construct, deployWebApp: string): cdk.CfnCondition {
if (this.deployWebAppCondition) {
return this.deployWebAppCondition;
}
this.deployWebAppCondition = new cdk.CfnCondition(cdk.Stack.of(scope), 'DeployWebAppCognitoCondition', {
expression: cdk.Fn.conditionEquals(deployWebApp, 'Yes')
});
return this.deployWebAppCondition;
} | /**
* Method to return the condition for deploying the web app
*
* @param scope
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L550-L559 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | CognitoSetup.buildUserName | private buildUserName(props: UserPoolProps): string {
const usernameBase = cdk.Fn.select(0, cdk.Fn.split('@', props.defaultUserEmail));
if (props.usernameSuffix) {
return `${usernameBase}-${props.usernameSuffix}`;
} else {
return usernameBase;
}
} | /**
* Method to build the username from the email address. This avoids conflicting user names even if the email address is the same.
*
* @param props
* @returns
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/auth/cognito-setup.ts#L567-L575 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | ApplicationSetup.addAnonymousMetricsCustomLambda | public addAnonymousMetricsCustomLambda(
solutionId: string,
solutionVersion: string,
additionalProperties?: { [key: string]: any }
) {
this.solutionHelper = new SolutionHelper(this, 'SolutionHelper', {
customResource: this.customResourceLambda,
solutionID: solutionId,
version: solutionVersion,
resourceProperties: additionalProperties,
sendAnonymousMetricsCondition: this.sendAnonymousMetricsCondition
});
} | /**
* This method adds the Anonymous Metrics lambda function to the solution.
*
* @param solutionId - The solution id for the AWS solution
* @param solutionVersion - The solution version for the AWS solution
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/application-setup.ts#L217-L229 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | ApplicationSetup.createWebConfigStorage | public createWebConfigStorage(props: WebConfigProps, ssmKey: string) {
// prettier-ignore
this.webConfigResource = new cdk.CustomResource(this.scope, 'WebConfig', {
resourceType: 'Custom::WriteWebConfig',
serviceToken: this.customResourceLambda.functionArn,
properties: {
Resource: 'WEBCONFIG',
SSMKey: ssmKey,
ApiEndpoint: props.apiEndpoint,
UserPoolId: props.userPoolId,
UserPoolClientId: props.userPoolClientId,
CognitoRedirectUrl: props.cognitoRedirectUrl,
IsInternalUser: cdk.Fn.conditionIf(props.isInternalUserCondition.logicalId, true, false),
...props.additionalProperties
}
});
const lambdaSSMPolicy = new iam.Policy(this, 'WriteToSSM', {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['ssm:PutParameter', 'ssm:GetParameter', 'ssm:DeleteParameter'],
resources: [
`arn:${cdk.Aws.PARTITION}:ssm:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:parameter${WEB_CONFIG_PREFIX}/*`
]
})
]
});
lambdaSSMPolicy.attachToRole(this.customResourceLambda.role!);
this.webConfigResource.node.tryFindChild('Default')!.node.addDependency(lambdaSSMPolicy);
const lambdaCognitoPolicy = new iam.Policy(this, 'GetCognitoUserPoolInfo', {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['cognito-idp:DescribeUserPool'],
resources: [
`arn:${cdk.Aws.PARTITION}:cognito-idp:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:userpool/${props.userPoolId}`
]
})
]
});
lambdaCognitoPolicy.attachToRole(this.customResourceLambda.role!);
this.webConfigResource.node.tryFindChild('Default')!.node.addDependency(lambdaCognitoPolicy);
// prettier-ignore
new cdk.CfnOutput(cdk.Stack.of(this), 'WebConfigKey', { // NOSONAR typescript:S1848. Not valid for CDK
value: ssmKey
});
NagSuppressions.addResourceSuppressions(lambdaSSMPolicy, [
{
id: 'AwsSolutions-IAM5',
reason: 'Permission is required to delete old webconfig ssm parameters',
appliesTo: [
`Resource::arn:<AWS::Partition>:ssm:<AWS::Region>:<AWS::AccountId>:parameter${WEB_CONFIG_PREFIX}/*`
]
}
]);
} | /**
* Method that provisions a custom resource. This custom resource will store the WebConfig in SSM Parameter store.
* Also adds permissions to allow the lambda to write to SSM Parameter Store. The SSM Parameter Key will be
* exported as a stack output and export for the front-end stack to use.
*
* NOTE: all types passed to the CustomResource properties will be cast to string internally, e.g. a boolean true
* will come in the lambda event to the custom resource as 'true'.
*
* @param props
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/application-setup.ts#L241-L301 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | ApplicationSetup.webConfigCustomResource | public get webConfigCustomResource(): cdk.CustomResource {
return this.webConfigResource;
} | /**
* This getter method returns the instance of CustomResource that writes web config to SSM Parameter Store.
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/application-setup.ts#L306-L308 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | ApplicationSetup.addUUIDGeneratorCustomResource | public addUUIDGeneratorCustomResource(): cdk.CustomResource {
return new cdk.CustomResource(this, 'GenUUID', {
resourceType: 'Custom::GenUUID',
serviceToken: this.customResourceLambda.functionArn,
properties: {
Resource: 'GEN_UUID'
}
});
} | /**
* Create a custom resource that generates a UUID
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/application-setup.ts#L313-L321 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | BaseStack.withAdditionalResourceSetup | protected withAdditionalResourceSetup(props: BaseStackProps): any {
logWarningForEmptyImplementation();
} | /**
* Any sub-class stacks can add resources required for their case
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/base-stack.ts#L423-L425 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | UseCaseParameters.withAdditionalCfnParameters | protected withAdditionalCfnParameters(stack: BaseStack) {
this.useCaseUUID = new cdk.CfnParameter(stack, 'UseCaseUUID', {
type: 'String',
description:
'UUID to identify this deployed use case within an application. Please provide an 8 character long UUID. If you are editing the stack, do not modify the value (retain the value used during creating the stack). A different UUID when editing the stack will result in new AWS resource created and deleting the old ones',
allowedPattern: '^[0-9a-fA-F]{8}$',
maxLength: 8,
constraintDescription: 'Please provide an 8 character long UUID'
});
this.useCaseConfigTableName = new cdk.CfnParameter(stack, 'UseCaseConfigTableName', {
type: 'String',
maxLength: 255,
allowedPattern: '^[a-zA-Z0-9_.-]{3,255}$',
description: 'DynamoDB table name for the table which contains the configuration for this use case.',
constraintDescription:
'This parameter is required. The stack will read the configuration from this table to configure the resources during deployment'
});
this.useCaseConfigRecordKey = new cdk.CfnParameter(stack, 'UseCaseConfigRecordKey', {
type: 'String',
maxLength: 2048,
description:
'Key corresponding of the record containing configurations required by the chat provider lambda at runtime. The record in the table should have a "key" attribute matching this value, and a "config" attribute containing the desired config. This record will be populated by the deployment platform if in use. For standalone deployments of this use-case, a manually created entry in the table defined in `UseCaseConfigTableName` is required. Consult the implementation guide for more details.'
});
this.defaultUserEmail = new cdk.CfnParameter(stack, 'DefaultUserEmail', {
type: 'String',
description:
'Email of the default user for this use case. A cognito user for this email will be created to access the use case.',
default: PLACEHOLDER_EMAIL,
allowedPattern: OPTIONAL_EMAIL_REGEX_PATTERN,
constraintDescription: 'Please provide a valid email'
});
this.existingCognitoUserPoolId = new cdk.CfnParameter(stack, 'ExistingCognitoUserPoolId', {
type: 'String',
allowedPattern: '^$|^[0-9a-zA-Z_-]{9,24}$',
maxLength: 24,
description:
'Optional - UserPoolId of an existing cognito user pool which this use case will be authenticated with. Typically will be provided when deploying from the deployment platform, but can be omitted when deploying this use-case stack standalone.',
default: ''
});
this.existingCognitoGroupPolicyTableName = new cdk.CfnParameter(stack, 'ExistingCognitoGroupPolicyTableName', {
type: 'String',
allowedPattern: '^$|^[a-zA-Z0-9_.-]{3,255}$',
maxLength: 255,
description:
'Name of the DynamoDB table containing user group policies, used by the custom authorizer on this use-cases API. Typically will be provided when deploying from the deployment platform, but can be omitted when deploying this use-case stack standalone.',
default: ''
});
this.existingUserPoolClientId = new cdk.CfnParameter(stack, 'ExistingCognitoUserPoolClient', {
type: 'String',
allowedPattern: '^$|^[a-z0-9]{3,128}$',
maxLength: 128,
description:
'Optional - Provide a User Pool Client (App Client) to use an existing one. If not provided a new User Pool Client will be created. This parameter can only be provided if an existing User Pool Id is provided',
default: ''
});
const existingParameterGroups =
this.cfnStack.templateOptions.metadata !== undefined &&
Object.hasOwn(this.cfnStack.templateOptions.metadata, 'AWS::CloudFormation::Interface') &&
this.cfnStack.templateOptions.metadata['AWS::CloudFormation::Interface'].ParameterGroups !== undefined
? this.cfnStack.templateOptions.metadata['AWS::CloudFormation::Interface'].ParameterGroups
: [];
existingParameterGroups.unshift({
Label: { default: 'Please provide identity configuration to setup Amazon Cognito for the use case' },
Parameters: [
this.defaultUserEmail.logicalId,
this.existingCognitoUserPoolId.logicalId,
this.cognitoUserPoolClientDomain.logicalId,
this.existingUserPoolClientId.logicalId,
this.existingCognitoGroupPolicyTableName.logicalId
]
});
existingParameterGroups.unshift({
Label: { default: 'Please provide configuration for the use case' },
Parameters: [
this.useCaseUUID.logicalId,
this.useCaseConfigRecordKey.logicalId,
this.useCaseConfigTableName.logicalId
]
});
// prettier-ignore
new cdk.CfnRule(this.cfnStack, 'PolicyTableRequiredRule', { // NOSONAR - construct instantiation
ruleCondition: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoUserPoolId.valueAsString, '')
),
assertions: [
{
assert: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoGroupPolicyTableName.valueAsString, '')
),
assertDescription:
'When providing an ExistingCognitoUserPoolId ExistingCognitoGroupPolicyTableName must also be provided.'
}
]
});
// prettier-ignore
new cdk.CfnRule(this.cfnStack, 'ExistingUserPoolRequiredRule', { // NOSONAR - construct instantiation
ruleCondition: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoGroupPolicyTableName.valueAsString, '')
),
assertions: [
{
assert: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoUserPoolId.valueAsString, '')
),
assertDescription:
'When providing an ExistingCognitoGroupPolicyTableName ExistingCognitoUserPoolId must also be provided.'
}
]
});
new cdk.CfnRule(this.cfnStack, 'UserPoolClientProvidedWithEmptyUserPoolId', {
ruleCondition: cdk.Fn.conditionNot(cdk.Fn.conditionEquals(this.existingUserPoolClientId.valueAsString, '')),
assertions: [
{
assert: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoUserPoolId.valueAsString, '')
),
assertDescription:
'When providing an ExistingUserPoolClientId ExistingCognitoUserPoolId must also be provided.'
}
]
});
/**
* The rule is to check if user pool id is not provided and only add a custom prefix. The template does not mutate existing
* resources and hence will not create a domain if the user pool already exists
*/
new cdk.CfnRule(stack, 'CheckIfUserPoolIsEmptyForDomainPrefix', {
ruleCondition: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.cognitoUserPoolClientDomain.valueAsString, '')
),
assertions: [
{
assert: cdk.Fn.conditionNot(
cdk.Fn.conditionEquals(this.existingCognitoUserPoolId.valueAsString, '')
),
assertDescription:
"When providing UserPoolDomainPrefix, user pool id should not be empty. Provide the existing user pool's domain prefix"
}
]
});
} | /**
* This method allows adding additional cfn parameters to the stack
*
* @param stack
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/use-case-stack.ts#L92-L244 | b278845810db549e19740c5a2405faee959b82a3 |
generative-ai-application-builder-on-aws | github_2023 | aws-solutions | typescript | BundlerAssetOptionsFactory.constructor | constructor() {
this._assetOptionsMap = new Map();
this._assetOptionsMap.set(COMMERCIAL_REGION_LAMBDA_PYTHON_RUNTIME, new PythonAssetOptions());
this._assetOptionsMap.set(COMMERCIAL_REGION_LAMBDA_NODE_RUNTIME, new TypescriptAssetOptions());
this._assetOptionsMap.set(COMMERCIAL_REGION_LAMBDA_TS_LAYER_RUNTIME, new TypescriptLayerAssetOptions());
this._assetOptionsMap.set(COMMERCIAL_REGION_LAMBDA_JS_LAYER_RUNTIME, new JavascriptLayerAssetOptions());
this._assetOptionsMap.set(CDK_PYTHON_BUNDLER, new CdkJsonContextAssetOptions());
this._assetOptionsMap.set(CHAT_LAMBDA_PYTHON_RUNTIME, new LangchainPythonVersionAssetOptions());
this._assetOptionsMap.set(LANGCHAIN_LAMBDA_LAYER_PYTHON_RUNTIME, new LangChainLayerAssetOptions());
this._assetOptionsMap.set(REACTJS_ASSET_BUNDLER, new ReactjsAssetOptions());
this._assetOptionsMap.set(COMMERCIAL_REGION_LAMBDA_LAYER_PYTHON_RUNTIME, new PythonLayerAssetOptions());
this._assetOptionsMap.set(GOV_CLOUD_REGION_LAMBDA_NODE_RUNTIME, new TypescriptAssetOptions());
this._assetOptionsMap.set(GOV_CLOUD_REGION_LAMBDA_PYTHON_RUNTIME, new PythonAssetOptions());
} | /**
* The constructor initializes
*/ | https://github.com/aws-solutions/generative-ai-application-builder-on-aws/blob/b278845810db549e19740c5a2405faee959b82a3/source/infrastructure/lib/framework/bundler/asset-options-factory.ts#L38-L51 | b278845810db549e19740c5a2405faee959b82a3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.