repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.findServerByModel | public findServerByModel(model: ModelInfo): InferenceServer | undefined {
// check if model backend is supported
const backend: InferenceType = getInferenceType([model]);
const providers: InferenceProvider[] = this.inferenceProviderRegistry
.getByType(backend)
.filter(provider => provider.enable... | /**
* return the first inference server which is using the specific model
* it throws if the model backend is not currently supported
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L109-L119 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.requestCreateInferenceServer | requestCreateInferenceServer(config: InferenceServerConfig): string {
// create a tracking id to put in the labels
const trackingId: string = getRandomString();
config.labels = {
...config.labels,
trackingId: trackingId,
};
const task = this.taskRegistry.createTask('Creating Inference ... | /**
* Creating an inference server can be heavy task (pulling image, uploading model to WSL etc.)
* The frontend cannot wait endlessly, therefore we provide a method returning a tracking identifier
* that can be used to fetch the tasks
*
* @param config the config to use to create the inference server
... | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L130-L176 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.createInferenceServer | async createInferenceServer(config: InferenceServerConfig): Promise<string> {
if (!this.isInitialize()) throw new Error('Cannot start the inference server: not initialized.');
// Get the backend for the model inference server {@link InferenceType}
const backend: InferenceType = getInferenceType(config.mode... | /**
* Given an engineId, it will create an inference server using an InferenceProvider.
* @param config
*
* @return the containerId of the created inference server
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L184-L240 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.updateServerStatus | private updateServerStatus(engineId: string, containerId: string): void {
// Inspect container
containerEngine
.inspectContainer(engineId, containerId)
.then(result => {
const server = this.#servers.get(containerId);
if (server === undefined)
throw new Error('Something went... | /**
* Given an engineId and a containerId, inspect the container and update the servers
* @param engineId
* @param containerId
* @private
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L248-L275 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.watchContainerStatus | private watchContainerStatus(engineId: string, containerId: string): void {
// Update now
this.updateServerStatus(engineId, containerId);
// Create a pulling update for container health check
const intervalId = setInterval(this.updateServerStatus.bind(this, engineId, containerId), 10000);
this.#di... | /**
* Watch for container status changes
* @param engineId
* @param containerId the container to watch out
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L282-L311 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.watchContainerStart | private watchContainerStart(event: ContainerStart): void {
// We might have a start event for an inference server we already know about
if (this.#servers.has(event.id)) return;
containerEngine
.listContainers()
.then(containers => {
const container = containers.find(c => c.Id === event.... | /**
* Listener for container start events
* @param event the event containing the id of the container
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L321-L339 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.retryableRefresh | private retryableRefresh(retry: number = 3): void {
if (retry === 0) {
console.error('Cannot refresh inference servers: retry limit has been reached. Cleaning manager.');
this.cleanDisposables();
this.#servers.clear();
this.#initialized = false;
return;
}
this.refreshInferenceS... | /**
* This non-async utility method is made to retry refreshing the inference server with some delay
* in case of error raised.
*
* @param retry the number of retry allowed
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L347-L365 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.refreshInferenceServers | private async refreshInferenceServers(): Promise<void> {
const containers: ContainerInfo[] = await containerEngine.listContainers();
const filtered = containers.filter(c => c.Labels && LABEL_INFERENCE_SERVER in c.Labels);
// clean existing disposables
this.cleanDisposables();
this.#servers = new Ma... | /**
* Refresh the inference servers by listing all containers.
*
* This method has an important impact as it (re-)create all inference servers
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L372-L414 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.removeInferenceServer | private removeInferenceServer(containerId: string): void {
this.#servers.delete(containerId);
this.notify();
} | /**
* Remove the reference of the inference server
* /!\ Does not delete the corresponding container
* @param containerId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L421-L424 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.deleteInferenceServer | async deleteInferenceServer(containerId: string): Promise<void> {
const server = this.#servers.get(containerId);
if (!server) {
throw new Error(`cannot find a corresponding server for container id ${containerId}.`);
}
try {
// Set status a deleting
this.setInferenceServerStatus(server... | /**
* Delete the InferenceServer instance from #servers and matching container
* @param containerId the id of the container running the Inference Server
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L430-L455 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.startInferenceServer | async startInferenceServer(containerId: string): Promise<void> {
if (!this.isInitialize()) throw new Error('Cannot start the inference server.');
const server = this.#servers.get(containerId);
if (server === undefined) throw new Error(`cannot find a corresponding server for container id ${containerId}.`);
... | /**
* Start an inference server from the container id
* @param containerId the identifier of the container to start
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L461-L484 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.stopInferenceServer | async stopInferenceServer(containerId: string): Promise<void> {
if (!this.isInitialize()) throw new Error('Cannot stop the inference server.');
const server = this.#servers.get(containerId);
if (server === undefined) throw new Error(`cannot find a corresponding server for container id ${containerId}.`);
... | /**
* Stop an inference server from the container id
* @param containerId the identifier of the container to stop
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L490-L515 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.setInferenceServerStatus | private setInferenceServerStatus(containerId: string, status: InferenceServerStatus): void {
const server = this.#servers.get(containerId);
if (server === undefined) throw new Error(`cannot find a corresponding server for container id ${containerId}.`);
this.#servers.set(server.container.containerId, {
... | /**
* Given an containerId, set the status of the corresponding inference server
* @param containerId
* @param status
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L522-L532 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | BuilderManager.dispose | dispose(): void {
// eslint-disable-next-line sonarjs/array-callback-without-return
Array.from(this.controller.values()).every(controller => controller.abort('disposing builder manager'));
} | /**
* On dispose, the builder will abort all current build.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/BuilderManager.ts#L47-L50 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodManager.getAllPods | getAllPods(): Promise<PodInfo[]> {
return containerEngine.listPods();
} | /**
* Utility method to get all the pods
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/PodManager.ts#L74-L76 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodManager.findPodByLabelsValues | async findPodByLabelsValues(requestedLabels: Record<string, string>): Promise<PodInfo | undefined> {
const pods = await this.getAllPods();
return pods.find(pod => {
const labels = pod.Labels;
// eslint-disable-next-line sonarjs/different-types-comparison
if (labels === undefined) return false... | /**
* return the first pod matching the provided labels and their associated value
* @param requestedLabels the labels the pod must be matching
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/PodManager.ts#L82-L96 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodManager.getPodsWithLabels | async getPodsWithLabels(labels: string[]): Promise<PodInfo[]> {
const pods = await this.getAllPods();
return pods.filter(pod => labels.every(label => !!pod.Labels && label in pod.Labels));
} | /**
* return pods containing all the labels provided
* This method does not check for the values, only existence
* @param labels
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/PodManager.ts#L103-L107 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodManager.getHealth | async getHealth(pod: PodInfo): Promise<PodHealth> {
const containerStates: (string | undefined)[] = await Promise.all(
pod.Containers.map(container =>
containerEngine.inspectContainer(pod.engineId, container.Id).then(data => data.State.Health?.Status),
),
);
return getPodHealth(containe... | /**
* Given a pod Info, will fetch the health status of each containing composing it, and
* will return a PodHealth
* @param pod the pod to inspect
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/PodManager.ts#L114-L122 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodManager.getPodById | private async getPodById(id: string): Promise<PodInfo> {
const pods = await this.getAllPods();
const result = pods.find(pod => pod.Id === id);
if (!result) throw new Error(`pod with Id ${id} cannot be found.`);
return result;
} | /**
* This handy method is private as we do not want expose method not providing
* the engineId, but this is required because PodEvent do not provide the engineId
* @param id
* @private
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/recipes/PodManager.ts#L130-L135 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | CancellationTokenRegistry.createCancellationTokenSource | createCancellationTokenSource(func?: () => void): number {
// keep track of this request
this.#callbackId++;
const token = new CancellationTokenSource();
if (func !== undefined) {
token.token.onCancellationRequested(func);
}
// store the callback that will resolve the promise
this.#c... | /**
* Creating a cancellation token.
* @param func an optional function that will be called when the cancel action will be triggered
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/CancellationTokenRegistry.ts#L33-L46 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.removeMessage | removeMessage(conversationId: string, messageId: string): void {
const conversation: Conversation = this.get(conversationId);
conversation.messages = conversation.messages.filter(message => message.id !== messageId);
this.notify();
} | /**
* Remove a message from a conversation
* @param conversationId
* @param messageId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L51-L56 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.update | update(conversationId: string, messageId: string, message: Partial<ChatMessage>): void {
const conversation: Conversation = this.get(conversationId);
const messageIndex = conversation.messages.findIndex(message => message.id === messageId);
if (messageIndex === -1)
throw new Error(`message with id ${... | /**
* Utility method to update a message content in a given conversation
* @param conversationId
* @param messageId
* @param message
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L64-L78 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.completeMessage | completeMessage(conversationId: string, messageId: string): void {
const conversation: Conversation = this.get(conversationId);
const messageIndex = conversation.messages.findIndex(message => message.id === messageId);
if (messageIndex === -1)
throw new Error(`message with id ${messageId} does not ex... | /**
* This method will be responsible for finalizing the message by concatenating all the choices
* @param conversationId
* @param messageId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L102-L120 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.setUsage | setUsage(conversationId: string, messageId: string, usage: ModelUsage | undefined | null): void {
const conversation: Conversation = this.get(conversationId);
const messageIndex = conversation.messages.findIndex(message => message.id === messageId);
if (messageIndex === -1)
throw new Error(`message w... | /**
* Utility method to quickly add a usage to a given a message inside a conversation
* @param conversationId
* @param messageId
* @param usage
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L128-L139 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.appendChoice | appendChoice(conversationId: string, messageId: string, choice: Choice): void {
const conversation: Conversation = this.get(conversationId);
const messageIndex = conversation.messages.findIndex(message => message.id === messageId);
if (messageIndex === -1)
throw new Error(`message with id ${messageId... | /**
* Utility method to quickly add a choice to a given a message inside a conversation
* @param conversationId
* @param messageId
* @param choice
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L147-L158 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ConversationRegistry.submit | submit(conversationId: string, message: Message): void {
const conversation = this.#conversations.get(conversationId);
if (conversation === undefined) throw new Error(`conversation with id ${conversationId} does not exist.`);
this.#conversations.set(conversationId, {
...conversation,
messages: ... | /**
* Utility method to add a new Message to a given conversation
* @param conversationId
* @param message
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/ConversationRegistry.ts#L165-L174 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | NavigationRegistry.readRoute | public readRoute(): string | undefined {
const result: string | undefined = this.#route;
this.#route = undefined;
return result;
} | /**
* This function return the route, and reset it.
* Meaning after read the route is undefined
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/NavigationRegistry.ts#L56-L60 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.constructor | constructor(private webview: Webview) {} | /**
* Constructs a new TaskRegistry.
* @param webview The webview instance to use for communication.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L34-L34 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.get | get(id: string): Task | undefined {
if (this.tasks.has(id)) return this.tasks.get(id);
return undefined;
} | /**
* Retrieves a task by its ID.
* @param id The ID of the task to retrieve.
* @returns The task with the specified ID, or undefined if not found.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L41-L44 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.createTask | createTask(name: string, state: TaskState, labels: { [id: string]: string } = {}): Task {
const task = {
id: `task-${++this.counter}`,
name: name,
state: state,
labels: labels,
};
this.tasks.set(task.id, task);
this.notify();
return task;
} | /**
* Creates a new task.
* @param name The name of the task.
* @param state The initial state of the task.
* @param labels Optional labels for the task.
* @returns The newly created task.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L53-L63 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.updateTask | updateTask(task: Task): void {
if (!this.tasks.has(task.id)) throw new Error(`Task with id ${task.id} does not exist.`);
this.tasks.set(task.id, {
...task,
state: task.error !== undefined ? 'error' : task.state, // enforce error state when error is defined
});
this.notify();
} | /**
* Updates an existing task.
* @param task The task to update.
* @throws Error if the task with the specified ID does not exist.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L70-L77 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.delete | delete(taskId: string): void {
this.deleteAll([taskId]);
} | /**
* Deletes a task by its ID.
* @param taskId The ID of the task to delete.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L83-L85 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.deleteAll | deleteAll(taskIds: string[]): void {
taskIds.forEach(taskId => this.tasks.delete(taskId));
this.notify();
} | /**
* Deletes multiple tasks by their IDs.
* @param taskIds The IDs of the tasks to delete.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L91-L94 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.getTasks | getTasks(): Task[] {
return Array.from(this.tasks.values());
} | /**
* Retrieves all tasks.
* @returns An array of all tasks.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L100-L102 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.getTasksByLabels | getTasksByLabels(requestedLabels: { [key: string]: string }): Task[] {
return this.getTasks().filter(task => this.filter(task, requestedLabels));
} | /**
* Retrieves tasks that match the specified labels.
* @param requestedLabels The labels to match against.
* @returns An array of tasks that match the specified labels.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L109-L111 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.findTaskByLabels | findTaskByLabels(requestedLabels: { [key: string]: string }): Task | undefined {
return this.getTasks().find(task => this.filter(task, requestedLabels));
} | /**
* Return the first task matching all the labels provided
* @param requestedLabels
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L117-L119 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | TaskRegistry.deleteByLabels | deleteByLabels(labels: { [key: string]: string }): void {
this.deleteAll(this.getTasksByLabels(labels).map(task => task.id));
} | /**
* Deletes tasks that match the specified labels.
* @param labels The labels to match against for deletion.
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/registries/TaskRegistry.ts#L136-L138 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | Downloader.getRedirect | protected getRedirect(url: string, location: string): string {
if (URL.canParse(location)) return location;
const origin = new URL(url).origin;
if (URL.canParse(location, origin)) return new URL(location, origin).href;
return location;
} | /**
* This file takes as argument a location, either a full url or a path
* if a path is provided, the url will be used as origin.
* @param url
* @param location
* @protected
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/utils/downloader.ts#L97-L104 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | Uploader.perform | async perform(id: string): Promise<string> {
// Find the uploader for the current operating system
const worker: IWorker<UploaderOptions, string> | undefined = this.#workers.find(w => w.enabled());
// If none are found, we return the current path
if (worker === undefined) {
console.warn('There is... | /**
* Performing the upload action
* @param id tracking id
*
* @return the path to model after the operation (either on the podman machine or local if not compatible)
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/utils/uploader.ts#L47-L99 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | renderForm | async function renderForm(): Promise<RenderResult<any>> {
const renderResult = render(NewInstructLabSession);
if (type === 'skills') {
const useSkills = renderResult.getByTitle('Use Skills');
expect(useSkills).toBeDefined();
await fireEvent.click(useSkills);
}
return renderResult;
... | /**
* This function render the NewInstructLabSession with the radio expected selected (either skills or knowledge
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/frontend/src/pages/NewInstructLabSession.spec.ts#L111-L121 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | getSelectedOption | function getSelectedOption<T>(container: HTMLElement): T | undefined {
const input = container.querySelector('input[name="select-model"][type="hidden"]');
if (!input) throw new Error('input not found');
// eslint-disable-next-line sonarjs/different-types-comparison
if ((input as HTMLInputElement).value === unde... | /**
* Return the selected value
* @param container
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/frontend/src/pages/StartRecipe.spec.ts#L176-L182 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | selectOption | async function selectOption(container: HTMLElement, label: string): Promise<void> {
// first get the select input
const input = screen.getByLabelText('Select Model');
await fireEvent.pointerUp(input); // they are using the pointer up event instead of click.
// get all options available
const items = containe... | /**
* Utility method to select an option in the svelte-select component
* @param container
* @param label
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/frontend/src/pages/StartRecipe.spec.ts#L189-L210 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
openctx | github_2023 | sourcegraph | typescript | generateStreamId | function generateStreamId(): string {
return Math.random().toString(36).slice(2) + Date.now().toString(36)
} | // This function generates a unique ID for each message stream. | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/browser/src/browser-extension/web-extension-api/rpc.ts#L47-L49 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | callBackgroundMethodReturningObservable | function callBackgroundMethodReturningObservable(method: string, args: unknown[]): Observable<unknown> {
const streamId = generateStreamId()
const request: RequestMessage = { streamId, method, args }
return new Observable<unknown>(observer => {
// Set up a listener for messages from the background.... | // This function sends a message and returns an Observable that will emit the responses | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/browser/src/browser-extension/web-extension-api/rpc.ts#L52-L83 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | messageListener | const messageListener = (response: ResponseMessage): void => {
// If the message is on the stream for this call, emit it.
if (response.streamId === streamId) {
switch (response.streamEvent) {
case 'next':
observer.next(response.data)
... | // Set up a listener for messages from the background. | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/browser/src/browser-extension/web-extension-api/rpc.ts#L58-L73 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | getRenderedBoundaryLines | function getRenderedBoundaryLines(): number[] {
const renderedLines = getRenderedLines()
const boundaryLines: number[] = []
for (const [i, line] of renderedLines.entries()) {
if (i === 0 || line === renderedLines.length - 1) {
boundaryLines.push(line)
continue
}
... | /**
* Get the line numbers of the first and last lines (for each sequentially rendered section) that
* are rendered.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/browser/src/contentScript/github/codeView.ts#L224-L242 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | resolveProviderUrisInConfig | function resolveProviderUrisInConfig(
config: vscode.WorkspaceConfiguration,
scope?: vscode.ConfigurationScope,
): ClientConfiguration['providers'] {
const info = config.inspect<ClientConfiguration['providers']>('providers')
if (!info) {
return undefined
}
const merged: NonNullable<Clie... | /**
* Resolve provider URIs in the configuration. For example, if a `.vscode/settings.json` workspace
* folder configuration file references a provider at `../foo.js` or `file://../bar.js`, those URIs
* need to be resolved relative to the `.vscode/settings.json` file.
*
* TODO(sqs): support `${workspaceRoot}` and ... | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/configuration.ts#L28-L113 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | rewriteProviderRelativeFilePaths | function rewriteProviderRelativeFilePaths(
providers: ClientConfiguration['providers'],
fromUri?: vscode.Uri,
): ClientConfiguration['providers'] {
if (!providers || !fromUri) {
return undefined
}
return Object.fromEntries(
Object.entries(providers).ma... | /**
* Allow the use of `../path/to/module.js` and `./path/to/module.js` in the
* `openctx.providers` setting.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/configuration.ts#L43-L65 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | annotationCodeLens | function annotationCodeLens(
doc: vscode.TextDocument,
ann: AnnotationWithRichRange<vscode.Range>,
showHover: ReturnType<typeof createShowHoverCommand>,
): CodeLens {
const range = ann.range ?? new vscode.Range(0, 0, 0, 0)
return {
range,
command: {
title: ann.item.title,... | /** Create a code lens for a single item. */ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/ui/editor/codeLens.ts#L83-L101 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | ErrorReporterController.wrapObservable | public wrapObservable<T, R>(
userAction: UserAction,
providerMethod: (params: T, opts?: ProviderMethodOptions) => Observable<R>,
) {
return (params: T, opts?: ProviderMethodOptions) => {
const errorReporter = this.getErrorReporter(userAction, opts)
if (errorReporter.s... | /**
* wraps providerMethod to ensure it reports errors to the user.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L36-L63 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | ErrorReporterController.wrapPromise | public wrapPromise<T, R>(
userAction: UserAction,
providerMethod: (params: T, opts?: ProviderMethodOptions) => Promise<R>,
) {
return async (params: T, opts?: ProviderMethodOptions) => {
const errorReporter = this.getErrorReporter(userAction, opts)
if (errorReporter.s... | /**
* wraps providerMethod to ensure it reports errors to the user.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L68-L82 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | ErrorReporterController.getErrorReporter | private getErrorReporter(userAction: UserAction, opts?: ProviderMethodOptions) {
// If we are unsure of which providerUri to associate a report with,
// we use this URI.
const defaultProviderUri = opts?.providerUri ?? ''
// We can have multiple providers fail in a call, so we store the
... | /**
* getErrorReporter implements the core reporting state that is shared
* between errorHook, promise and observables. It takes cares to:
*
* - Aggregate errors to only report once
* - Associate errors with a specific providerUri
* - Decide if a notification should be shown.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L92-L147 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | onValue | const onValue = (providerUri: string | undefined) => {
providerUri = providerUri ?? defaultProviderUri
// If we get a value signal we had no errors for this providerUri
errorByUri.set(providerUri, [])
} | // onValue is called when we have succeeded | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L102-L106 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | onError | const onError = (providerUri: string | undefined, error: any) => {
// Append to errors for this providerUri
providerUri = providerUri ?? defaultProviderUri
const errors = errorByUri.get(providerUri) ?? []
errors.push(error)
errorByUri.set(providerUri, errors)
... | // onError is called each time we see an error. | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L109-L118 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | report | const report = () => {
// We may not have reported a value or error for
// defaultProviderUri, so add an empty list so we clear it out.
if (!errorByUri.has(defaultProviderUri)) {
errorByUri.set(defaultProviderUri, [])
}
for (const [providerUri... | // report takes the seen errors so far and decides if they should be | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/errorReporter.ts#L122-L139 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | importCommonJSFromESM | function importCommonJSFromESM(esmSource: string, fakeFilename: string): unknown {
return {
default: requireCommonJSFromString(`cjs-string:${fakeFilename}`, esmToCommonJS(esmSource)),
}
} | /**
* Convert an ESM bundle to CommonJS.
*
* VS Code does not support dynamically import()ing ES modules (see
* https://github.com/microsoft/vscode/issues/130367). But we always want OpenCtx providers to be ES
* modules for consistency. So, we need to rewrite the ESM bundle to CommonJS to import it here.
*
* Not... | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/importHelpers.ts#L37-L41 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | base64Encode | function base64Encode(text: string): string {
const bytes = new TextEncoder().encode(text)
const binString = String.fromCodePoint(...bytes)
return btoa(binString)
} | /**
* See https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem for why we need
* something other than just `btoa` for base64 encoding.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/client/vscode-lib/src/util/importHelpers.ts#L63-L67 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | promiseWithResolvers | function promiseWithResolvers<T>(): {
promise: Promise<T>
resolve: (value: T) => void
reject: (error: any) => void
} {
let resolve: (value: T) => void = () => {}
let reject: (error: any) => void = () => {}
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve
... | /** ESNext will have Promise.withResolvers built in. */ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/lib/client/src/misc/observable.ts#L105-L117 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | isWellKnownNpmUrl | function isWellKnownNpmUrl(url: URL): boolean {
return url.protocol === 'https:' && url.host === 'openctx.org' && url.pathname.startsWith('/npm/')
} | /**
* Matches the https://openctx.org/npm/* service.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/lib/client/src/providerClient/transport/createTransport.ts#L87-L89 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | expectMentionItem | async function expectMentionItem(
params: MentionsParams,
settings: Settings,
mention: Mention,
): Promise<Item> {
const mentions = await devdocs.mentions!(params, settings)
expect(mentions).toContainEqual(mention)
const items = await devdocs.items!({ mention }, settings)
expect(items).toHa... | /**
* Helper which expects a certain mention back and then passes it on to items
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/devdocs/index.test.ts#L166-L182 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | createClient | async function createClient(
nodeCommand: string,
mcpProviderFile: string,
mcpProviderArgs: string[],
): Promise<Client> {
const client = new Client(
{
name: 'mcp-tool',
version: '0.0.1',
},
{
capabilities: {
experimental: {},
... | // Creates a new MCP client specific to the MCP Tools Provider | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/modelcontextprotocoltools/index.ts#L20-L44 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | MCPToolsProxy.meta | async meta(_params: MetaParams, settings: ProviderSettings): Promise<MetaResult> {
const nodeCommand: string = (settings.nodeCommand as string) ?? 'node'
const mcpProviderUri = settings['mcp.provider.uri'] as string
if (!mcpProviderUri) {
this.mcpClient = undefined
return... | // Gets the Metadata for the MCP Tools Provider | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/modelcontextprotocoltools/index.ts#L52-L79 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | MCPToolsProxy.mentions | async mentions?(params: MentionsParams, _settings: ProviderSettings): Promise<MentionsResult> {
if (!this.mcpClient) {
return []
}
const mcpClient = await this.mcpClient
const toolsResp = await mcpClient.listTools()
const { tools } = toolsResp
const mentions:... | // Gets Lists All the tools available in the MCP Provider along with their schemas | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/modelcontextprotocoltools/index.ts#L82-L123 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | MCPToolsProxy.getToolSchema | getToolSchema(toolName: string): any {
return JSON.parse(this.toolSchemas.get(toolName) as string)
} | // Retrieves the schema for a tool from the Map using the tool name as key | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/modelcontextprotocoltools/index.ts#L126-L128 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | MCPToolsProxy.items | async items?(params: ItemsParams, _settings: ProviderSettings): Promise<ItemsResult> {
if (!this.mcpClient) {
return []
}
const mcpClient = await this.mcpClient
const toolName = params.mention?.title
const toolInput = params.mention?.data
// Validates the to... | // Calls the tool with the provided input and returns the result | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/modelcontextprotocoltools/index.ts#L131-L181 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | SlackClient.fetchThreadMessages | private async fetchThreadMessages(channelId: string, threadTs: string): Promise<string | null> {
const allMessages: MessageElement[] = []
try {
let response = await this.client.conversations.replies({ channel: channelId, ts: threadTs })
if (response.messages) {
al... | // ----------- Helper function --------------- | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/slack/client.ts#L164-L186 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | SlackClient.initializeSlackData | public async initializeSlackData() {
await Promise.all([this.initializeAllChannels(), this.initializeUseridMapping()])
} | // ----------- Initialization function --------------- | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/slack/client.ts#L263-L265 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | SlackClient.initializeUseridMapping | private async initializeUseridMapping() {
let nextCursor: string | undefined = undefined
do {
const response = await this.client.users.list({
limit: 1000,
cursor: nextCursor,
})
const userList = response.members ?? []
for (c... | // Initialize the userid mapping from the slack user list | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/slack/client.ts#L268-L286 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | SlackClient.initializeAllChannels | private async initializeAllChannels() {
let allChannels: ChannelInfo[] = []
let cursor: string | undefined
do {
const response = await this.client.conversations.list({
exclude_archived: true,
limit: 1000,
cursor: cursor,
})
... | // Initialize the channel list from the slack channel list | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/slack/client.ts#L289-L310 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | kebabCase | function kebabCase(text: string): string {
return text.replaceAll(/([A-Z])/g, g => `-${g[0].toLowerCase()}`).replace(/^-/, '')
} | /**
* Convert from CamelCase to kebab-case.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/storybook/index.ts#L243-L245 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | tryGetHTMLDocumentTitle | function tryGetHTMLDocumentTitle(html: string): string | undefined {
return html
.match(/<title>(?<title>[^<]+)<\/title>/)
?.groups?.title.replaceAll(/\s+/gm, ' ')
.trim()
} | /**
* Try to get the title of an HTML document, using incomplete regexp parsing for simplicity (because
* this feature is experimental and we don't need robustness yet).
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/provider/web/index.ts#L117-L122 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
openctx | github_2023 | sourcegraph | typescript | getTitle | function getTitle(pageContext: PageContext): null | string {
if (pageContext.pageTitle !== undefined) {
return pageContext.pageTitle
}
const titleConfig = pageContext.configEntries.pageTitle?.[0]
if (!titleConfig) {
return null
}
const pageTitle = titleConfig.configValue
if ... | /**
* Get the page's title if defined, either from the additional data fetched by
* the page's onBeforeRender() hook or from the config.
*/ | https://github.com/sourcegraph/openctx/blob/2fe038e1af38a4b7664312d0a28785f09f20b19d/web/renderer/+title.ts#L16-L41 | 2fe038e1af38a4b7664312d0a28785f09f20b19d |
xtools | github_2023 | chaitin | typescript | isFullscreen | function isFullscreen() {
return (
document.fullscreenElement ||
(document as any).mozFullScreenElement ||
(document as any).webkitFullscreenElement ||
(document as any).msFullscreenElement
);
} | // 检查是否处于全屏状态 | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/MainContent/index.tsx#L50-L57 | 76511710024a704c21840392ef0ed9c01e88aad3 |
xtools | github_2023 | chaitin | typescript | getSizeDiff | function getSizeDiff<T>(prev: Set<T>, next: Set<T>) {
return prev.size === next.size ? prev : next;
} | /**
* Only return `next` when size changed.
* This is only used for elements compare, not a shallow equal!
*/ | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/Watermark/index.tsx#L39-L41 | 76511710024a704c21840392ef0ed9c01e88aad3 |
xtools | github_2023 | chaitin | typescript | getMarkSize | const getMarkSize = (ctx: CanvasRenderingContext2D) => {
let defaultWidth = 120;
let defaultHeight = 64;
if (!image && ctx.measureText) {
ctx.font = `${Number(fontSize)}px ${fontFamily}`;
const contents = Array.isArray(content) ? content : [content];
const sizes = contents.map((item) => {
... | // ============================ Content ============================= | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/Watermark/index.tsx#L129-L149 | 76511710024a704c21840392ef0ed9c01e88aad3 |
xtools | github_2023 | chaitin | typescript | renderWatermark | const renderWatermark = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (ctx) {
const ratio = getPixelRatio();
const [markWidth, markHeight] = getMarkSize(ctx);
const drawCanvas = (
drawContent?: NonNullable<WatermarkProps['content... | // Generate new Watermark content | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/Watermark/index.tsx#L158-L206 | 76511710024a704c21840392ef0ed9c01e88aad3 |
xtools | github_2023 | chaitin | typescript | getClips | function getClips(
content: NonNullable<WatermarkProps['content']> | HTMLImageElement,
rotate: number,
ratio: number,
width: number,
height: number,
font: Required<NonNullable<WatermarkProps['font']>>,
gapX: number,
gapY: number
): [dataURL: string, finalWidth: number, finalHeight: num... | // Get single clips | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/Watermark/useClips.ts#L33-L144 | 76511710024a704c21840392ef0ed9c01e88aad3 |
xtools | github_2023 | chaitin | typescript | getRotatePos | function getRotatePos(x: number, y: number) {
const targetX = x * Math.cos(angle) - y * Math.sin(angle);
const targetY = x * Math.sin(angle) + y * Math.cos(angle);
return [targetX, targetY];
} | // Get boundary of rotated text | https://github.com/chaitin/xtools/blob/76511710024a704c21840392ef0ed9c01e88aad3/src/components/Watermark/useClips.ts#L86-L90 | 76511710024a704c21840392ef0ed9c01e88aad3 |
ticketz | github_2023 | ticketz-oss | typescript | startServer | async function startServer() {
try {
const companies = await Company.findAll();
const sessionPromises = companies.map(async company => {
try {
await StartAllWhatsAppsSessions(company.id);
logger.info(`Started WhatsApp session for company ID: ${company.id}`);
} catch (error) {
... | // Function to start server and initialize services | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/server.ts#L20-L50 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | SimpleObjectCache.constructor | constructor(ttl: number, logger: Logger = null) {
this.ttl = ttl;
this.logger = logger;
this.cache = new Map();
} | /**
* @param ttl Time to live in milliseconds
* @param logger
*/ | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/helpers/simpleObjectCache.ts#L17-L21 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | SimpleObjectCache.set | set(key: string, value: any) {
// If a timer already exists for this key, clear it
if (this.cache.has(key)) {
clearTimeout(this.cache.get(key)!.timer);
this.logger?.debug(`Cache key ${key} was cleared`);
}
// Set a new timer
const timer = setTimeout(() => {
this.cache.delete(key);... | /**
* Set a key-value pair in the cache
* @param key
* @param value
* @returns void
* @example cache.set('foo', 'bar');
* @example cache.set('foo', { bar: 'baz' });
*/ | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/helpers/simpleObjectCache.ts#L31-L47 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | SimpleObjectCache.get | get(key: string) {
const data = this.cache.get(key);
if (!data) {
return null;
}
this.logger?.debug(`Cache key ${key} was accessed`);
return data.value;
} | /**
* Get a value from the cache
* @param key
* @returns The value stored in the cache
* @example cache.get('foo');
*/ | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/helpers/simpleObjectCache.ts#L55-L63 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | CounterManager.incrementCounter | incrementCounter(name: string, amount: number = 1): number {
if (!this.counters[name]) {
this.counters[name] = { name, value: 0 };
}
this.counters[name].value += amount;
return this.counters[name].value;
} | // Function to increment the value of a counter and return the current value | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/libs/counter.ts#L14-L20 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | CounterManager.decrementCounter | decrementCounter(name: string, amount: number = 1): number {
if (this.counters[name]) {
this.counters[name].value -= amount;
if (this.counters[name].value < 0) {
this.counters[name].value = 0; // Ensure the counter doesn't go below zero
}
return th... | // Function to decrement the value of a counter and return the current value | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/libs/counter.ts#L23-L32 | de610068e5263408e97441651373adfb965a7f61 |
ticketz | github_2023 | ticketz-oss | typescript | User.hashPassword | @BeforeUpdate
@BeforeCreate
static hashPassword = async (instance: User): Promise<void> => {
if (instance.password) {
instance.passwordHash = await hash(instance.password, 8);
}
} | // Nova associação | https://github.com/ticketz-oss/ticketz/blob/de610068e5263408e97441651373adfb965a7f61/backend/src/models/User.ts | de610068e5263408e97441651373adfb965a7f61 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | BeautitabPlugin.loadSettings | async loadSettings() {
const data = (await this.loadData()) || {};
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
} | /**
* Load data from disk, stored in data.json in plugin folder
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/main.ts#L67-L70 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | BeautitabPlugin.saveSettings | async saveSettings() {
await this.saveData(this.settings);
} | /**
* Save data to disk, stored in data.json in plugin folder
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/main.ts#L75-L77 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | BeautitabPlugin.versionCheck | async versionCheck() {
const localVersion = process.env.PLUGIN_VERSION;
const stableVersion = await requestUrl(
"https://raw.githubusercontent.com/andrewmcgivery/obsidian-beautitab/main/package.json"
).then(async (res) => {
if (res.status === 200) {
const response = await res.json;
return response.v... | /**
* Check the local plugin version against github. If there is a new version, notify the user.
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/main.ts#L82-L114 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | BeautitabPlugin.onLayoutChange | private onLayoutChange(): void {
const leaf = this.app.workspace.getMostRecentLeaf();
if (leaf?.getViewState().type === "empty") {
leaf.setViewState({
type: BEAUTITAB_REACT_VIEW,
});
}
} | /**
* Hijack new tabs and show Beauitab
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/main.ts#L119-L126 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | BeautitabPlugin.openSwitcherCommand | openSwitcherCommand(command: string): void {
const pluginID = command.split(":")[0];
//@ts-ignore
const plugins = this.app.plugins.plugins;
//@ts-ignore
const internalPlugins = this.app.internalPlugins.plugins;
if (plugins[pluginID] || internalPlugins[pluginID]?.enabled) {
//@ts-ignore
this.app.comma... | /**
* Check if the choosen provider is enabled
* If yes: open it by using executeCommandById
* If no: Notice the user and tell them to enable it in the settings
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/main.ts#L133-L148 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getSeasonalTag | const getSeasonalTag = (date: Date) => {
const month = date.getMonth() + 1;
const day = date.getDate();
const year = date.getFullYear();
// Easter is an edge case cause it's a silly calculation
const easter = getEasterDate(year);
if (isWithinDaysBefore(date, 5, easter)) {
return SEASONAL_THEME.EASTER;
}
swi... | /**
* Given a date, returns a seasonal tag for use in background generation
* @param date
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getBackground.ts#L50-L143 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getBackground | const getBackground = (
backgroundTheme: BackgroundTheme,
customBackground: string,
localBackgrounds: string[]
) => {
switch (backgroundTheme) {
case BackgroundTheme.SEASONS_AND_HOLIDAYS:
const seasonalTag = getSeasonalTag(new Date());
return `https://source.unsplash.com/random?${seasonalTag}&cachetag=${new... | /**
* Gets the background URL based on the theme settings, either for a specific theme, based on the season, or a custom background
* @param backgroundTheme
* @param customBackground
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getBackground.ts#L150-L175 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | flattenBookmarks | const flattenBookmarks = (items: any[]) => {
let flattedBookmarks: any[] = [];
items.forEach((item) => {
if (item.type === "file") {
flattedBookmarks.push(item);
} else if (item.type === "group") {
flattedBookmarks = flattedBookmarks.concat(
flattenBookmarks(item.items)
);
}
});
return flattedB... | /**
* Recursively gets all bookmarks
* @param items
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getBookmarks.ts#L9-L23 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getBookmarksByGroupName | const getBookmarksByGroupName = (title: string, items: any[]) => {
let flattedBookmarks: any[] = [];
items.forEach((item) => {
if (item.type === "group") {
console.log(`Found group with title ${item.title}`);
if (item.title === title) {
console.log("found match!", item.items);
flattedBookmarks = flat... | /**
* Finds a group by name and then returns it's bookmarks
* @param title
* @param items
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getBookmarks.ts#L30-L49 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | flattenBookmarkGroups | const flattenBookmarkGroups = (items: any[], parentPath = null) => {
let flattedGroups: any[] = [];
items.forEach((item) => {
if (item.type === "group") {
const path = parentPath
? `${parentPath}/${item.title}`
: item.title;
flattedGroups.push({ title: item.title, path });
flattedGroups = flattedG... | /**
* Recursive function to return all bookmark groups with their paths
* @param items
* @param parentPath
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getBookmarks.ts#L81-L97 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getEasterDate | const getEasterDate = (year: number) => {
// Step 1: Calculate the Golden Number (GN)
const GN = (year % 19) + 1;
// Step 2: Calculate the Century (C)
const C = Math.floor(year / 100) + 1;
// Step 3: Calculate the X value
const X = Math.floor((3 * C) / 4) - 12;
// Step 4: Calculate the Z value
const Z = Math... | /**
* An incredibly silly calculation to figure out when Easter is. I can't believe this is a thing.
* @param year
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getEasterDate.ts#L5-L45 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getQuote | const getQuote = async (
quoteSource: QUOTE_SOURCE,
customQuotes: CustomQuote[]
) => {
let actualQuoteSource = quoteSource;
let quote = {};
// If set to both, pick one of the two at random
if (quoteSource === QUOTE_SOURCE.BOTH) {
actualQuoteSource = [QUOTE_SOURCE.QUOTEABLE, QUOTE_SOURCE.MY_QUOTES][
Math.flo... | /**
* Based on the configured quoteSource, gets a random quote from Quoteable, a custom quote, or both.
* @param quoteSource
* @param customQuotes
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getQuote.ts#L10-L39 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getTime | const getTime = (timeFormat: TIME_FORMAT) => {
const today = new Date();
let hours;
if (timeFormat === TIME_FORMAT.TWELVE_HOUR) {
hours =
today.getHours() > 12
? today.getHours() - 12
: today.getHours() === 0
? 12
: today.getHours();
} else {
hours = today.getHours().toString().padStart(2, "0... | /**
* Returns the current time in a 00:00 format, either 12-hour or 24-hour
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getTime.ts#L6-L23 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | getTimeOfDayGreeting | const getTimeOfDayGreeting = () => {
const hours = new Date().getHours();
if (hours >= 18 || hours < 5) {
return "Good evening";
} else if (hours >= 12) {
return "Good afternoon";
} else {
return "Good morning";
}
}; | /**
* Depending on the time of the day, returns a greeting like "Good morning"
* @returns
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/React/Utils/getTimeOfDayGreeting.ts#L5-L15 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
obsidian-beautitab | github_2023 | andrewmcgivery | typescript | ChooseImageSuggestModal.getItems | getItems(): TFile[] {
return this.app.vault
.getFiles()
.filter((f) => ["jpg", "jpeg", "png"].includes(f.extension));
} | /**
* Gets all png/jpg images from the vault
*/ | https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/src/ChooseImageSuggestModal/ChooseImageSuggestModal.ts#L22-L26 | 8b796a66bd05e1aaab61b09f48b8a346d323dea7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.