repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
onchainkit | github_2023 | coinbase | typescript | vwToPx | const vwToPx = (vw: number) => (vw / 100) * window.innerWidth; | // Convert viewport units to pixels | https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/internal/utils/getWindowDimensions.ts#L23-L23 | afcc29e362654e2fd7bc60908a0cc122b0d281c4 |
onchainkit | github_2023 | coinbase | typescript | onError | function onError(e: ErrorEvent) {
e.preventDefault();
} | // disable error output | https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/nft/components/NFTErrorBoundary.test.tsx#L7-L9 | afcc29e362654e2fd7bc60908a0cc122b0d281c4 |
onchainkit | github_2023 | coinbase | typescript | mockWindow | const mockWindow = (innerWidth: number, innerHeight: number) => {
vi.stubGlobal('window', {
innerWidth,
innerHeight,
});
}; | // Mock window dimensions | https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/wallet/utils/getWalletSubComponentPosition.test.ts#L10-L15 | afcc29e362654e2fd7bc60908a0cc122b0d281c4 |
enterprise-commerce | github_2023 | Blazity | typescript | handleClick | const handleClick = async () => {
if (!combination?.id) return
setIsPending(true)
setTimeout(() => {
setProduct({ product, combination })
setIsPending(false)
}, 300)
setTimeout(() => clean(), 4500)
setCheckoutReady(false)
const res = await addCartItem(null, combination.id, product.id)
if (!res.ok) toast.error("Out of stock")
setCheckoutReady(true)
refresh()
} | // Mimic delay and display optimistic UI due to shopify API being slow | https://github.com/Blazity/enterprise-commerce/blob/d34a5d9e8e580f3db9d763955455d0a66669c5a2/starters/shopify-algolia/app/product/_components/add-to-cart-button.tsx#L33-L52 | d34a5d9e8e580f3db9d763955455d0a66669c5a2 |
enterprise-commerce | github_2023 | Blazity | typescript | getAllResults | const getAllResults = async <T extends Record<string, any>>(client: ReturnType<typeof algoliaClient>, args: BrowseProps) => {
const allHits: T[] = []
let totalPages: number
let currentPage = 0
do {
const { hits, nbPages } = await client.browse<T>({
...args,
browseParams: {
...args.browseParams,
hitsPerPage: 1000,
page: currentPage,
},
})
allHits.push(...hits)
totalPages = nbPages || 0
currentPage++
} while (currentPage < totalPages)
return { hits: allHits, totalPages }
} | // agregator as temp fix for now | https://github.com/Blazity/enterprise-commerce/blob/d34a5d9e8e580f3db9d763955455d0a66669c5a2/starters/shopify-algolia/lib/algolia/client.ts#L44-L64 | d34a5d9e8e580f3db9d763955455d0a66669c5a2 |
enterprise-commerce | github_2023 | Blazity | typescript | normalizeProduct | function normalizeProduct(product: PlatformProduct, originalId: string): PlatformProduct {
return {
...product,
id: originalId,
}
} | /* Extract into utils */ | https://github.com/Blazity/enterprise-commerce/blob/d34a5d9e8e580f3db9d763955455d0a66669c5a2/starters/shopify-meilisearch/app/api/feed/sync/route.ts#L106-L111 | d34a5d9e8e580f3db9d763955455d0a66669c5a2 |
enterprise-commerce | github_2023 | Blazity | typescript | handleClick | const handleClick = async () => {
if (!combination?.id) return
setIsPending(true)
setTimeout(() => {
setProduct({ product, combination })
setIsPending(false)
}, 300)
setTimeout(() => clean(), 4500)
setCheckoutReady(false)
const res = await addCartItem(null, combination.id, product.id)
if (!res.ok) toast.error("Out of stock")
setCheckoutReady(true)
refresh()
} | // Mimic delay and display optimistic UI due to shopify API being slow | https://github.com/Blazity/enterprise-commerce/blob/d34a5d9e8e580f3db9d763955455d0a66669c5a2/starters/shopify-meilisearch/app/product/_components/add-to-cart-button.tsx#L33-L52 | d34a5d9e8e580f3db9d763955455d0a66669c5a2 |
hydration-overlay | github_2023 | BuilderIO | typescript | getEntryPoint | const getEntryPoint = <T extends keyof EntryObject>(
entryPoint: EntryObject[T]
): string[] | null => {
if (typeof entryPoint === "string") {
return [entryPoint];
} else if (Array.isArray(entryPoint)) {
return entryPoint;
} else if (typeof entryPoint === "object" && "import" in entryPoint) {
const entryImport = entryPoint.import;
return Array.isArray(entryImport) ? entryImport : [entryImport];
} else {
console.error(
"[ReactHydrationOverlay]: Could not add hydration overlay script due to unexpected entry point: ",
entryPoint
);
return null;
}
}; | // `entryPoint` can be a string, array of strings, or object whose `import` property is one of those two | https://github.com/BuilderIO/hydration-overlay/blob/c8e1a27d6e2011ebdc9f3a7788df01d82eb84444/packages/lib/src/webpack.ts#L6-L23 | c8e1a27d6e2011ebdc9f3a7788df01d82eb84444 |
GPTRouter | github_2023 | Writesonic | typescript | main | async function main() {
const server = await buildServer();
try {
await server.listen({
port: 8000,
host: "0.0.0.0",
});
["SIGINT", "SIGTERM"].forEach(signal => {
process.on(signal, async () => {
server.log.info("Shutting down server...");
await server.close();
process.exit(0);
});
});
} catch (err) {
console.log(err);
process.exit(1);
}
} | /**
* The entry point for initializing and starting the Fastify server.
* It loads the server configuration, starts listening on a given port and sets up
* signal handlers for a graceful shutdown.
*
* @async
* @function main
* @returns {Promise<void>} A promise that resolves when the server is successfully started
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/index.ts#L12-L31 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | buildServer | async function buildServer() {
// Create a new Fastify server instance with pretty print logging enabled.
const server = Fastify({
logger: {
transport: {
target: "pino-pretty",
},
},
}).withTypeProvider<TypeBoxTypeProvider>();
try {
// Connect to the database using the TypeORM plugin.
await server.register(dbConn, { connection: PostgresDataSource });
} catch (err) {
// Log and exit if the database connection fails.
console.log("Error connecting to database");
console.log(err);
process.exit(1);
}
// server.setErrorHandler(async (error, request, reply) => {
// console.log('Error: ', error);
// Sentry.captureException(error);
// reply.status(500).send({ error: error.message || "Something went wrong" });
// });
// Register JWT support for authentication.
// eslint-disable-next-line @typescript-eslint/no-var-requires
server.register(require("@fastify/jwt"), {
secret: process.env.JWT_SECRET,
sign: {
expiresIn: "14d",
},
});
// Register the authentication decorator for the server.
server.decorate("authenticate", async (request, reply) => {
try {
const secret = request.headers["ws-secret"];
if (!secret) {
await request.jwtVerify();
return;
}
if (secret === process.env.WS_SECRET) {
return;
}
const orm = request.server.orm;
const user = await orm.getRepository(User).findOne({ where: { apikey: secret } });
if (user) {
request.user = user;
return;
}
reply.code(401).send({ message: "Unauthorized" });
} catch (err) {
reply.code(401).send({ message: "Unauthorized" });
}
});
// Register the Server-Sent Events (SSE) plugin.
server.register(FastifySSEPlugin);
// Register CORS handling.
// eslint-disable-next-line @typescript-eslint/no-var-requires
server.register(require("@fastify/cors"), () => {
return (req: any, callback: any) => {
const corsOptions = {
// This is NOT recommended for production as it enables reflection exploits
origin: true,
};
// TODO: Add a whitelist of allowed origins
// do not include CORS headers for requests from localhost
if (/^localhost$/m.test(req.headers.origin)) {
corsOptions.origin = false;
}
// callback expects two parameters: error and options
callback(null, corsOptions);
};
});
server.register(fastifyCron, {
jobs: [
{
cronTime: HEALTH_CHECK_CRON_JOB_EXPRESSION,
onTick: async server => {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const token = server.jwt.sign({});
await server.inject({
url: "api/v1/healthcheck",
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
} catch (err) {
console.log(err);
Sentry.captureException(err);
}
},
start: true,
},
],
});
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 1.0,
});
// Set a custom error handler for the server that sends errors to Sentry.
server.setErrorHandler(async (error, request, reply) => {
console.log("Error: ", error);
if (error.statusCode === 429) {
return reply.code(429).send({ message: "You've reached a limit on preview generations" });
}
Sentry.captureException(error);
reply.status(500).send({ error: "Something went wrong" });
});
// Register a default root route.
server.get("/", async function (request: any, reply: any) {
reply.code(200).send({ hello: "Writesonic's model router" });
});
// Register a health check route.
server.get("/healthcheck", async function (request: any, reply: any) {
reply.code(200).send({ status: "ok" });
});
// Initialize Swagger documentation plugin and define the API structure.
await initSwagger(server);
// Initialize all routes within the application.
initRoutes(server);
// Run any initialization scripts needed for the application.
await initData(server.orm);
// Signals that server is ready to accept requests.
await server.ready();
// Serve Swagger-generated API documentation.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
server.swagger();
return server;
} | /**
* Initializes and configures the Fastify server, including database connection,
* authentication, CORS settings, cron jobs, error handling, and routes.
*
* @returns {Promise<FastifyInstance>} A promise that resolves to the configured Fastify server instance.
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/server.ts#L49-L200 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | generationRouter | async function generationRouter(server: FastifyInstance) {
await server.register(import("@fastify/rate-limit"), {
max: 10,
timeWindow: "1440 minute",
keyGenerator: request => {
return request.headers["ws-secret"]?.toString() || "";
},
allowList: request => {
return request.headers["ws-secret"]?.toString() === process.env.WS_SECRET;
},
});
server.post("", { schema: GenerateResponseSchema, onRequest: [server.authenticate] }, generateResponse);
server.post(
"/prompt",
{ schema: GenerateFromPromptResponseSchema, onRequest: [server.authenticate] },
generateResponseFromPrompt,
);
server.post(
"/image",
{ schema: GenerateFromImageResponseSchema, onRequest: [server.authenticate] },
generateResponseFromImage,
);
server.post(
"/generate-image",
{ schema: GenerateImageResponseSchema, onRequest: [server.authenticate] },
generateImageResponse,
);
} | /**
* Attach generation routes to the Fastify server.
* @param {FastifyInstance} server - The Fastify server instance.
* @returns {Promise<void>} - A promise that resolves after attaching the generation routes.
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/generation.route.ts#L22-L50 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | healthCheckRouter | async function healthCheckRouter(server: FastifyInstance) {
server.post("", { schema: HealthCheckSchema, onRequest: [server.authenticate] }, triggerHealthCheck);
server.get("", { schema: GetHealthCheckDataSchema, onRequest: [server.authenticate] }, getHealthCheckData);
} | /**
* Define routes for health check endpoint
* @param {FastifyInstance} server - The Fastify server instance
* @returns {Promise<void>} - A Promise that resolves once the routes are defined
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/healthCheck.route.ts#L11-L14 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | modelRouter | async function modelRouter(server: FastifyInstance) {
server.get("/all", { schema: GetAllModelsSchema, onRequest: [server.authenticate] }, getAllModels);
server.get("/:id", { schema: GetModelByIdSchema, onRequest: [server.authenticate] }, getModelById);
} | /**
* Attach model routes to the Fastify server instance
* @param {FastifyInstance} server - The Fastify server instance
* @returns {Promise<void>}
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/model.route.ts#L11-L14 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | modelUsageRouter | async function modelUsageRouter(server: FastifyInstance) {
server.get("/model", { schema: GetAllUsageByModelSchema, onRequest: [server.authenticate] }, getUsageDataByModel);
} | /**
* Adds route for getting usage data by model
*
* @param {FastifyInstance} server - The Fastify server instance
* @returns {Promise<void>} - A promise that resolves after adding the route
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/modelUsage.route.ts#L12-L14 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | promptRouter | async function promptRouter(server: FastifyInstance) {
server.get("/all", { schema: GetAllPromptsSchema, onRequest: [server.authenticate] }, getAllPrompts);
server.get("/:id", { schema: GetPromptByIdSchema, onRequest: [server.authenticate] }, getPromptById);
server.post("", { schema: CreatePromptSchema, onRequest: [server.authenticate] }, createPrompt);
server.put("/:id", { schema: UpdatePromptSchema, onRequest: [server.authenticate] }, updatePrompt);
server.delete("/:id", { schema: DeletePromptSchema, onRequest: [server.authenticate] }, deletePrompt);
server.post("/optimize", { schema: OptimizePromptSchema, onRequest: [server.authenticate] }, optimizePrompt);
} | /**
* Registers prompt related routes and their corresponding handlers.
* @param {FastifyInstance} server - The Fastify server instance.
* @returns {void}
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/prompt.route.ts#L18-L25 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | providerRouter | async function providerRouter(server: FastifyInstance) {
server.get("/all", { schema: GetAllProvidersSchema, onRequest: [server.authenticate] }, getActiveProviders);
} | /**
* Define routes for handling provider related operations.
*
* @param {FastifyInstance} server - The Fastify server instance
* @returns {Promise<void>} - A promise that resolves when the route is successfully registered
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/provider.route.ts#L12-L14 | 00601732f62a271e063a1341aa1237b37907c5a4 |
GPTRouter | github_2023 | Writesonic | typescript | userRouter | async function userRouter(server: FastifyInstance) {
server.post("/login", { schema: LoginSchema }, verifyUser);
} | /**
* Handles the user routes for login
* @param {FastifyInstance} server - The Fastify server instance
* @returns {Promise<void>} - A Promise that resolves when the route handling is complete
*/ | https://github.com/Writesonic/GPTRouter/blob/00601732f62a271e063a1341aa1237b37907c5a4/src/routes/user.route.ts#L11-L13 | 00601732f62a271e063a1341aa1237b37907c5a4 |
daisy-components | github_2023 | willpinha | typescript | format | function format(name: string) {
return name.toLowerCase().replace(/\s+/g, ""); // Case and whitespace insensitive
} | // Format tag and filter before comparison | https://github.com/willpinha/daisy-components/blob/7ad7e38e78eecdf8f464a1daab5b408c0a73245d/src/utils/filter.ts#L4-L6 | 7ad7e38e78eecdf8f464a1daab5b408c0a73245d |
glish | github_2023 | paralogical | typescript | hashForVariants | function hashForVariants(variants: {
[key in AlternativeCategory]?: unknown;
}): VariantHash {
return (
(variants.plural ? "1" : "0") +
(variants.past ? "1" : "0") +
(variants.gerund ? "1" : "0") +
(variants.actor ? "1" : "0")
);
} | // 0010 | https://github.com/paralogical/glish/blob/3d4578f9fd51421537ca64540c6d8e928c479f18/main.ts#L506-L515 | 3d4578f9fd51421537ca64540c6d8e928c479f18 |
glish | github_2023 | paralogical | typescript | findVariants | function findVariants(
wordSet: Map<string, Array<Array<string>>>,
word: Array<Array<string>>
): { [key in AlternativeCategory]?: Array<Array<string>> } {
const result: { [key in AlternativeCategory]?: Array<Array<string>> } = {};
const checkAndSet = (which: AlternativeCategory, end: string) => {
const combined = JSON.parse(JSON.stringify(word)) as typeof word;
combined[combined.length - 1].push(end);
const flat = combined.flatMap((w) => w.join("")).join("");
if (wordSet.has(flat)) {
result[which] = wordSet.get(flat); // use the actual word, since syllabilization is unpredictable
}
};
checkAndSet("plural", "z");
checkAndSet("plural", "s");
checkAndSet("past", "d");
checkAndSet("past", "t");
checkAndSet("gerund", "ŋ");
checkAndSet("gerund", "ɪŋ");
checkAndSet("actor", "ɹ");
checkAndSet("actor", "ɛɹ");
return result;
} | /**
* Given a split IPA word, find all variants in original english, in split IPA
*/ | https://github.com/paralogical/glish/blob/3d4578f9fd51421537ca64540c6d8e928c479f18/main.ts#L520-L543 | 3d4578f9fd51421537ca64540c6d8e928c479f18 |
glish | github_2023 | paralogical | typescript | updateGraphPart | function updateGraphPart(
which: "onset" | "nucleus" | "coda",
graphPart: SonorityGraphPart,
letters: Array<string>,
// first phone of next part
nextPart: string | null
) {
// initial part of graph
if (which === "onset") {
incGraphPart(graphPart, null, letters?.[0] ?? nextPart);
}
if (letters == null) {
return;
}
let letter: string | null = letters[0] ?? null;
for (const next of [...letters.slice(1), nextPart]) {
incGraphPart(graphPart, letter, next);
letter = next;
}
} | // Given an input syllable, go through letters and update graph part | https://github.com/paralogical/glish/blob/3d4578f9fd51421537ca64540c6d8e928c479f18/sonorityGraph.ts#L125-L145 | 3d4578f9fd51421537ca64540c6d8e928c479f18 |
glish | github_2023 | paralogical | typescript | randomTilInPalete | const randomTilInPalete = (from: Array<[string | null, number]>) => {
const filteredFrom = from.filter(
([l]) => l == null || pallete.includes(l!)
);
if (filteredFrom.length === 0) {
return null;
}
return weightedRandomChoice(filteredFrom);
}; | // TODO: remove from palette as you usefrom a graph, | https://github.com/paralogical/glish/blob/3d4578f9fd51421537ca64540c6d8e928c479f18/sonorityGraph.ts#L302-L310 | 3d4578f9fd51421537ca64540c6d8e928c479f18 |
glish | github_2023 | paralogical | typescript | log | const log: typeof console.log = () => undefined; | // const log: typeof console.log = console.log; | https://github.com/paralogical/glish/blob/3d4578f9fd51421537ca64540c6d8e928c479f18/syllablize.ts#L351-L351 | 3d4578f9fd51421537ca64540c6d8e928c479f18 |
breadboard | github_2023 | breadboard-ai | typescript | describeSpecialist | function describeSpecialist(inputs: unknown) {
const { $inputSchema, $outputSchema, persona, task } =
inputs as SpecialistDescriberInputs;
const inputSchema: Schema = {
type: "object",
additionalProperties: false,
properties: {
...$inputSchema.properties,
in: {
title: "Context in",
description: "Incoming conversation context",
type: "array",
behavior: ["main-port"],
items: {
type: "object",
behavior: ["llm-content"],
},
examples: [],
},
task: {
title: "Prompt",
description:
"(Optional) A prompt. Will be added to the end of the the conversation context. Use mustache-style {{params}} to add parameters.",
type: "object",
default: '{"role":"user","parts":[{"text":""}]}',
behavior: ["llm-content", "config"],
examples: [],
},
persona: {
type: "object",
behavior: ["llm-content", "config"],
title: "System Instruction",
description:
"Give the model additional context on what to do, like specific rules/guidelines to adhere to or specify behavior separate from the provided context. Use mustache-style {{params}} to add parameters.",
default: '{"role":"user","parts":[{"text":""}]}',
examples: [],
},
},
required: [],
};
const all = [
...collectParams(textFromLLMContent(persona)),
...collectParams(textFromLLMContent(task)),
];
const params: string[] = [];
const outs: string[] = [];
for (const param of all) {
const { op = "in" } = param;
if (op === "in") {
params.push(param.name);
} else {
outs.push(param.name);
}
}
const inputProps = Object.fromEntries(
unique(params).map((param) => [
toId(param),
{
title: toTitle(param),
description: `The value to substitute for the parameter "${param}"`,
type: "string",
},
])
);
const outputProps: Record<string, Schema> = Object.fromEntries(
unique(outs).map((param) => [
toId(`TOOL_${param.toLocaleUpperCase()}`),
{
title: toTitle(param),
description: `The output chosen when the "${param}" tool is invoked`,
type: "array",
items: {
type: "object",
behavior: ["llm-content"],
},
},
])
);
const required = params.map(toId);
return mergeSchemas(inputSchema, $outputSchema, inputProps, outputProps);
function mergeSchemas(
inputSchema: Schema,
outputSchema: Schema,
properties: Record<string, Schema>,
outputProps: Record<string, Schema>
) {
return {
inputSchema: {
...inputSchema,
properties: {
...inputSchema.properties,
...properties,
},
required: [...(inputSchema.required || []), ...required],
},
outputSchema: {
...outputSchema,
properties: {
...outputSchema.properties,
...outputProps,
},
},
};
}
function toId(param: string) {
return `p-${param}`;
}
function toTitle(id: string) {
const spaced = id?.replace(/[_-]/g, " ");
return (
(spaced?.at(0)?.toUpperCase() ?? "") +
(spaced?.slice(1)?.toLowerCase() ?? "")
);
}
function textFromLLMContent(content: LlmContent | undefined) {
return (
content?.parts
.map((item) => {
return "text" in item ? item.text : "";
})
.join("\n") || ""
);
}
function unique<T>(params: T[]): T[] {
return Array.from(new Set(params));
}
function collectParams(text: string): ParamInfo[] {
if (!text) return [];
const matches = text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
return Array.from(matches).map((match) => {
const name = match.groups?.name || "";
const op = match.groups?.op;
const arg = match.groups?.arg;
return { name, op, arg, locations: [] } as ParamInfo;
});
}
} | /**
* The describer for the "Specialist" v2 component.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/templating.ts#L55-L206 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | content | function content(starInputs: unknown) {
const { template, role, context, ...inputs } = starInputs as ContentInputs;
const params = mergeParams(findParams(template));
const values = collectValues(params, inputs);
if (role) {
template.role = role;
}
return {
context: prependContext(context, subContent(template, values)),
};
function prependContext(
context: LlmContent[] | undefined,
c: LlmContent | string
): LlmContent[] {
const content = (isEmptyContent(c) ? [] : [c]) as LlmContent[];
if (!context) return [...content] as LlmContent[];
if (isLLMContentArray(context)) {
// If the last item in the context has a user rule,
// merge the new content with it instead of creating a new item.
const last = context.at(-1);
if (last && last.role === "user" && content.at(-1)?.role !== "model") {
return [
...context.slice(0, -1),
{
role: "user",
parts: [
...last.parts,
...((content.at(0) as LlmContent)?.parts || []),
],
},
];
}
return [...context, ...content] as LlmContent[];
}
return content;
}
function isEmptyContent(content: LlmContent | string | undefined) {
if (!content) return true;
if (typeof content === "string") return true;
if (!content.parts?.length) return true;
if (content.parts.length > 1) return false;
const part = content.parts[0];
if (!("text" in part)) return true;
if (part.text.trim() === "") return true;
return false;
}
function subContent(
content: LlmContent | undefined,
values: Record<string, unknown>
): LlmContent | string {
// If this is an array, optimistically presume this is an LLM Content array.
// Take the last item and use it as the content.
if (Array.isArray(content)) {
content = content.at(-1);
}
if (!content) return "";
return {
role: content.role || "user",
parts: mergeTextParts(
splitToTemplateParts(content).flatMap((part) => {
if ("param" in part) {
const value = values[part.param];
if (typeof value === "string") {
return { text: value };
} else if (isLLMContent(value)) {
return value.parts;
} else if (isLLMContentArray(value)) {
const last = getLastNonMetadata(value);
return last ? last.parts : [];
} else {
return { text: JSON.stringify(value) };
}
} else {
return part;
}
})
),
};
}
function getLastNonMetadata(content: Context[]): LlmContent | null {
for (let i = content.length - 1; i >= 0; i--) {
if (content[i].role !== "$metadata") {
return content[i] as LlmContent;
}
}
return null;
}
function findParams(content: LlmContent | undefined): ParamInfo[] {
const parts = content?.parts;
if (!parts) return [];
const results = parts.flatMap((part) => {
if (!("text" in part)) return [];
const matches = part.text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
return unique(Array.from(matches))
.map((match) => {
const name = match.groups?.name || "";
if (!name) return null;
return { name, locations: [{ part, parts }] };
})
.filter(Boolean);
}) as unknown as ParamInfo[];
return results;
}
function mergeParams(...paramList: ParamInfo[][]) {
return paramList.reduce((acc, params) => {
for (const param of params) {
const { name, locations } = param;
const existing = acc[name];
if (existing) {
existing.push(...locations);
} else {
acc[name] = locations;
}
}
return acc;
}, {} as ParamLocationMap);
}
function unique<T>(params: T[]): T[] {
return Array.from(new Set(params));
}
function mergeTextParts(parts: TemplatePart[]) {
const merged = [];
for (const part of parts) {
if ("text" in part) {
const last = merged[merged.length - 1];
if (last && "text" in last) {
last.text += part.text;
} else {
merged.push(part);
}
} else {
merged.push(part);
}
}
return merged as LlmContent["parts"];
}
function toId(param: string) {
return `p-${param}`;
}
function toTitle(id: string) {
const spaced = id?.replace(/[_-]/g, " ");
return (
(spaced?.at(0)?.toUpperCase() ?? "") +
(spaced?.slice(1)?.toLowerCase() ?? "")
);
}
/**
* Takes an LLM Content and splits it further into parts where
* each {{param}} substitution is a separate part.
*/
function splitToTemplateParts(content: LlmContent): TemplatePart[] {
const parts = [];
for (const part of content.parts) {
if (!("text" in part)) {
parts.push(part);
continue;
}
const matches = part.text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
let start = 0;
for (const match of matches) {
const name = match.groups?.name || "";
const end = match.index;
if (end > start) {
parts.push({ text: part.text.slice(start, end) });
}
parts.push({ param: name });
start = end + match[0].length;
}
if (start < part.text.length) {
parts.push({ text: part.text.slice(start) });
}
}
return parts;
}
function collectValues(
params: ParamLocationMap,
inputs: Record<string, unknown>
) {
const values: Record<string, unknown> = {};
for (const param in params) {
const id = toId(param);
const value = inputs[id];
if (!value) {
const title = toTitle(param);
throw new Error(`Missing required parameter: ${title}`);
}
values[param] = value;
}
return values;
}
/**
* Copied from @google-labs/breadboard
*/
function isLLMContent(nodeValue: unknown): nodeValue is LlmContent {
if (typeof nodeValue !== "object" || !nodeValue) return false;
if (nodeValue === null || nodeValue === undefined) return false;
if ("role" in nodeValue && nodeValue.role === "$metadata") {
return true;
}
return "parts" in nodeValue && Array.isArray(nodeValue.parts);
}
function isLLMContentArray(nodeValue: unknown): nodeValue is LlmContent[] {
if (!Array.isArray(nodeValue)) return false;
if (nodeValue.length === 0) return true;
return isLLMContent(nodeValue.at(-1));
}
} | /**
* The guts of the "Content" component.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/templating.ts#L211-L439 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | splitToTemplateParts | function splitToTemplateParts(content: LlmContent): TemplatePart[] {
const parts = [];
for (const part of content.parts) {
if (!("text" in part)) {
parts.push(part);
continue;
}
const matches = part.text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
let start = 0;
for (const match of matches) {
const name = match.groups?.name || "";
const end = match.index;
if (end > start) {
parts.push({ text: part.text.slice(start, end) });
}
parts.push({ param: name });
start = end + match[0].length;
}
if (start < part.text.length) {
parts.push({ text: part.text.slice(start) });
}
}
return parts;
} | /**
* Takes an LLM Content and splits it further into parts where
* each {{param}} substitution is a separate part.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/templating.ts#L376-L401 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | isLLMContent | function isLLMContent(nodeValue: unknown): nodeValue is LlmContent {
if (typeof nodeValue !== "object" || !nodeValue) return false;
if (nodeValue === null || nodeValue === undefined) return false;
if ("role" in nodeValue && nodeValue.role === "$metadata") {
return true;
}
return "parts" in nodeValue && Array.isArray(nodeValue.parts);
} | /**
* Copied from @google-labs/breadboard
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/templating.ts#L423-L432 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | describeContent | function describeContent(inputs: unknown) {
const { template } = inputs as DescribeContentInputs;
const params = unique([...collectParams(textFromLLMContent(template))]);
const props = Object.fromEntries(
params.map((param) => [
toId(param),
{
title: toTitle(param),
description: `The value to substitute for the parameter "${param}"`,
type: "string",
},
])
);
const $inputSchema: Schema = {
properties: {
context: {
type: "array",
title: "Context in",
examples: [],
behavior: ["main-port"],
items: {
type: "object",
behavior: ["llm-content"],
},
default: '[{"role":"user","parts":[{"text":""}]}]',
description: "The optional incoming conversation context",
},
template: {
type: "object",
title: "Template",
examples: [],
behavior: ["llm-content", "config"],
default: "null",
description:
"(Optional) Content that will initialize a new conversation contenxt or be appended to the existing one. Use mustache-style {{params}} to add parameters.",
},
role: {
type: "string",
title: "Role",
default: "user",
enum: ["user", "model"],
description:
"(Optional) The conversation turn role that will be assigned to content created from the template.",
behavior: ["config"],
},
},
type: "object",
required: [],
};
const $outputSchema: Schema = {
type: "object",
properties: {
context: {
type: "array",
title: "Context out",
examples: [],
items: {
type: "object",
behavior: ["llm-content"],
},
description:
"The resulting context, created from the template and parameters.",
},
},
required: [],
};
const required = params.map(toId);
return mergeSchemas($inputSchema, $outputSchema, props);
function mergeSchemas(
inputSchema: Schema,
outputSchema: Schema,
properties: Record<string, Schema>
) {
return {
inputSchema: {
...inputSchema,
properties: {
...inputSchema.properties,
...properties,
},
required: [...(inputSchema.required || []), ...required],
},
outputSchema: outputSchema,
};
}
function toId(param: string) {
return `p-${param}`;
}
function toTitle(id: string) {
const spaced = id?.replace(/[_-]/g, " ");
return (
(spaced?.at(0)?.toUpperCase() ?? "") +
(spaced?.slice(1)?.toLowerCase() ?? "")
);
}
function textFromLLMContent(content: LlmContent | undefined) {
return (
content?.parts
.map((item) => {
return "text" in item ? item.text : "";
})
.join("\n") || ""
);
}
function unique<T>(params: T[]): T[] {
return Array.from(new Set(params));
}
function collectParams(text: string) {
if (!text) return [];
const matches = text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
return Array.from(matches).map((match) => match.groups?.name || "");
}
} | /**
* The describer for the "Content" component.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/templating.ts#L444-L569 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | splitToTemplateParts | function splitToTemplateParts(content: LlmContent): TemplatePart[] {
const parts: TemplatePart[] = [];
for (const part of content.parts) {
if (!("text" in part)) {
parts.push(part);
continue;
}
const matches = part.text.matchAll(
/{{\s*(?<name>[\w-]+)(?:\s*\|\s*(?<op>[\w-]*)(?::\s*"(?<arg>[\w-]+)")?)?\s*}}/g
);
let start = 0;
for (const match of matches) {
const name = match.groups?.name || "";
const op = match.groups?.op as Operation;
const arg = match.groups?.arg;
const end = match.index;
if (end > start) {
parts.push({ text: part.text.slice(start, end) });
}
parts.push({ param: name, op, arg });
start = end + match[0].length;
}
if (start < part.text.length) {
parts.push({ text: part.text.slice(start) });
}
}
return parts;
} | /**
* Takes an LLM Content and splits it further into parts where
* each {{param}} substitution is a separate part.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/agent-kit/src/js-components/substitute.ts#L191-L218 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Conversation.availableTools | get availableTools() {
return this.#availableToolsComputed.value;
} | // pattern? | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/bbrt/src/llm/conversation.ts#L65-L67 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | ReactiveSessionState.rollback | rollback(index: number) {
this.events.splice(index);
} | /**
* Delete all events including and after the given index.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/bbrt/src/state/session.ts#L55-L57 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | ReactiveTurnState.partialText | get partialText(): string {
while (this.#textStartIndex < this.chunks.length) {
const event = this.chunks[this.#textStartIndex]!;
if (event.kind === "text") {
this.#textAccumulator += event.text;
}
this.#textStartIndex++;
}
return this.#textAccumulator;
} | /**
* The text we have accumulated so far (signal-reactive).
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/bbrt/src/state/turn.ts#L69-L78 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | ReactiveTurnState.partialFunctionCalls | get partialFunctionCalls(): ReadonlyArray<ReactiveFunctionCallState> {
const length = this.chunks.length;
for (let i = this.#functionCallsNextStartIndex; i < length; i++) {
const event = this.chunks[i]!;
if (event.kind === "function-call") {
this.#functionCallsAccumulator.push(event.call);
}
}
this.#functionCallsNextStartIndex = length;
return this.#functionCallsAccumulator;
} | /**
* The function calls we have accumulated so far (signal-reactive).
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/bbrt/src/state/turn.ts#L85-L95 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | ReactiveTurnState.partialErrors | get partialErrors(): ReadonlyArray<TurnChunkError> {
const length = this.chunks.length;
for (let i = this.#errorsNextStartIndex; i < length; i++) {
const event = this.chunks[i]!;
if (event.kind === "error") {
this.#errorsAccumulator.push(event);
}
}
this.#errorsNextStartIndex = length;
return this.#errorsAccumulator;
} | /**
* The errors we have accumulated so far (signal-reactive).
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/bbrt/src/state/turn.ts#L102-L112 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | VisitorStateManager.getOrCreateInvite | async getOrCreateInvite(): Promise<CreateInviteResponse> {
const invites = await this.listInvites();
if (invites.success && invites.invites.length > 0) {
return { success: true, invite: invites.invites[0] as string };
}
return this.createInvite();
} | /**
* Same as createInvite, but if an invite already exists, it will return that
* instead of creating a new one.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/board-server/src/app/utils/visitor-state-manager.ts#L249-L255 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | proxy | const proxy = async (_req: Request, _res: Response): Promise<void> => {
throw new Error("Not implemented");
// if (!getUserKey(req)) {
// res.status(401).json({
// error: "Need a valid server key to access the node proxy.",
// timestamp: timestamp(),
// });
// return;
// }
// const server = new ProxyServer(
// new HTTPServerTransport({ body: req.body }, new ResponseAdapter(res))
// );
// const store = getDataStore();
// store.createGroup("run-board");
// const tunnel = await buildSecretsTunnel();
// const config: ProxyServerConfig = {
// kits: [secretsKit, asRuntimeKit(Core)],
// store,
// proxy: ["fetch", { node: "secrets", tunnel }],
// };
// try {
// await server.serve(config);
// } catch (e) {
// res.status(500).json({ error: (e as Error).message });
// }
// store.releaseAll();
}; | // class ResponseAdapter implements ProxyServerResponse { | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/board-server/src/express/proxy/proxy.ts#L32-L62 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.constructor | constructor(
{ url, title, description, version, $schema }: GraphInlineMetadata = {
$schema: breadboardSchema.$id,
}
) {
Object.assign(this, {
$schema: $schema ?? breadboardSchema.$id,
url,
title,
description,
version,
});
} | /**
*
* @param metadata - optional metadata for the board. Use this parameter
* to provide title, description, version, and URL for the board.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L60-L72 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.input | input<In = InputValues, Out = OutputValues>(
config: OptionalIdConfiguration = {}
): BreadboardNode<In, Out> {
const { $id, ...rest } = config;
return new Node(this, undefined, "input", { ...rest }, $id);
} | /**
* Places an `input` node on the board.
*
* An `input` node is a node that asks for inputs from the user.
*
* See [`input` node reference](https://github.com/breadboard-ai/breadboard/blob/main/packages/breadboard/docs/nodes.md#input) for more information.
*
* @param config - optional configuration for the node.
* @returns - a `Node` object that represents the placed node.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L93-L98 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.output | output<In = InputValues, Out = OutputValues>(
config: OptionalIdConfiguration = {}
): BreadboardNode<In, Out> {
const { $id, ...rest } = config;
return new Node(this, undefined, "output", { ...rest }, $id);
} | /**
* Places an `output` node on the board.
*
* An `output` node is a node that provides outputs to the user.
*
* See [`output` node reference](https://github.com/breadboard-ai/breadboard/blob/main/packages/breadboard/docs/nodes.md#output) for more information.
*
* @param config - optional configuration for the node.
* @returns - a `Node` object that represents the placed node.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L110-L115 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.addKit | addKit<T extends Kit>(ctr: KitConstructor<T>): T {
const kit = asComposeTimeKit(ctr, this);
return kit as T;
} | /**
* Adds a new kit to the board.
*
* Kits are collections of nodes that are bundled together for a specific
* purpose. For example, the [Core Kit](https://github.com/breadboard-ai/breadboard/tree/main/packages/core) provides a nodes that
* are useful for making boards.
*
* Typically, kits are distributed as NPM packages. To add a kit to the board,
* simply install it using `npm` or `yarn`, and then add it to the board:
*
* ```js
* import { Board } from "@google-labs/breadboard";
* import { Core } from "@google-labs/core-kit";
*
* const board = new Board();
* const kit = board.addKit(Core);
* ```
*
* @param ctr - the kit constructor.
* @returns - the kit object, which is associated with
* the board and can be used to place nodes on that board.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L147-L150 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.currentBoardToAddTo | currentBoardToAddTo(): Breadboard {
const closureStack = this.#topClosure
? this.#topClosure.#closureStack
: this.#closureStack;
if (closureStack.length === 0) return this;
else return closureStack[closureStack.length - 1];
} | /**
* Used in the context of board.lambda(): Returns the board that is currently
* being constructed, according to the nesting level of board.lambda() calls
* with JS functions.
*
* Only called by Node constructor, when adding nodes.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L159-L165 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Board.addEdgeAcrossBoards | addEdgeAcrossBoards(edge: Edge, from: Board, to: Board) {
if (edge.out === "*")
throw new Error("Across board wires: * wires not supported");
if (!edge.constant)
throw new Error("Across board wires: Must be constant for now");
if (to !== this)
throw new Error("Across board wires: Must be invoked on to board");
const closureStack = this.#topClosure
? this.#topClosure.#closureStack
: this.#closureStack;
if (from !== this.#topClosure && !closureStack.includes(from))
throw new Error("Across board wires: From must be parent of to");
this.#acrossBoardsEdges.push({ edge, from, to });
} | /**
*
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/board.ts#L170-L187 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | filterEmptyValues | function filterEmptyValues<T extends Record<string, unknown>>(obj: T): T {
return Object.fromEntries(
Object.entries(obj).filter(([, value]) => !!value)
) as T;
} | /**
* A utility function to filter out empty (null or undefined) values from
* an object.
*
* @param obj -- The object to filter.
* @returns -- The object with empty values removed.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/graph-based-node-handler.ts#L170-L174 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | filterEmptyValues | function filterEmptyValues<T extends Record<string, unknown>>(obj: T): T {
return Object.fromEntries(
Object.entries(obj).filter(([, value]) => !!value)
) as T;
} | /**
* A utility function to filter out empty (null or undefined) values from
* an object.
*
* @param obj -- The object to filter.
* @returns -- The object with empty values removed.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/sandboxed-run-module.ts#L424-L428 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | findStreams | const findStreams = (value: NodeValue, foundStreams: ReadableStream[]) => {
if (Array.isArray(value)) {
value.forEach((item: NodeValue) => {
findStreams(item, foundStreams);
});
} else if (typeof value === "object") {
if (value === null || value === undefined) return;
const maybeCapability = value as StreamCapabilityType;
if (maybeCapability.kind && maybeCapability.kind === STREAM_KIND) {
foundStreams.push(maybeCapability.stream);
} else {
Object.values(value as object).forEach((item) => {
findStreams(item, foundStreams);
});
}
}
}; | // TODO: Remove this once MessageController is gone. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/stream.ts#L44-L60 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | computeSelection | function computeSelection(
graph: InspectableGraph,
nodes: NodeIdentifier[]
): EditableGraphSelectionResult {
// First, let's make sure that all nodes are present in graph.
const allPresent = nodes.every((id) => graph.nodeById(id));
if (!allPresent) {
return {
success: false,
error: "Can't create selection: some nodes aren't in the graph",
};
}
// Now, let's get all the edges connected to these nodes.
const n = new Set(nodes);
const edges: Edge[] = [];
const dangling: Edge[] = [];
graph.raw().edges.forEach((edge) => {
const { from, to } = edge;
const hasFrom = n.has(from);
const hasTo = n.has(to);
if (hasFrom && hasTo) {
edges.push(edge);
} else if (hasFrom || hasTo) {
dangling.push(edge);
}
});
return {
success: true,
nodes,
edges,
dangling,
};
} | /**
* Creates a selection: a list of nodes and edges that will are associated
* with the given list of node identifiers within the graph.
* The selection is transient in that it only applies to the current version
* of the graph and becomes invalid as soon as the graph mutates.
*
* @param nodes -- nodes to include in the selection
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/editor/selection.ts#L21-L54 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | LocalRunner.constructor | constructor(config: RunConfig) {
super();
this.#config = config;
} | /**
* Initialize the runner.
* This does not start the runner.
*
* @param config -- configuration for the run
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/harness/local-runner.ts#L51-L54 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | secretHandlersFromKits | const secretHandlersFromKits = (kits: Kit[]): NodeHandler[] => {
const secretHandlers = [];
for (const kit of kits) {
for (const [key, handler] of Object.entries(kit.handlers)) {
if (key === "secrets") {
secretHandlers.push(handler);
}
}
}
return secretHandlers;
}; | /**
* Get all secret handlers from the given kits.
* This is used to create a fallback list for secret asking.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/harness/secrets.ts#L24-L34 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | makeTerribleOptions | function makeTerribleOptions(
options: InspectableGraphOptions = {}
): Required<InspectableGraphOptions> {
return {
kits: options.kits || [],
sandbox: options.sandbox || {
runModule() {
throw new Error("Non-existent sandbox: Terrible Options were used.");
},
},
loader: createLoader(),
};
} | // TODO: Deprecate and remove. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/graph-store.ts#L59-L71 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | filterEmptyValues | function filterEmptyValues<T extends Record<string, unknown>>(obj: T): T {
return Object.fromEntries(
Object.entries(obj).filter(([, value]) => !!value)
) as T;
} | /**
* A utility function to filter out empty (null or undefined) values from
* an object.
*
* @param obj -- The object to filter.
* @returns -- The object with empty values removed.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/graph-store.ts#L535-L539 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | filterEmptyValues | function filterEmptyValues<T extends Record<string, unknown>>(obj: T): T {
return Object.fromEntries(
Object.entries(obj).filter(([, value]) => {
if (!value) return false;
if (typeof value === "object") {
return Object.keys(value).length > 0;
}
return true;
})
) as T;
} | /**
* A utility function to filter out empty (null or undefined) values from
* an object.
*
* @param obj -- The object to filter.
* @returns -- The object with empty values removed.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/graph/describer-manager.ts#L495-L505 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Entry.addError | addError(event: InspectableRunErrorEvent) {
const entry = this.create([this.#children.length]);
entry.event = event as unknown as InspectableRunNodeEvent;
} | /**
* We handle error specially, because unlike sidecars, errors result
* in stopping the run, and we need to display them at the end of the run.
* @param event -- The error event to add.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/run/path-registry.ts#L94-L97 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | getLastNodeEVent | const getLastNodeEVent = () => {
const events = this.#events.events;
for (let i = events.length - 1; i >= 0; i--) {
const maybeNodeEvent = events[i];
if (maybeNodeEvent.type === "node" && !maybeNodeEvent.bubbled)
return maybeNodeEvent;
}
return null;
}; | // TODO: Implement full stack. For now, just return the top-level item. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/run/run.ts#L305-L313 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Snapshot.update | async update(_manual: boolean = false): Promise<void> {
// Use inifite loop with dequeueing instead of a typical forEach,
// because the middle of the loop has awaits and they can introduce
// new items into the pending queue.
for (;;) {
const pending = this.#pending.shift();
if (!pending) {
this.#setFresh();
break;
}
switch (pending.type) {
case "updateports": {
const { graphId, nodeId } = pending;
const inspector = this.#mutable.graphs.get(graphId);
if (!inspector) {
throw new Error(
`Snapshot API integrity error: unable to find graph "${graphId}"`
);
}
const node = inspector.nodeById(nodeId);
if (!node) {
throw new Error(
`Snasphot API integrity error: uanble to find node "${nodeId}" in graph "${graphId}"`
);
}
const ports = await node.ports();
const changes = this.#mutable.ports.getChanges(
graphId,
nodeId,
ports
);
this.#changes.addPorts(graphId, nodeId, changes);
break;
}
default: {
throw new Error(
`Snapshot API integrity error: Unsupported pending type "${pending.type}"`
);
}
}
}
} | /**
*
* @param manual -- if `true`, the updates will stop once the
* update queue is empty, and when the new items arrive, this
* method will have to be called again.
* If `false` (default), will continue updating as soon as new
* items arrive into the update queue.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/inspector/snapshot/snapshot.ts#L81-L122 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | KitBuilder.wrap | static wrap<F extends Record<string, Function>>(
params: KitBuilderOptions,
functions: F
): KitConstructor<
GenericKit<{ [x in keyof FunctionsOnly<F>]: NodeHandler }>
> {
const createHandler = (
previous: NodeHandlers,
// eslint-disable-next-line @typescript-eslint/ban-types
current: [string, Function]
) => {
const [name, fn] = current;
previous[name] = {
invoke: async (inputs: InputValues) => {
// JS can have rest args, eg. "...args" as a parameter at the end of a function, but breadboard cannot accept "." so we use "___".
let argNames: string[] = [];
if (fn && fn.length > 0) {
argNames =
fn
.toString()
.match(/\((.+?)\)/)?.[1]
.split(",") ?? [];
/*
If fn.length is greater than 1 and argNames.length = 0, then we likely have a system function that accepts a splat of arguments..
e.g Math.max([1,2,3,4])
We need to special case this and pass the arguments as an array and expect `inputs` to have a key of `args` that is an array.
*/
if (
fn.length > 1 &&
argNames.length === 0 &&
"___args" in inputs &&
Array.isArray(inputs["___args"])
) {
argNames = ["___args"];
}
}
// Validate the input names.
for (const argName of argNames) {
if (argName.trim() in inputs === false) {
throw new Error(
`Missing input: ${argName.trim()}. Valid inputs are: ${Object.keys(
inputs
).join(", ")}`
);
}
}
const args = argNames
.filter((argName) => argName.startsWith("___") == false)
.map((argName: string) => inputs[argName.trim()]);
const lastArgName = argNames[argNames.length - 1];
if (lastArgName != undefined && lastArgName.startsWith("___")) {
// Splat the rest of the arguments.
args.push(...(<Array<any>>inputs[lastArgName]));
}
const results = await fn(...args);
if (typeof results !== "object" || Array.isArray(results)) {
// Number, Boolean, Array, String, will output to `result`.
return { result: results };
}
// Objects will destructured into the output.
return { ...results };
},
};
return previous;
};
const handlers = Object.entries(functions).reduce<NodeHandlers>(
createHandler,
{}
);
const builder = new KitBuilder(params);
return builder.build(handlers) as KitConstructor<
GenericKit<{ [x in keyof FunctionsOnly<F>]: NodeHandler }>
>;
} | // eslint-disable-next-line @typescript-eslint/ban-types | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/kits/builder.ts#L113-L201 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | getConfigWithLambda | const getConfigWithLambda = (
board: Breadboard,
config: ConfigOrGraph
): OptionalIdConfiguration => {
// Did we get a graph?
const gotGraph =
(config as GraphDescriptor).nodes !== undefined &&
(config as GraphDescriptor).edges !== undefined &&
(config as GraphDescriptor).kits !== undefined;
// Look for functions, nodes and board capabilities.
const gotBoard =
gotGraph ||
typeof config === "function" ||
config instanceof Node ||
((config as BreadboardCapability).kind === "board" &&
(config as GraphDescriptorBoardCapability).board);
const result = (
gotBoard
? { board: gotGraph ? { kind: "board", board: config } : config }
: config
) as OptionalIdConfiguration;
return result;
}; | /**
* Syntactic sugar for node factories that accept lambdas. This allows passing
* either
* - A JS function that is a lambda function defining the board
* - A board capability, i.e. the result of calling lambda()
* - A board node, which should be a node with a `board` output
* or
* - A regular config, with a `board` property with any of the above.
*
* @param config {ConfigOrGraph} the overloaded config
* @returns {NodeConfigurationConstructor} config with a board property
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/kits/ctors.ts#L68-L93 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | registerKitGraphs | function registerKitGraphs(
legacyKitGraphs: GraphDescriptor[],
graphStore: MutableGraphStore
): void {
for (const project of legacyKitGraphs) {
if (!project.graphs) continue;
for (const [key, graph] of Object.entries(project.graphs)) {
graphStore.addByDescriptor({
...graph,
url: `${project.url}?graph=${key}`,
});
}
}
} | /**
* A helper function for registering old-style graph kits that are
* created using `kitFromGraphDescriptor`.
*
* Call it to ensure that the graphs, representing the node handlers
* for these kits are in the graph store, so that the graph store doesn't
* attempt to load them (their URLs are just URIs).
*
* @param legacyKitGraphs -- loosely, Agent Kit and Google Drive Kit
* @param graphStore
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/kits/load.ts#L186-L199 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | lambdaFactory | function lambdaFactory(
options: {
input?: Schema;
output?: Schema;
graph?: GraphDeclarationFunction;
invoke?: NodeProxyHandlerFunction;
describe?: NodeDescriberFunction;
name?: string;
} & GraphCombinedMetadata
): Lambda {
if (!options.invoke && !options.graph)
throw new Error("Missing invoke or graph definition function");
const lexicalScope = getCurrentContextScope();
const closureEdgesToWire: ClosureEdge[] = [];
// Extract board metadata from config. Used in serialize().
const { url, title, description, version } = options ?? {};
const configMetadata: GraphCombinedMetadata = {
...(url ? { url } : {}),
...(title ? { title } : {}),
...(description ? { description } : {}),
...(version ? { version } : {}),
};
const inputSchema = options.input;
const outputSchema = options.output;
const handler: NodeHandler = {};
if (options.describe) handler.describe = options.describe;
else if (inputSchema && outputSchema)
handler.describe = async () => ({ inputSchema, outputSchema });
if (options.invoke) handler.invoke = options.invoke as NodeHandlerFunction;
if (options.graph) {
const scope = new BuilderScope({ lexicalScope, serialize: true });
scope.asScopeFor(() => {
const inputNode = new BuilderNode(
"input",
scope,
inputSchema ? { schema: inputSchema } : {}
);
const outputNode = new BuilderNode(
"output",
scope,
outputSchema ? { schema: outputSchema } : {}
);
const createAndPinNode = (
type: string,
config: InputsMaybeAsValues<InputValues>
) => {
const node = new BuilderNode(type, scope, config);
scope.pin(node);
return node.asProxy();
};
// Create base kit that auto-pins to the scope.
const base = {
input: createAndPinNode.bind(null, "input") as NodeFactory,
output: createAndPinNode.bind(null, "output") as NodeFactory,
};
const result = options.graph?.(
inputNode.asProxy() as InputsForGraphDeclaration<InputValues>,
base
);
// Nothing returned means that the function must have pinned nodes itself
// using the `base` kit supplied above.
if (result === undefined) return;
if (result instanceof Promise)
throw new Error("Graph generation function can't be async");
let actualOutput = outputNode as BuilderNode;
if (result instanceof BuilderNode) {
// If the handler returned an output node, serialize it directly,
// otherwise connect the returned node's outputs to the output node.
const node = result.unProxy();
if (node.type === "output") actualOutput = node;
else outputNode.addInputsFromNode(node);
} else if (typeof result === "object") {
// Otherwise wire up all keys of the returned object to the output.
outputNode.addInputsAsValues(
result as InputsMaybeAsValues<OutputValues>
);
} else {
throw new Error(
`Unexpected return ${typeof result} value from graph declaration`
);
}
// Pin the resulting graph. Note: This might not contain either of the
// input or output nodes created above, if e.g. a new input node was
// created and an output node was returned.
scope.pin(actualOutput);
})();
// Add closure wires from parent scopes, if any
if (scope.getClosureEdges().length > 0) {
// This input node will receive all closure wires into the new graph.
const closureInput = new BuilderNode("input", scope, {
$id: "closure-input",
});
scope.pin(closureInput);
for (const edge of scope.getClosureEdges()) {
// Connect closure input to destination node
const { to, out, in: in_ } = edge;
const wire = `$l-${out}-${to.id}`;
to.addIncomingEdge(closureInput, wire, in_, true);
// Wire upwards. This has to wait until the end of this function because
// we first need the lambda node, and that in turn needs to serialize
// this graph first.
closureEdgesToWire.push({ ...edge, to: closureInput, in: wire });
}
}
scope.compactPins();
const numGraphs = scope.getPinnedNodes().length;
if (numGraphs !== 1)
if (numGraphs === 0)
throw new Error(
"If not returning a graph, use `base.input` and `base.output`."
);
else
throw new Error(
`Expected exactly one graph, but got ${numGraphs}. Are ${scope
.getPinnedNodes()
.map((node) => node.id)
.join(", ")} maybe disjoint?`
);
handler.graph = scope;
}
let lambdaNode:
| BuilderNode<
{ board: BreadboardCapability },
{ board: BreadboardCapability }
>
| undefined = undefined;
// TODO: Fix for closures, probably create a graph with an invoke node and
// re-register name with that as handler. But first we need to get cross-scope
// wiring right.
if (options.name)
registerNodeType(options.name, handler as unknown as NodeHandler);
// When this factory is called, create node with handler and return as proxy.
// But if this is a closure, i.e. there are incoming wires to the lambda node
// (= like a closure, it reads from other nodes in its parent lexical scope),
// then invoke said lambda by reading the board capability it creates.
const factory = ((config?: InputsMaybeAsValues<InputValues>) => {
if (
!lambdaNode ||
(lambdaNode.incoming.length === 0 && closureEdgesToWire.length == 0)
)
return new BuilderNode(
handler,
getCurrentContextScope(),
config
).asProxy();
else
return new BuilderNode("invoke", getCurrentContextScope(), {
...config,
$board: lambdaNode.asProxy().board,
});
}) as Lambda;
// Serializable:
// (Will be called and then overwritten by `createLambda` below
// once this turns into a closure)
factory.serialize = async (metadata?: GraphCombinedMetadata) => {
const node = new BuilderNode(handler, lexicalScope);
const [singleNode, graph] = await node.serializeNode();
// If there is a subgraph that is invoked, just return that.
if (graph) {
if (singleNode.type !== "invoke")
throw new Error("Unexpected node with graph");
return { ...configMetadata, ...metadata, ...graph } as GraphDescriptor;
}
// Otherwise build a graph around the node:
else
return {
...configMetadata,
...metadata,
edges: [
{ from: `${singleNode.id}-input`, to: singleNode.id, out: "*" },
{ from: singleNode.id, to: `${singleNode.id}-output`, out: "*" },
],
nodes: [
{
id: `${singleNode.id}-input`,
type: "input",
configuration: inputSchema ? { schema: inputSchema } : {},
},
singleNode,
{
id: `${singleNode.id}-output`,
type: "output",
configuration: outputSchema ? { schema: outputSchema } : {},
},
],
};
};
// ClosureNodeInterface:
// Creates a lambda node if this lambda is used as a closure, i.e. it accesses
// wires from nodes in it's lexical scope, or it's passed as a value, i.e. a
// BoardCapability needs to be created. Those wires will be wired to this
// node, which then passes the values to the lambda when invoked. For now it
// does that by adding those values to the `args` field in the serialized
// graph. And it outputs a `BoardCapability` that can be invoked. In the
// future we'll replace the latter with first class support of factories.
function getLambdaNode() {
if (lambdaNode) return lambdaNode;
const serialized = factory.serialize();
// HACK: Since node creation is synchronous, we put a promise for the board
// capability here. BuilderNode.serializeNode() awaits that then.
lambdaNode = new BuilderNode("lambda", lexicalScope, {
board: (async () => ({
kind: "board",
board: { kits: [], ...(await serialized) },
// kits: because Runner.fromBoardCapability checks for that.
}))() as unknown as BreadboardCapability,
});
// Replace the serialize function with one that returns a graph with that
// lambda node and an invoke node, not the original graph.
factory.serialize = async (metadata?: GraphCombinedMetadata) => {
// If there are no incoming wires to the lambda node, it's not a closure
// and we can just return the original board.
if (lambdaNode?.incoming.length === 0 && closureEdgesToWire.length === 0)
return await serialized;
const invoke = new BuilderNode("invoke", getCurrentContextScope(), {
$board: lambdaNode?.asProxy().board,
});
return invoke.serialize({ ...configMetadata, ...metadata });
};
return lambdaNode;
}
// Return wire from lambdaNode that will generate a BoardCapability
factory.getBoardCapabilityAsValue = () =>
lambdaNode !== undefined &&
(lambdaNode.incoming.length > 0 || closureEdgesToWire.length > 0)
? lambdaNode.asProxy().board
: ((async () => ({
kind: "board",
board: { kits: [], ...(await factory.serialize()) },
}))() as Promise<BreadboardCapability>);
// Access to factory as if it was a node means accessing the closure node.
// This makes otherNode.to(factory) work.
factory.unProxy = () => getLambdaNode().unProxy() as unknown as BuilderNode;
// Allow factory.in(...incoming wires...).
//
// Note: factory.to() is not supported as there are no outgoing wires. To
// access to `board` output, wire the factory directly. In the future we'll
// get rid of BoardCapability and treat node factories as first class entities.
//
factory.in = (inputs: Parameters<Lambda["in"]>[0]) => {
getLambdaNode().in(inputs);
return factory as unknown as NodeProxy;
};
for (const { scope: fromScope, from, out, in: in_ } of closureEdgesToWire) {
// If we reached the source scope, connect source node to lambda
if (fromScope === lexicalScope)
getLambdaNode().addIncomingEdge(from, out, in_, true);
// Otherwise add closure edge to the lambda node's scope
else
lexicalScope.addClosureEdge({
scope: fromScope,
from,
to: getLambdaNode(),
out,
in: in_,
});
}
return factory;
} | /**
* Actual implementation of all the above
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/board.ts#L73-L372 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | getLambdaNode | function getLambdaNode() {
if (lambdaNode) return lambdaNode;
const serialized = factory.serialize();
// HACK: Since node creation is synchronous, we put a promise for the board
// capability here. BuilderNode.serializeNode() awaits that then.
lambdaNode = new BuilderNode("lambda", lexicalScope, {
board: (async () => ({
kind: "board",
board: { kits: [], ...(await serialized) },
// kits: because Runner.fromBoardCapability checks for that.
}))() as unknown as BreadboardCapability,
});
// Replace the serialize function with one that returns a graph with that
// lambda node and an invoke node, not the original graph.
factory.serialize = async (metadata?: GraphCombinedMetadata) => {
// If there are no incoming wires to the lambda node, it's not a closure
// and we can just return the original board.
if (lambdaNode?.incoming.length === 0 && closureEdgesToWire.length === 0)
return await serialized;
const invoke = new BuilderNode("invoke", getCurrentContextScope(), {
$board: lambdaNode?.asProxy().board,
});
return invoke.serialize({ ...configMetadata, ...metadata });
};
return lambdaNode;
} | // ClosureNodeInterface: | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/board.ts#L298-L329 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | serializeFunction | const serializeFunction = (name: string, handlerFn: Function) => {
let code = handlerFn.toString();
const arrowFunctionRegex = /(?:async\s*)?(\w+|\([^)]*\))\s*=>\s*/;
const traditionalFunctionRegex =
/(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*\{/;
if (arrowFunctionRegex.test(code)) {
code = `const ${name} = ${code};`;
} else {
const match = traditionalFunctionRegex.exec(code);
if (match === null) throw new Error("Unexpected serialization: " + code);
else name = match[1] || name;
}
return [code, name];
}; | // eslint-disable-next-line @typescript-eslint/ban-types | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L40-L55 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.addInputsFromNode | addInputsFromNode(
from: AbstractNode,
keymap: KeyMap = { "*": "" },
constant?: boolean,
schema?: Schema
) {
const keyPairs = Object.entries(keymap);
if (keyPairs.length === 0) {
// Add an empty edge: Just control flow, no data moving.
this.addIncomingEdge(from, "", "", constant);
} else {
keyPairs.forEach(([fromKey, toKey]) => {
// "*-<id>" means "all outputs from <id>" and comes from using a node in
// a spread, e.g. newNode({ ...node, $id: "id" }
if (fromKey.startsWith("*-")) {
fromKey = "*";
toKey = "";
}
this.unProxy().addIncomingEdge(
isBuilderNodeProxy(from) ? from.unProxy() : from,
fromKey,
toKey,
constant,
schema
);
});
}
} | // Add inputs from another node as edges | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L161-L189 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.serializeNode | async serializeNode(): Promise<[NodeDescriptor, GraphDescriptor?]> {
// HACK: See board.getClosureNode() and
// board.getBoardCapabilityAsValue() for why this is needed. There we
// create a node that has a board capability as input, but serializing the
// graph is async, while node creation isn't. So we wait until here to
// await the serialized BoardCapability. To fix: Make node factories a
// first class object, which should inherently move serializing the
// subgraph to here (and never serialize subgraphs if their parent graphs
// aren't serialized either).
for (const [key, value] of Object.entries(this.configuration))
if (value instanceof Promise)
this.configuration[key as keyof typeof this.configuration] =
await value;
if (this.type !== "fn") {
return super.serializeNode();
}
const scope = new BuilderScope({
lexicalScope: this.#scope,
serialize: true,
});
const handler = this.#handler ?? scope.getHandler(this.type);
// If this is a graph node, save it as a subgraph (returned as second value)
// and turns this into an invoke node.
if (handler && typeof handler !== "function" && handler.graph) {
const node: NodeDescriptor = {
id: this.id,
type: "invoke",
configuration: {
...(this.configuration as OriginalInputValues),
path: "#" + this.id,
},
};
const graphs = handler.graph.getPinnedNodes();
if (graphs.length !== 1) throw new Error("Expected exactly one graph");
return [node, await scope.serialize({}, graphs[0])];
} else {
// Else, serialize the handler itself and return a runJavascript node.
const handlerFn =
handler && "invoke" in handler && handler.invoke
? handler.invoke
: typeof handler === "function"
? handler
: undefined;
if (!handlerFn)
throw new Error(`Handler for ${this.type} in ${this.id} not found`);
const jsFriendlyId = this.id.replace(/-/g, "_");
const [code, name] = serializeFunction(jsFriendlyId, handlerFn);
const node = {
id: this.id,
type: "runJavascript",
configuration: {
...(this.configuration as OriginalInputValues),
code,
name,
raw: true,
},
metadata: this.metadata,
};
return [node];
}
} | // here. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L314-L383 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.asProxy | asProxy(): NodeProxy<I, O> {
return new Proxy(this, {
get(target, prop, receiver) {
if (typeof prop === "string") {
const value = new Value(
target as unknown as BuilderNode<InputValues, OutputValues>,
target.#scope as BuilderScope,
prop
);
let method = target[prop as keyof BuilderNode<I, O>] as () => void;
// .to(), .in(), etc. call the original method:
if (method && typeof method === "function")
method = method.bind(target);
// Otherwise, default "method" is to invoke the lambda represented by the value
else
method = ((config?: BuilderNodeConfig) =>
value.invoke(config)).bind(value);
return new Proxy(method, {
get(_, key, __) {
const maybeMethod = Reflect.get(value, key, value);
return typeof maybeMethod === "function"
? maybeMethod.bind(value)
: maybeMethod;
},
ownKeys(_) {
return Reflect.ownKeys(value).filter(
(key) => typeof key === "string"
);
},
});
} else {
return Reflect.get(target, prop, receiver);
}
},
ownKeys(target) {
return [target.#spreadKey()];
},
}) as unknown as NodeProxy<I, O>;
} | // TODO: Hack keys() to make spread work | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L419-L459 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.unProxy | unProxy() {
return this;
} | /**
* Retrieve underlying node from a NodeProxy. Use like this:
*
* if (thing instanceof BuilderNode) { const node = thing.unProxy(); }
*
* @returns A BuilderNode that is not a proxy, but the original BuilderNode.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L468-L470 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.then | then<TResult1 = O, TResult2 = never>(
onfulfilled?: ((value: O) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null
): PromiseLike<TResult1 | TResult2> {
if (this.#scope.serializing())
throw new Error(
`Can't \`await\` on ${this.id} in board declaration. ` +
`Did you mean to use \`code\` instead of \`board\`?`
);
try {
// It's ok to call this multiple times: If it already run it'll only do
// something if new nodes or inputs were added (e.g. between await calls)
this.#scope.invoke(this as unknown as BaseNode).catch((e) => {
if (onrejected)
return Promise.reject(e).catch(this.#scope.asScopeFor(onrejected));
else throw e;
});
return this.#promise.then(
onfulfilled && this.#scope.asScopeFor(onfulfilled),
onrejected && this.#scope.asScopeFor(onrejected)
);
} catch (e) {
if (onrejected)
return Promise.reject(e).catch(this.#scope.asScopeFor(onrejected));
else throw e;
}
} | /**
* Makes the node (and its proxy) act as a Promise, which returns the output
* of the node. This trigger the execution of the graph built up so far.
*
* this.#promise is a Promise that gets resolved with the (first and only the
* first) invoke() call of the node. It is resolved with the outputs.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L483-L510 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderNode.in | in(
inputs:
| NodeProxy<InputValues, Partial<I>>
| InputsMaybeAsValues<I>
| AbstractValue<NodeValue>
) {
if (inputs instanceof BaseNode) {
this.addInputsFromNode(inputs);
} else if (isValue(inputs)) {
this.addInputsFromNode(...inputs.asNodeInput());
} else {
this.addInputsAsValues(inputs as InputsMaybeAsValues<I>);
}
return this.asProxy();
} | // return a proxy object typed with the input types. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/node.ts#L547-L561 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderScope.constructor | constructor(
config: ScopeConfig & {
serialize?: boolean;
parentLambda?: BuilderNode;
} = {}
) {
super(config);
this.#isSerializing = config.serialize ?? false;
this.parentLambdaNode = config.parentLambda;
} | // TODO:BASE, config of subclasses can have more fields | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/scope.ts#L29-L38 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BuilderScope.asScopeFor | asScopeFor<T extends (...args: any[]) => any>(fn: T): T {
return ((...args: unknown[]) => {
const oldScope = swapCurrentContextScope(this);
try {
return fn(...args);
} finally {
swapCurrentContextScope(oldScope);
}
}) as T;
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/scope.ts#L57-L66 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Value.in | in(
inputs:
| BuilderNodeInterface<InputValues, OutputValues>
| AbstractValue<NodeValue>
| InputsMaybeAsValues<InputValues>
) {
let invertedMap = Object.fromEntries(
Object.entries(this.#keymap).map(([fromKey, toKey]) => [toKey, fromKey])
);
if (isValue(inputs)) {
invertedMap = inputs.#remapKeys(invertedMap);
this.#node.addInputsFromNode(
inputs.#node,
invertedMap,
inputs.#constant,
inputs.#schema
);
} else if (isBuilderNodeProxy(inputs)) {
this.#node.addInputsFromNode(inputs.unProxy(), invertedMap);
} else {
this.#node.addInputsAsValues(inputs as InputsMaybeAsValues<InputValues>);
}
} | // node input values type through the chain of values and .as() statements. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/value.ts#L148-L171 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Value.invoke | invoke(config?: BuilderNodeConfig): NodeProxy {
return new BuilderNode("invoke", this.#scope, {
...config,
$board: this,
}).asProxy();
} | // do it and let the runtime throw an error if this wasn't one. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/value.ts#L199-L204 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Value.isUnknown | isUnknown(): AbstractValue<unknown> {
delete this.#schema.type;
return this as unknown as AbstractValue<unknown>;
} | /**
* The following are type-casting methods that are useful when a node type
* returns generic types but we want to narrow the types to what we know they
* are, e.g. a parser node returning the result as raw wires.
*
* This is also a way to define the schema of a board, e.g. by casting input
* wires and what is returned.
*
* Use as `foo.asString()` or `foo.asNumber()`. `isArray` and `isObject` cast
* to generic arrays and objects.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/grammar/value.ts#L218-L221 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | BaseNode.invoke | async invoke(inputs: I, dynamicScope?: Scope): Promise<O> {
const scope = dynamicScope ?? (this.#scope as Scope);
const handler: NodeHandler | undefined =
this.#handler ?? scope.getHandler(this.type);
let result;
const handlerFn =
handler && "invoke" in handler && handler.invoke
? handler.invoke
: typeof handler === "function"
? handler
: undefined;
if (handlerFn) {
result = (await handlerFn(inputs, this)) as O;
} else if (handler && typeof handler !== "function" && handler.graph) {
// TODO: This isn't quite right, but good enough for now. Instead what
// this should be in invoking a graph from a lexical scope in a dynamic
// scope. This requires moving state management into the dyanmic scope.
const graphs = handler.graph.getPinnedNodes();
if (graphs.length !== 1) throw new Error("Expected exactly one graph");
result = (await scope.invokeOneRound(inputs, graphs[0])) as O;
} else {
throw new Error(`Can't find handler for ${this.id}`);
}
return result;
} | // deserialized nodes that require the Builder environment. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/runner/node.ts#L117-L146 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | State.missingInputs | missingInputs(node: AbstractNode): string[] | false {
if (node.incoming.length === 0 && this.haveRun.has(node)) return [];
const requiredKeys = new Set(node.incoming.map((edge) => edge.in));
const presentKeys = new Set([
...Object.keys(node.configuration),
...Object.keys(this.constants.get(node) ?? {}),
]);
for (const [port, values] of (this.inputs.get(node) ?? new Map()).entries())
if (values.length) presentKeys.add(port);
if (this.controlWires.get(node)?.length) presentKeys.add("");
const missingInputs = [...requiredKeys].filter(
(key) => !presentKeys.has(key)
);
return missingInputs.length ? missingInputs : false;
} | /**
* Compute required inputs from edges and compare with present inputs
*
* Required inputs are
* - for all named incoming edges, the presence of any data, irrespective of
* which node they come from
* - at least one of the incoming empty or * wires, if present (TODO: Is that
* correct?)
* - data from at least one node if it already ran
*
* @returns false if none are missing, otherwise string[] of missing inputs.
* NOTE: A node with no incoming wires returns an empty array after first
* run.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/new/runner/state.ts#L53-L70 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | getCompleteChunks | const getCompleteChunks = (pending: string, chunk: string) => {
const asString = `${pending}${chunk}`;
return asString.split("\n\n");
}; | /**
* @license
* Copyright 2024 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/remote/chunk-repair.ts#L7-L10 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | toReanimationState | function toReanimationState(
root: LifecyclePathRegistryEntry<RunStackEntry>,
visits: VisitTracker
): ReanimationState {
function pathToString(path: number[]): string {
return path.join("-");
}
function descend(
entry: LifecyclePathRegistryEntry<RunStackEntry>,
path: number[],
result: ReanimationStateCache
) {
for (const [index, child] of entry.children.entries()) {
if (!child) continue;
const newPath = [...path, index];
if (child.data) {
result[pathToString(path)] = child.data;
}
descend(child, newPath, result);
}
}
const states: ReanimationStateCache = {};
descend(root, [], states);
return { states, visits: visits.visited() };
} | // TODO: Support stream serialization somehow. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/run/lifecycle.ts#L30-L56 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Registry.constructor | constructor(root: LifecyclePathRegistryEntry<Data> = emptyEntry()) {
this.root = root;
} | // parent: LifecyclePathRegistryEntry | null; | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/run/registry.ts#L20-L22 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Traversal.computeMissingInputs | static computeMissingInputs(
heads: Edge[],
inputs: InputValues,
current: NodeDescriptor,
start?: NodeIdentifier
): string[] {
const isStartNode = current.id === start;
const requiredInputs: string[] = isStartNode
? []
: requiredInputsFromEdges(heads);
const inputsWithConfiguration = new Set();
Object.keys(inputs).forEach((key) => inputsWithConfiguration.add(key));
if (current.configuration) {
Object.keys(current.configuration).forEach((key) =>
inputsWithConfiguration.add(key)
);
}
return requiredInputs.filter(
(input) => !inputsWithConfiguration.has(input)
);
} | /**
* Computes the missing inputs for a node. A missing input is an input that is
* required by the node, but is not (yet) available in the current state.
* @param heads All the edges that point to the node.
* @param inputs The input values that will be passed to the node
* @param current The node that is being visited.
* @returns Array of missing input names.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/traversal/index.ts#L32-L52 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | MachineResult.skip | get skip(): boolean {
return this.missingInputs.length > 0;
} | /**
* `true` if the machine decided that the node should be skipped, rather than
* visited.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/traversal/result.ts#L52-L54 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | MachineEdgeState.wireOutputs | wireOutputs(opportunites: Edge[], outputs: OutputValues): void {
// Verify that all edges are from the same node.
if (
opportunites.filter(
(opportunity) => opportunity.from != opportunites[0].from
).length !== 0
)
throw new Error("All opportunities must be from the same node");
opportunites.forEach((opportunity) => {
const to = opportunity.to;
const out = opportunity.out;
const queuesMap = opportunity.constant ? this.constants : this.state;
if (!out) return;
if (out === "*") {
for (const key in outputs) {
const output = outputs[key];
if (output != null && output != undefined)
this.#queueOutput(queuesMap, to, key, output);
}
} else if (opportunity.in) {
const output = outputs[out];
// TODO: Check and document why we don't allow that
if (output != null && output != undefined)
this.#queueOutput(queuesMap, to, opportunity.in, output);
}
});
} | /**
* Processes outputs by wiring them to the destinations according
* to the supplied edges. Assumes that the outputs were generated by
* the from node.
*
* @param opportunites {Edge[]} Edges to process
* @param outputs {OutputValues} Outputs to wire
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/traversal/state.ts#L48-L75 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | MachineEdgeState.getAvailableInputs | getAvailableInputs(nodeId: NodeIdentifier): InputValues {
const result: InputValues = {};
for (const queuesMap of [
this.constants.get(nodeId), // Constants are overwritten by state.
this.state.get(nodeId),
]) {
if (!queuesMap) continue;
for (const [key, queue] of queuesMap.entries()) {
if (queue.length === 0) continue;
result[key] = queue[0];
}
}
return result;
} | /**
* Returns the available inputs for a given node.
*
* @param nodeId {NodeIdentifier} The node to get the inputs for.
* @returns {InputValues} The available inputs.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/traversal/state.ts#L83-L97 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | MachineEdgeState.useInputs | useInputs(nodeId: NodeIdentifier, inputs: InputValues): void {
const queuesMap = this.state.get(nodeId);
if (!queuesMap) return;
for (const key in inputs) {
const queue = queuesMap.get(key);
if (!queue) continue;
queue.shift();
}
} | /**
* Shifts inputs from the queues. Leaves constants as is.
*
* @param nodeId {NodeIdentifier} The node to shift the inputs for.
* @param inputs {InputValues} The inputs that are used.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/traversal/state.ts#L105-L113 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | hashString | function hashString(str: string) {
let hash = 5381;
let i = str.length;
while (i) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}
return hash >>> 0;
} | /**
* Computes a hash for a string using the DJB2 algorithm.
* @param str
* @returns
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/src/utils/hash.ts#L63-L72 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | echo | const echo = (input: string) => input; | // A normal function that will be wrapped. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/kits.ts#L8-L8 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | echo | const echo = (echo_this: string) => echo_this; | // A normal function that will be wrapped. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/kits.ts#L27-L27 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | echo | const echo = (echo_this: string) => {
return { out: echo_this, other: "stuff" };
}; | // A normal function that will be wrapped. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/kits.ts#L59-L61 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | add | const add = (a: number, b: number) => {
return a + b;
}; | // A normal function that will be wrapped. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/kits.ts#L93-L95 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | buildTestGraph | function buildTestGraph(scope: Scope) {
const input = new BaseNode("input", scope);
const noop = new BaseNode("noop", scope);
const output = new BaseNode("output", scope);
noop.addIncomingEdge(input, "foo", "foo");
output.addIncomingEdge(noop, "foo", "bar");
scope.pin(output);
} | // Builds a test graph just using the primitives. | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/new/runner/pinning-scopes.ts#L15-L23 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | neverResolves | async function neverResolves(
promise: Promise<unknown>,
timeout = 100
): Promise<void> {
const timeoutPromise = new Promise<"timeout">((resolve) =>
setTimeout(() => resolve("timeout"), timeout)
);
const result = await Promise.race([promise, timeoutPromise]);
ok(result === "timeout");
} | // Helper function to test that a promise never resolves | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/breadboard/tests/node/file-system/streams.ts#L21-L31 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | simplifyRefNames | function simplifyRefNames(root: JSONSchema7) {
if (root.definitions === undefined) {
return;
}
const aliases = new Map<string, string>();
let nextId = 0;
for (const [oldName, def] of Object.entries(root.definitions)) {
const newName = `def-${nextId++}`;
aliases.set(DEFINITIONS_PREFIX + oldName, DEFINITIONS_PREFIX + newName);
root.definitions[newName] = def;
delete root.definitions[oldName];
}
if (aliases.size === 0) {
return;
}
const visit = (schema: JSONSchema7) => {
if (Array.isArray(schema)) {
for (const item of schema) {
visit(item);
}
} else if (typeof schema === "object" && schema !== null) {
for (const val of Object.values(schema)) {
visit(val);
}
if (schema.$ref !== undefined) {
const alias = aliases.get(schema.$ref);
if (alias !== undefined) {
schema.$ref = alias;
}
}
}
};
visit(root);
} | /**
* Replace all $refs with a simple unique name.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build-code/src/generate.ts#L218-L254 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | cleanUpDefinitions | function cleanUpDefinitions(root: JSONSchema7) {
if (root.definitions === undefined) {
return;
}
const usedRefs = new Set<string>();
const visit = (schema: JSONSchema7) => {
if (Array.isArray(schema)) {
for (const item of schema) {
visit(item);
}
} else if (typeof schema === "object" && schema !== null) {
for (const val of Object.values(schema)) {
visit(val);
}
if (schema.$ref !== undefined) {
usedRefs.add(schema.$ref);
}
}
};
visit(root);
for (const ref of Object.keys(root.definitions)) {
if (!usedRefs.has(DEFINITIONS_PREFIX + ref)) {
delete root.definitions[ref];
}
}
if (Object.keys(root.definitions).length === 0) {
delete root.definitions;
}
} | /**
* Remove any `definitions` that aren't referenced in the schema, and then if
* there are none left, remove `definitions` all together.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build-code/src/generate.ts#L260-L288 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | bindComponentToKit | function bindComponentToKit<
T extends GenericDiscreteComponent | BoardDefinition,
>(definition: T, kitBinding: KitBinding): T {
return new Proxy(definition, {
apply(target, thisArg, args) {
// The instantiate functions for both discrete and board components have
// an optional final argument called `kitBinding`. Normally it is
// undefined, but when called via this proxy we will add the final
// argument. Now those instances know which kit they're from, which helps
// us serialize them.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return target.apply(thisArg, [...args, kitBinding] as any);
},
});
} | /**
* Returns a proxy of a component instance which binds it to a kit.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/internal/kit.ts#L164-L178 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | normalizeBoardInputs | function normalizeBoardInputs(inputs: BoardInit["inputs"]): InputNode[] {
if (Array.isArray(inputs)) {
return inputs;
}
if (isInputNode(inputs)) {
return [inputs];
}
return [inputNode(inputs)];
} | /**
* Normalize the 3 allowed forms for board `inputs` to just 1.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/internal/board/board.ts#L125-L133 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | normalizeBoardOutputs | function normalizeBoardOutputs(outputs: BoardInit["outputs"]): OutputNode[] {
if (Array.isArray(outputs)) {
return outputs;
}
if (isOutputNode(outputs)) {
return [outputs];
}
return [outputNode(outputs)];
} | /**
* Normalize the 3 allowed forms for board `outputs` to just 1.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/internal/board/board.ts#L138-L146 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Loopback.resolve | resolve(value: OutputPortReference<T>): void {
if (this.#value !== undefined) {
throw new Error("Loopback has already been resolved");
}
this.#value = value;
} | /**
* Set the value of this Loopback. Throws if this Loopback has already
* been resolved.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/internal/board/loopback.ts#L63-L68 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | Loopback.value | get value(): OutputPortReference<T> | undefined {
return this.#value;
} | /**
* Get the resolved value, or `undefined` if it has not yet been resolved.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/internal/board/loopback.ts#L73-L75 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | checkInput | function checkInput<T extends GenericSpecialInput>(
input: T,
expectedType: BreadboardType,
expectedExamples?: JsonSerializable[]
): T {
assert.equal(input.type, expectedType);
assert.deepEqual(input.examples, expectedExamples);
return input;
} | /* eslint-disable @typescript-eslint/ban-ts-comment */ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/test/input_test.ts#L32-L40 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | assertType | function assertType<T extends { type: BreadboardType }>(
loopback: T,
expected: BreadboardType
): T {
assert.equal(loopback.type, expected);
return loopback;
} | /* eslint-disable @typescript-eslint/ban-ts-comment */ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/build/src/test/loopback_test.ts#L15-L21 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | inferOriginFromHostname | function inferOriginFromHostname(host?: string) {
if (!host) throw new Error("Unable to infer origin: no host");
return host.startsWith("localhost") ? `http://${host}` : `https://${host}`;
} | /**
* This is a gnarly workaround. When used within Express, the origin
* request header is occasionally undefined, so we have to do something
* to get the origin again.
*
* This code naively uses hostname to infer the origin.
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/connection-server/src/api/grant.ts#L148-L151 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | stripCodeBlock | const stripCodeBlock = (code: string) =>
code.replace(/(?:```(?:js|javascript)?\n+)(.*)(?:\n+```)/gms, "$1"); | // https://regex101.com/r/PeEmEW/1 | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/core-kit/src/nodes/run-javascript.ts#L42-L43 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
breadboard | github_2023 | breadboard-ai | typescript | IDBBackend.initialize | async initialize() {
return openDB<Files>(FILES_DB, 1, {
upgrade(db) {
// 1) Initialize `files` store.
const files = db.createObjectStore("files", {
keyPath: ["graphUrl", "path"],
});
files.createIndex(`byGraph`, `graphUrl`);
// 2) Initialize `blobs` store.
db.createObjectStore("blobs", { keyPath: "handle" });
// 4) Initialize `refs` store.
const refs = db.createObjectStore("refs", {
keyPath: ["handle", "path"],
});
refs.createIndex("byPath", "path");
refs.createIndex("byHandle", "handle");
},
});
} | /**
*
* @param url -- the URL of the graph associated
*/ | https://github.com/breadboard-ai/breadboard/blob/5edbb3f0175596ddf9df8ff7a804a9627aea8966/packages/data-store/src/file-system/idb-backend.ts#L75-L95 | 5edbb3f0175596ddf9df8ff7a804a9627aea8966 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.