repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
wordflow | github_2023 | poloclub | typescript | NightjarToast.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L122-L122 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarToast.show | show() {
if (this.isHidden) {
this.isHidden = false;
}
// Hide the element after delay
if (this.duration > 0) {
if (this.timer !== null) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.hide();
}, this.duration);
}
} | /**
* Show the toast message
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L127-L142 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarToast.hide | hide() {
if (this.isHidden) return;
if (this.shadowRoot === null) {
throw Error('Shadow root is null');
}
const toastElement = this.shadowRoot.querySelector('.toast') as HTMLElement;
// Fade the element first
const fadeOutAnimation = toastElement.animate(
{ opacity: [1, 0] },
{ duration: 200, easing: 'ease-in-out' }
);
// Hide the element after animation
fadeOutAnimation.onfinish = () => {
this.isHidden = true;
};
} | /**
* Hide the toast message
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L147-L165 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarToast.render | render() {
let curIcon = SUCCESS_SVG;
if (this.type === 'warning') {
curIcon = WARN_SVG;
} else if (this.type === 'error') {
curIcon = ERROR_SVG;
}
return html`
<div class="toast" toast-type=${this.type} ?is-hidden=${this.isHidden}>
<div class="svg-icon">${curIcon}</div>
<div class="message">${this.message}</div>
<div
class="svg-icon cross-icon"
@click=${() => {
this.hide();
}}
>
${CROSS_SVG}
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L178-L200 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.restoreFromStorage | async restoreFromStorage() {
// Restore the local prompts
const promptKeys = (await get(`${PREFIX}-keys`)) as string[] | undefined;
if (promptKeys !== undefined) {
this.promptKeys = [];
this.localPrompts = [];
this.promptKeys = promptKeys;
for (const key of this.promptKeys) {
const prompt = (await get(`${PREFIX}-${key}`)) as
| PromptDataLocal
| undefined;
if (prompt === undefined) {
throw Error(`Can't access prompt with key ${key}`);
}
this.localPrompts.push(prompt);
}
}
// Restore the fav prompts
const favPromptKeys = (await get(`${PREFIX}-fav-keys`)) as
| [string | null, string | null, string | null]
| undefined;
if (favPromptKeys !== undefined) {
this.favPromptKeys = favPromptKeys;
this.favPrompts = [null, null, null];
for (const [i, key] of this.favPromptKeys.slice(0, 3).entries()) {
if (key !== null) {
const promptIndex = this.promptKeys.indexOf(key);
this.favPrompts[i] = this.localPrompts[promptIndex];
}
}
}
// Notify the consumers
this._broadcastLocalPrompts();
this._broadcastFavPrompts();
} | /**
* Reconstruct the prompts from the local storage.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L67-L107 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.addPrompt | addPrompt(newPrompt: PromptDataLocal) {
this.promptKeys.unshift(newPrompt.key);
this.localPrompts.unshift(newPrompt);
// Save the prompt and new keys in indexed db
set(`${PREFIX}-${newPrompt.key}`, newPrompt);
set(`${PREFIX}-keys`, this.promptKeys);
// If the user is in the search mode, add the new prompt to the search
// result regardless its content
if (this.localPromptsProjection !== null) {
this.localPromptsProjection.unshift(newPrompt);
this._broadcastLocalPromptsProjection();
} else {
this._broadcastLocalPrompts();
}
} | /**
* Add a new prompt
* @param newPrompt New prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L113-L129 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.setPrompt | setPrompt(newPrompt: PromptDataLocal) {
// Find the index of this prompt based on its key
let index = -1;
for (const [i, p] of this.localPrompts.entries()) {
if (p.key === newPrompt.key) {
index = i;
break;
}
}
if (index === -1) {
throw Error(`Can't find they key ${newPrompt.key}.`);
}
this.localPrompts[index] = newPrompt;
// Update the prompt in indexed db
const key = this.promptKeys[index];
set(`${PREFIX}-${key}`, newPrompt);
// If the user is in the search mode, also update the prompt in the search projection
if (this.localPromptsProjection !== null) {
for (const [i, p] of this.localPromptsProjection.entries()) {
if (p.key === newPrompt.key) {
this.localPromptsProjection[i] = newPrompt;
break;
}
}
this._broadcastLocalPromptsProjection();
} else {
this._broadcastLocalPrompts();
}
// If this prompt is a fav prompt, also update them from fav prompts
const allFavIndexes = this.favPromptKeys.reduce(
(
indexes: number[],
currentValue: string | null,
currentIndex: number
) => {
if (currentValue === newPrompt.key) {
indexes.push(currentIndex);
}
return indexes;
},
[]
);
if (allFavIndexes.length !== 0) {
for (const favIndex of allFavIndexes) {
this.favPrompts[favIndex] = newPrompt;
}
this._broadcastFavPrompts();
}
} | /**
* Update the prompt in the localPrompts. This method doesn't change
* the prompt key.
* @param newPrompt New prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L136-L190 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.deletePrompt | deletePrompt(prompt: PromptDataLocal) {
// Find the index of this prompt based on its key
let index = -1;
for (const [i, p] of this.localPrompts.entries()) {
if (p.key === prompt.key) {
index = i;
}
}
if (index === -1) {
throw Error(`Can't find they key ${prompt.key}.`);
}
// Remove it from local prompts
this.localPrompts.splice(index, 1);
this.promptKeys.splice(index, 1);
// Remove the prompt from indexed db
del(`${PREFIX}-${prompt.key}`);
set(`${PREFIX}-keys`, this.promptKeys);
// If the user is in the searching mode, also delete the prompt there if possible
if (this.localPromptsProjection !== null) {
for (const [i, p] of this.localPromptsProjection.entries()) {
if (p.key === prompt.key) {
this.localPromptsProjection.splice(i, 1);
break;
}
}
this._broadcastLocalPromptsProjection();
} else {
this._broadcastLocalPrompts();
}
// If this prompt is a fav prompt, also remove it from fav prompts
const allFavIndexes = this.favPromptKeys.reduce(
(
indexes: number[],
currentValue: string | null,
currentIndex: number
) => {
if (currentValue === prompt.key) {
indexes.push(currentIndex);
}
return indexes;
},
[]
);
if (allFavIndexes.length !== 0) {
for (const favIndex of allFavIndexes) {
this.favPromptKeys[favIndex] = null;
this.favPrompts[favIndex] = null;
}
set(`${PREFIX}-fav-keys`, this.favPromptKeys);
this._broadcastFavPrompts();
}
} | /**
* Delete a prompt in the localPrompts
* @param prompt The prompt to delete
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L196-L255 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.setFavPrompt | setFavPrompt(index: number, newPrompt: PromptDataLocal | null) {
this.favPrompts[index] = newPrompt;
this.favPromptKeys[index] = newPrompt?.key || null;
// Update indexed db
set(`${PREFIX}-fav-keys`, this.favPromptKeys);
this._broadcastFavPrompts();
} | /**
* Update the prompt at the index of favPrompts
* @param index Index of the prompt in favPrompts to update (fav slot index)
* @param newPrompt New prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L262-L270 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.sortPrompts | sortPrompts(order: 'name' | 'created' | 'runCount') {
switch (order) {
case 'name': {
this.localPrompts.sort((a, b) => a.title.localeCompare(b.title));
this.localPromptsProjection?.sort((a, b) =>
a.title.localeCompare(b.title)
);
break;
}
case 'created': {
// Recent prompts at front
this.localPrompts.sort((a, b) => b.created.localeCompare(a.created));
this.localPromptsProjection?.sort((a, b) =>
b.created.localeCompare(a.created)
);
break;
}
case 'runCount': {
this.localPrompts.sort((a, b) => b.promptRunCount - a.promptRunCount);
this.localPromptsProjection?.sort(
(a, b) => b.promptRunCount - a.promptRunCount
);
break;
}
default: {
throw Error(`Unknown order ${order}`);
}
}
this.promptKeys = this.localPrompts.map(d => d.key);
set(`${PREFIX}-keys`, this.promptKeys);
if (this.localPromptsProjection !== null) {
// The user is in the search mode
this._broadcastLocalPromptsProjection();
} else {
this._broadcastLocalPrompts();
}
} | /**
* Sort the local prompts by an order
* @param order Order of the new local prompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L276-L317 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager.searchPrompt | searchPrompt(query: string) {
if (query === '') {
// Cancel the search
this.localPromptsProjection = null;
this._broadcastLocalPrompts();
} else {
// Create a projection of the local prompts that only include search results
this.localPromptsProjection = [];
const queryLower = query.toLowerCase();
for (const prompt of this.localPrompts) {
const promptInfoString = this._getPromptString(prompt);
if (promptInfoString.includes(queryLower)) {
this.localPromptsProjection.push(prompt);
}
}
this._broadcastLocalPromptsProjection();
}
} | /**
* Search all prompts and only show prompts including the query
* @param query Search query
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L323-L342 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._cleanStorage | _cleanStorage() {
clear();
} | /**
* Remove all local storage set by PromptManager.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L347-L349 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._syncStorage | _syncStorage() {
this.promptKeys = [];
for (const [_, prompt] of this.localPrompts.entries()) {
this.promptKeys.push(prompt.key);
set(`${PREFIX}-${prompt.key}`, prompt);
}
this.favPromptKeys = [null, null, null];
for (const prompt of this.favPrompts) {
this.favPromptKeys.push(prompt ? prompt.key : null);
}
set(`${PREFIX}-keys`, this.promptKeys);
set(`${PREFIX}-fav-keys`, this.favPromptKeys);
} | /**
* Sync localPrompts and keys to storage
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L354-L368 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._broadcastLocalPrompts | _broadcastLocalPrompts() {
this.localPromptCount = this.localPrompts.length;
this.localPromptBroadcastCount = this.localPrompts.length;
// const getRandomISODateString = () => {
// const start = new Date('2023-11-01');
// const end = new Date('2023-12-31T23:59:59');
// const randomDate = new Date(
// start.getTime() + Math.random() * (end.getTime() - start.getTime())
// );
// return randomDate.toISOString();
// };
// const newPrompts = structuredClone(this.localPrompts);
// if (DEV_MODE) {
// const prompts = structuredClone(this.localPrompts);
// for (const prompt of prompts) {
// if (prompt.title.toLocaleLowerCase().includes('academic')) {
// newPrompts[1] = prompt;
// }
// if (prompt.title.toLocaleLowerCase().includes('explainer')) {
// newPrompts[0] = prompt;
// }
// if (prompt.title.toLocaleLowerCase().includes('flow')) {
// newPrompts[2] = prompt;
// }
// if (prompt.title.toLocaleLowerCase().includes('japanese')) {
// newPrompts[3] = prompt;
// }
// }
// this.localPromptsUpdateCallback(newPrompts);
// }
// for (const prompt of newPrompts) {
// prompt.created = getRandomISODateString();
// }
// newPrompts[0].promptRunCount = 397;
// newPrompts[1].promptRunCount = 188;
// newPrompts[2].promptRunCount = 80;
// newPrompts[3].promptRunCount = 59;
this.localPromptsUpdateCallback(structuredClone(this.localPrompts));
} | /**
* Pass the localPrompts to consumers as their localPrompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L373-L419 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._broadcastLocalPromptsProjection | _broadcastLocalPromptsProjection() {
if (this.localPromptsProjection === null) {
throw Error('localPromptsProjection is null');
}
this.localPromptCount = this.localPrompts.length;
this.localPromptBroadcastCount = this.localPromptsProjection.length;
this.localPromptsUpdateCallback(
structuredClone(this.localPromptsProjection)
);
} | /**
* Pass the localPromptsProjection to consumers as their localPrompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L424-L433 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._broadcastFavPrompts | _broadcastFavPrompts() {
this.favPromptsUpdateCallback(structuredClone(this.favPrompts));
} | /**
* Pass the favPrompts to consumers as their favPrompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L438-L440 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PromptManager._getPromptString | _getPromptString(prompt: PromptDataLocal) {
const content =
`${prompt.title} ${prompt.prompt} ${prompt.icon} ${prompt.description}
${prompt.recommendedModels} ${prompt.tags}`.toLowerCase();
return content;
} | /**
* Convert a prompt object to string that can be used for search
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/prompt-manager.ts#L445-L450 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager.getPopularTags | async getPopularTags() {
const url = new URL(ENDPOINT);
url.searchParams.append('popularTags', 'true');
const requestOptions: RequestInit = {
method: 'GET',
credentials: 'include'
};
const response = await fetch(url.toString(), requestOptions);
this.popularTags = (await response.json()) as TagData[];
// Filter ou the empty tag
this.popularTags = this.popularTags.filter(d => d.tag !== '');
this._broadcastPopularTags();
} | /**
* Get a list of the most popular tags.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L73-L87 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager.getPromptsByTag | async getPromptsByTag(tag: string, orderMode: 'new' | 'popular') {
const url = new URL(ENDPOINT);
url.searchParams.append('tag', tag);
if (orderMode === 'new') {
url.searchParams.append('mostRecent', 'true');
} else {
url.searchParams.append('mostPopular', 'true');
}
const requestOptions: RequestInit = {
method: 'GET',
credentials: 'include'
};
const response = await fetch(url.toString(), requestOptions);
this.remotePrompts = (await response.json()) as PromptDataRemote[];
// Add random dates and run count in dev mode
// if (DEV_MODE) {
// const shuffler = d3.shuffler(d3.randomLcg(10));
// const rng = d3.randomExponential(1 / 300);
// this.remotePrompts = shuffler(this.remotePrompts);
// const randomRunCounts = Array(this.remotePrompts.length)
// .fill(0)
// .map(() => Math.floor(rng()))
// .sort((a, b) => b - a);
// const toTitleCase = (str: string) => {
// return str.toLowerCase().replace(/(?:^|\s)\w/g, match => {
// return match.toUpperCase();
// });
// };
// for (const [i, prompt] of this.remotePrompts.entries()) {
// if (orderMode === 'popular') {
// prompt.promptRunCount = randomRunCounts[i];
// } else {
// prompt.promptRunCount = random(0, 555);
// }
// prompt.created = getRandomISODateString();
// if (random(1, 10) < 8) {
// prompt.userName = '';
// }
// prompt.title = toTitleCase(prompt.title);
// }
// const oldPrompt = this.remotePrompts[1];
// const oldPrompt2 = this.remotePrompts[3];
// this.remotePrompts[1] = this.remotePrompts[2];
// this.remotePrompts[2] = oldPrompt2;
// this.remotePrompts[3] = oldPrompt;
// for (const p of fakePrompts) {
// if (p.title === 'Improve Academic Writing') {
// const oldCount = this.remotePrompts[0].promptRunCount;
// this.remotePrompts[0] = p;
// this.remotePrompts[0].promptRunCount = oldCount;
// }
// }
// this.remotePrompts[0].promptRunCount = 1497;
// this.remotePrompts[1].promptRunCount = 833;
// this.remotePrompts[2].promptRunCount = 580;
// this.remotePrompts[3].promptRunCount = 505;
// this.remotePrompts[0].icon = 'โ๏ธ';
// this.remotePrompts[1].icon = '๐';
// this.remotePrompts[2].icon = '๐';
// this.remotePrompts[3].icon = '๐ง๐ฝโ๐ป';
// this.remotePrompts[1].title = 'Inspirational Travel Guide';
// this.remotePrompts[2].title = 'Improve Text Flow';
// this.remotePrompts[2].prompt = 'Improve the flow of the following text.';
// this.remotePrompts[2].tags = ['general', 'writing', 'flow'];
// }
// Check if the response is not complete
const isSubset = response.headers.get('x-has-pagination');
this.promptIsSubset = isSubset === 'true';
this._broadcastRemotePrompts();
} | /**
* Query prompts based on tags.
* @param tag A tag string. If tag is '', query all prompts.
* @param orderMode Prompt query order
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L94-L176 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager.sharePrompt | async sharePrompt(prompt: PromptDataLocal) {
const url = new URL(ENDPOINT);
url.searchParams.append('type', 'prompt');
const promptBody = { ...prompt } as PromptPOSTBody;
delete promptBody.created;
delete promptBody.promptRunCount;
delete promptBody.key;
const requestOptions: RequestInit = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(promptBody),
credentials: 'include'
};
try {
const response = await fetch(url.toString(), requestOptions);
return response.status;
} catch {
return 401;
}
} | /**
* Share a local prompt to the server
* @param prompt Local prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L182-L206 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager.getPrompt | async getPrompt(promptID: string) {
const url = new URL(ENDPOINT);
url.searchParams.append('getPrompt', promptID);
const requestOptions: RequestInit = {
method: 'GET',
credentials: 'include'
};
const response = await fetch(url.toString(), requestOptions);
if (response.status === 200) {
const remotePrompt = (await response.json()) as PromptDataRemote;
return remotePrompt;
} else {
return null;
}
} | /**
* Get a particular prompt
* @param promptID Remote prompt ID
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L212-L228 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager._broadcastRemotePrompts | _broadcastRemotePrompts() {
this.remotePromptsUpdateCallback(structuredClone(this.remotePrompts));
} | /**
* Pass the remotePrompts to consumers as their remotePrompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L233-L235 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager._broadcastPopularTags | _broadcastPopularTags() {
this.popularTagsUpdateCallback(structuredClone(this.popularTags));
} | /**
* Pass the popularTags to consumers as their popularTags
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L240-L242 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | RemotePromptManager._populateRemotePrompts | async _populateRemotePrompts(size: number) {
for (const p of fakePrompts.slice(0, size)) {
await this.sharePrompt(p);
}
} | /**
* Initialize remote servers with fake prompts
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L247-L251 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | getRandomISODateString | const getRandomISODateString = () => {
const start = new Date('2023-01-01'); // January 1, 2023
const end = new Date('2023-12-31T23:59:59'); // December 31, 2023
const randomDate = new Date(
start.getTime() + Math.random() * (end.getTime() - start.getTime())
);
return randomDate.toISOString();
}; | /**
* Generates a random ISO date string in 2023
*
* @returns {string} The generated random ISO date string.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/remote-prompt-manager.ts#L259-L266 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | UserConfigManager._restoreFromStorage | async _restoreFromStorage() {
// Restore the local prompts
const config = (await get(PREFIX)) as UserConfig | undefined;
if (config) {
this.#llmAPIKeys = config.llmAPIKeys;
this.#preferredLLM = config.preferredLLM;
}
this._broadcastUserConfig();
} | /**
* Reconstruct the prompts from the local storage.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/user-config.ts#L99-L107 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | UserConfigManager._syncStorage | async _syncStorage() {
const config = this._constructConfig();
await set(PREFIX, config);
} | /**
* Store the current config to local storage
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/user-config.ts#L112-L115 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | UserConfigManager._constructConfig | _constructConfig(): UserConfig {
const config: UserConfig = {
llmAPIKeys: this.#llmAPIKeys,
preferredLLM: this.#preferredLLM
};
return config;
} | /**
* Create a copy of the user config
* @returns User config
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/user-config.ts#L121-L127 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | UserConfigManager._cleanStorage | async _cleanStorage() {
await del(PREFIX);
} | /**
* Clean the local storage
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/user-config.ts#L132-L134 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | UserConfigManager._broadcastUserConfig | _broadcastUserConfig() {
const newConfig = this._constructConfig();
this.updateUserConfig(newConfig);
} | /**
* Update the public user config
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/user-config.ts#L139-L142 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.constructor | constructor() {
super();
// Set up user info
this.initUserID();
// Set up the local prompt manager
const updateLocalPrompts = (newLocalPrompts: PromptDataLocal[]) => {
this.localPrompts = newLocalPrompts;
};
const updateFavPrompts = (
newFavPrompts: [
PromptDataLocal | null,
PromptDataLocal | null,
PromptDataLocal | null
]
) => {
this.favPrompts = newFavPrompts;
};
this.promptManager = new PromptManager(
updateLocalPrompts,
updateFavPrompts
);
// Set up the remote prompt manager
const updateRemotePrompts = (newRemotePrompts: PromptDataRemote[]) => {
this.remotePrompts = newRemotePrompts;
};
const updatePopularTags = (popularTags: TagData[]) => {
this.popularTags = popularTags;
};
this.remotePromptManager = new RemotePromptManager(
updateRemotePrompts,
updatePopularTags
);
this.initDefaultPrompts();
// Set up the user config store
const updateUserConfig = (userConfig: UserConfig) => {
this.userConfig = userConfig;
};
this.userConfigManager = new UserConfigManager(updateUserConfig);
// We do not collect usage data now
localStorage.setItem('has-confirmed-privacy', 'true');
// Query and show a prompt if the URL includes the prompt search param
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('prompt')) {
const promptID = urlParams.get('prompt')!;
if (validate(promptID)) {
this.remotePromptManager.getPrompt(promptID).then(prompt => {
if (prompt !== null) {
this.showSettingWindow = true;
this.settingWindowComponent.then(window => {
window.showCommunityPrompt(prompt);
});
}
});
}
}
// Initialize the local llm worker
this.textGenLocalWorker = new TextGenLocalWorkerInline();
} | // ===== Lifecycle Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L158-L228 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | updateLocalPrompts | const updateLocalPrompts = (newLocalPrompts: PromptDataLocal[]) => {
this.localPrompts = newLocalPrompts;
}; | // Set up the local prompt manager | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L165-L167 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | updateRemotePrompts | const updateRemotePrompts = (newRemotePrompts: PromptDataRemote[]) => {
this.remotePrompts = newRemotePrompts;
}; | // Set up the remote prompt manager | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L185-L187 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | updateUserConfig | const updateUserConfig = (userConfig: UserConfig) => {
this.userConfig = userConfig;
}; | // Set up the user config store | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L201-L203 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L240-L240 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.updateSidebarMenu | initData = async () => {} | /**
* Update the sidebar menu position and content
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.initDefaultPrompts | initDefaultPrompts() {
let userID = localStorage.getItem('user-id');
if (userID === null) {
console.warn('userID is null');
userID = this.initUserID();
}
// Add some default prompts for the first-time users
const hasAddedDefaultPrompts = localStorage.getItem(
'has-added-default-prompts'
);
if (hasAddedDefaultPrompts === null) {
for (const [_, prompt] of defaultPrompts.entries()) {
// Update some fields
prompt.key = uuidv4();
prompt.userID = userID;
prompt.created = new Date().toISOString();
// prompt.promptRunCount = random(12, 250);
this.promptManager.addPrompt(prompt);
}
// Add the last three as fav prompts
for (const [i, prompt] of defaultPrompts
.reverse()
.slice(0, 3)
.entries()) {
this.promptManager.setFavPrompt(i, prompt);
}
localStorage.setItem('has-added-default-prompts', 'true');
}
} | /**
* Add a few default prompts to the new user's local library.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L259-L291 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.sidebarMenuFooterButtonClickedHandler | sidebarMenuFooterButtonClickedHandler(e: CustomEvent<string>) {
// Delegate the event to the text editor component
if (!this.textEditorElement) return;
this.textEditorElement.sidebarMenuFooterButtonClickedHandler(e);
} | // ===== Event Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L409-L413 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowWordflow.render | render() {
return html`
<div class="wordflow">
<div class="toast-container">
<nightjar-toast
id="toast-wordflow"
message=${this.toastMessage}
type=${this.toastType}
></nightjar-toast>
</div>
<div class="left-panel">
<div class="left-padding"></div>
<div
class="popper-box popper-sidebar-menu hidden"
id="popper-sidebar-box"
>
<wordflow-sidebar-menu
id="right-sidebar-menu"
@footer-button-clicked=${(e: CustomEvent<string>) =>
this.sidebarMenuFooterButtonClickedHandler(e)}
></wordflow-sidebar-menu>
</div>
<div class="right-padding"></div>
</div>
<div class="logo-container">
<div class="center">
<a
class="row"
href="https://github.com/poloclub/wordflow"
target="_blank"
>
<span class="svg-icon">${unsafeHTML(logoIcon)}</span>
<span class="name">Wordflow</span>
</a>
</div>
</div>
<div class="center-panel">
<div class="editor-content">
<wordflow-text-editor
.popperSidebarBox=${this.popperSidebarBox}
.floatingMenuBox=${this.floatingMenuBox}
.updateSidebarMenu=${this.updateSidebarMenu}
.promptManager=${this.promptManager}
.userConfig=${this.userConfig}
.textGenLocalWorker=${this.textGenLocalWorker}
@loading-finished=${() => this.textEditorLoadingFinishedHandler()}
@show-toast=${(e: CustomEvent<ToastMessage>) => {
this.toastMessage = e.detail.message;
this.toastType = e.detail.type;
this.toastComponent?.show();
}}
></wordflow-text-editor>
</div>
</div>
<div class="right-panel">
<div class="top-padding"></div>
<div class="footer-info">
<a
class="row"
href="https://github.com/poloclub/wordflow/"
target="_blank"
><span class="svg-icon">${unsafeHTML(githubIcon)}</span> Code</a
>
<a
class="row"
href="https://arxiv.org/abs/2401.14447"
target="_blank"
><span class="svg-icon">${unsafeHTML(fileIcon)}</span> Paper</a
>
<a class="row" href="https://youtu.be/3dOcVuofGVo" target="_blank"
><span class="svg-icon">${unsafeHTML(youtubeIcon)}</span> Video</a
>
<a
class="row"
href="https://github.com/poloclub/wordflow/issues/new"
target="_blank"
>Report an issue</a
>
<a
class="row"
href="https://github.com/poloclub/wordflow"
target="_blank"
>Version (${packageInfoJSON.version})</a
>
<div
class="row"
@click=${() => {
this.privacyDialogComponent?.show(() => {});
}}
>
Privacy
</div>
</div>
</div>
<div class="floating-menu-box hidden" id="floating-menu-box">
<wordflow-floating-menu
.popperTooltip=${this.popperTooltip}
.loadingActionIndex=${this.loadingActionIndex}
.favPrompts=${this.favPrompts}
@mouse-enter-tools=${() => this.floatingMenuToolMouseEnterHandler()}
@mouse-leave-tools=${() =>
this.floatingMenuToolsMouseLeaveHandler()}
@tool-button-clicked=${(
e: CustomEvent<[PromptDataLocal, number]>
) => this.floatingMenuToolButtonClickHandler(e)}
@setting-button-clicked=${() => {
this.showSettingWindow = true;
}}
></wordflow-floating-menu>
</div>
<wordflow-setting-window
?is-hidden=${!this.showSettingWindow}
.promptManager=${this.promptManager}
.localPrompts=${this.localPrompts}
.favPrompts=${this.favPrompts}
.remotePromptManager=${this.remotePromptManager}
.remotePrompts=${this.remotePrompts}
.popularTags=${this.popularTags}
.userConfigManager=${this.userConfigManager}
.userConfig=${this.userConfig}
.textGenLocalWorker=${this.textGenLocalWorker}
@close-button-clicked=${() => {
this.showSettingWindow = false;
}}
@share-clicked=${(e: CustomEvent<SharePromptMessage>) =>
this.promptEditorShareClicked(e)}
></wordflow-setting-window>
<wordflow-privacy-dialog-simple></wordflow-privacy-dialog-simple>
<div id="popper-tooltip" class="popper-tooltip hidden" role="tooltip">
<span class="popper-content"></span>
<div class="popper-arrow"></div>
</div>
</div>
`;
} | // ===== Templates and Styles ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/wordflow/wordflow.ts#L488-L635 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | startLoadModel | const startLoadModel = async (
model: SupportedLocalModel,
temperature: number
) => {
const curModel = modelMap[model];
// Only use custom conv template for Llama to override the pre-included system
// prompt from WebLLM
let chatOption: webllm.ChatOptions | undefined = undefined;
if (model === SupportedLocalModel['llama-2-7b']) {
chatOption = {
conv_config: CONV_TEMPLATES[model],
conv_template: 'custom'
};
}
engine = webllm.CreateEngine(curModel, {
initProgressCallback: initProgressCallback,
chatOpts: chatOption
});
await engine;
try {
// Send back the data to the main thread
const message: TextGenLocalWorkerMessage = {
command: 'finishLoadModel',
payload: {
model,
temperature
}
};
postMessage(message);
} catch (error) {
// Throw the error to the main thread
const message: TextGenLocalWorkerMessage = {
command: 'error',
payload: {
requestID: 'web-llm',
originalCommand: 'startLoadModel',
message: error as string
}
};
postMessage(message);
}
}; | /**
* Reload a WebLLM model
* @param model Local LLM model
* @param temperature LLM temperature for all subsequent generation
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/llms/web-llm.ts#L151-L197 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | startTextGen | const startTextGen = async (prompt: string, temperature: number) => {
try {
const curEngine = await engine!;
const response = await curEngine.chat.completions.create({
messages: [{ role: 'user', content: prompt }],
n: 1,
max_gen_len: 2048,
// Override temperature to 0 because local models are very unstable
temperature: 0
// logprobs: false
});
// Reset the chat cache to avoid memorizing previous messages
await curEngine.resetChat();
// Send back the data to the main thread
const message: TextGenLocalWorkerMessage = {
command: 'finishTextGen',
payload: {
requestID: 'web-llm',
apiKey: '',
result: response.choices[0].message.content || '',
prompt: prompt,
detail: ''
}
};
postMessage(message);
} catch (error) {
// Throw the error to the main thread
const message: TextGenLocalWorkerMessage = {
command: 'error',
payload: {
requestID: 'web-llm',
originalCommand: 'startTextGen',
message: error as string
}
};
postMessage(message);
}
}; | /**
* Use Web LLM to generate text based on a given prompt
* @param prompt Prompt to give to the PaLM model
* @param temperature Model temperature
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/llms/web-llm.ts#L204-L243 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
vscode-helix | github_2023 | jasonwilliams | typescript | CommandLine.addChar | addChar(helixState: HelixState, char: string): void{
if (char==='\n'){
// when the `enter` key is pressed
this.enter(helixState)
return;
}
this.commandLineText += char;
// display what the user has written in command mode
this.setText(this.commandLineText, helixState);
} | // concatenate each keystroke to a buffer | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/commandLine.ts#L13-L22 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | SearchState.getFlags | getFlags(): string {
if (this.searchString.startsWith('(?i)')) {
return 'gi';
} else if (this.searchString.startsWith('(?-i)')) {
return 'g';
}
return this.searchString === this.searchString.toLowerCase() ? 'gi' : 'g';
} | // https://github.com/helix-editor/helix/issues/4978 | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/search.ts#L20-L28 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | SearchState.addChar | addChar(helixState: HelixState, char: string): void {
if (char === '\n') {
this.enter(helixState);
return;
}
// If we've just started a search, set a marker where we were so we can go back on escape
if (this.searchString === '') {
this.lastActivePosition = helixState.editorState.activeEditor?.selection.active;
}
this.searchString += char;
helixState.commandLine.setText(this.searchString, helixState);
if (helixState.mode === Mode.Select) {
this.findInstancesInRange(helixState);
} else {
this.findInstancesInDocument(helixState);
}
} | /** Add character to search string */ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/search.ts#L46-L64 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | SearchState.backspace | backspace(helixState: HelixState): void {
this.searchString = this.searchString.slice(0, -1);
helixState.commandLine.setText(this.searchString, helixState);
if (this.searchString && helixState.mode === Mode.Select) {
this.findInstancesInRange(helixState);
} else if (this.searchString) {
this.findInstancesInDocument(helixState);
}
} | /** The "type" event handler doesn't pick up backspace so it needs to be dealt with separately */ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/search.ts#L82-L90 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | SearchState.enter | enter(helixState: HelixState): void {
this.searchHistory.push(this.searchString);
this.searchString = '';
helixState.commandLine.setText(this.searchString, helixState);
// Upstream Bug
// Annoyingly, addSelectionToNextFindMatch actually does 2 things.
// For normal search it will put the selection into the search buffer (which is fine)
// But for selection (ctrl+d), it will select the next matching selection (which we don't want)
// We will need to compare the selections, and if they've changed remove the last one
// Cache what we have before calling the commmand
// Add the current selection to the next find match
if (helixState.mode === Mode.SearchInProgress) {
vscode.commands.executeCommand('actions.findWithSelection');
}
if (helixState.mode === Mode.Select) {
// Set a flag to signal we're in select mode, so when we go to search we can search the current selection
// This is a mitigation around https://github.com/jasonwilliams/vscode-helix/issues/5
this.selectModeActive = true;
}
// reset search history index
this.searchHistoryIndex = this.searchHistory.length - 1;
enterNormalMode(helixState);
} | /** Clear search string and return to Normal mode */ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/search.ts#L93-L118 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | SearchState.previousSearchResult | previousSearchResult(helixState: HelixState): void {
if (this.searchHistory.length > 0) {
this.searchString = this.searchHistory[this.searchHistoryIndex] || '';
this.searchHistoryIndex = Math.max(this.searchHistoryIndex - 1, 0); // Add this line
helixState.commandLine.setText(this.searchString, helixState);
this.findInstancesInDocument(helixState);
}
} | /** Go to the previous search result in our search history */ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/search.ts#L166-L173 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | StatusBarImpl.setText | public setText(helixState: HelixState, text: string) {
// Text
text = text.replace(/\n/g, '^M');
if (this.statusBarItem.text !== text) {
this.statusBarItem.text = `${this.statusBarPrefix(helixState)} ${text}`;
}
this.previousMode = helixState.mode;
this.showingDefaultMessage = false;
this.lastMessageTime = new Date();
} | /**
* Updates the status bar text
* @param isError If true, text rendered in red
*/ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/statusBar.ts#L34-L44 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | StatusBarImpl.clear | public clear(helixState: HelixState, force = true) {
if (!this.showingDefaultMessage && !force) {
return;
}
StatusBar.setText(helixState, '');
this.showingDefaultMessage = true;
} | /**
* Clears any messages from the status bar, leaving the default info, such as
* the current mode and macro being recorded.
* @param force If true, will clear even high priority messages like errors.
*/ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/statusBar.ts#L59-L66 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | createInnerMatchHandler | function createInnerMatchHandler(): (
helixState: HelixState,
document: vscode.TextDocument,
position: vscode.Position,
) => vscode.Range | undefined {
return (helixState, document, position) => {
const count = helixState.resolveCount();
// Get all ranges from our position then reduce down to the shortest one
const bracketRange = [
getBracketRange(document, position, '(', ')', count),
getBracketRange(document, position, '{', '}', count),
getBracketRange(document, position, '<', '>', count),
getBracketRange(document, position, '[', ']', count),
].reduce((acc, range) => {
if (range) {
if (!acc) {
return range;
} else {
return range.contains(acc) ? acc : range;
}
} else {
return acc;
}
}, undefined);
return bracketRange?.with(new vscode.Position(bracketRange.start.line, bracketRange.start.character + 1));
};
} | /*
* Implements going to nearest matching brackets from the cursor.
* This will need to call the other `createInnerBracketHandler` functions and get the smallest range from them.
* This should ensure that we're fetching the nearest bracket pair.
**/ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/actions/operator_ranges.ts#L518-L545 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | createOuterMatchHandler | function createOuterMatchHandler(): (
vimState: HelixState,
document: vscode.TextDocument,
position: vscode.Position,
) => vscode.Range | undefined {
return (_, document, position) => {
// Get all ranges from our position then reduce down to the shortest one
const bracketRange = [
getBracketRange(document, position, '(', ')'),
getBracketRange(document, position, '{', '}'),
getBracketRange(document, position, '<', '>'),
getBracketRange(document, position, '[', ']'),
].reduce((acc, range) => {
if (range) {
if (!acc) {
return range;
} else {
return range.contains(acc) ? acc : range;
}
} else {
return acc;
}
}, undefined);
return bracketRange?.with(undefined, new vscode.Position(bracketRange.end.line, bracketRange.end.character + 1));
};
} | /*
* Implements going to nearest matching brackets from the cursor.
* This will need to call the other `createInnerBracketHandler` functions and get the smallest range from them.
* This should ensure that we're fetching the nearest bracket pair.
**/ | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/actions/operator_ranges.ts#L552-L578 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
vscode-helix | github_2023 | jasonwilliams | typescript | isEmptyRange | function isEmptyRange(range: vscode.Range) {
return range.start.line === range.end.line && range.start.character === range.end.character;
} | // detect if a range is covering just a single character | https://github.com/jasonwilliams/vscode-helix/blob/a79c1f022cf82433a6dfa929e31b2295d2be149d/src/actions/operators.ts#L143-L145 | a79c1f022cf82433a6dfa929e31b2295d2be149d |
local-action | github_2023 | github | typescript | checkActionPath | function checkActionPath(value: string): string {
const actionPath: string = path.resolve(value)
try {
// Confirm the value is a directory
if (!fs.statSync(actionPath).isDirectory())
throw new InvalidArgumentError('Action path must be a directory')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
if ('code' in err && err.code === 'ENOENT')
throw new InvalidArgumentError('Action path does not exist')
else throw new InvalidArgumentError(err.message as string)
}
// Save the action path to environment metadata
EnvMeta.actionPath = actionPath
// Confirm there is an `action.yml` or `action.yaml` in the directory and
// save the path to environment metadata
/* istanbul ignore else */
if (fs.existsSync(path.resolve(actionPath, 'action.yml')))
EnvMeta.actionFile = path.resolve(EnvMeta.actionPath, 'action.yml')
else if (fs.existsSync(path.resolve(actionPath, 'action.yaml')))
EnvMeta.actionFile = path.resolve(EnvMeta.actionPath, 'action.yaml')
else
throw new InvalidArgumentError(
'Path must contain an action.yml / action.yaml file'
)
return path.resolve(value)
} | /**
* Checks if the provided action path is valid
*
* @param value The action path
* @returns The resolved action path
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/command.ts#L23-L53 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | checkEntrypoint | function checkEntrypoint(value: string): string {
const entrypoint: string = path.resolve(EnvMeta.actionPath, value)
// Confirm the entrypoint exists
if (!fs.existsSync(entrypoint))
throw new InvalidArgumentError('Entrypoint does not exist')
// Save the action entrypoint to environment metadata
EnvMeta.entrypoint = entrypoint
return entrypoint
} | /**
* Checks if the provided entrypoint is valid
*
* @param value The entrypoint
* @returns The resolved entrypoint path
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/command.ts#L61-L72 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | checkDotenvFile | function checkDotenvFile(value: string): string {
const dotenvFile: string = path.resolve(value)
// Confirm the dotenv file exists
if (!fs.existsSync(dotenvFile))
throw new InvalidArgumentError('Environment file does not exist')
// Save the .env file path to environment metadata
EnvMeta.dotenvFile = dotenvFile
return dotenvFile
} | /**
* Checks if the provided dotenv file is valid
*
* @param value The dotenv file path
* @returns The resolved dotenv file path
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/command.ts#L80-L91 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | scrubQueryParameters | const scrubQueryParameters = (url: string): string => {
const parsed = new URL(url)
parsed.search = ''
return parsed.toString()
} | /**
* @github/local-action Unmodified
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/download/download-artifact.ts#L22-L26 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | exists | async function exists(path: string): Promise<boolean> {
try {
fs.accessSync(path)
return true
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
if (error.code === 'ENOENT') return false
else throw error
}
} | /**
* @github/local-action Unmodified
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/download/download-artifact.ts#L32-L41 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | streamExtract | async function streamExtract(url: string, directory: string): Promise<void> {
let retryCount = 0
while (retryCount < 5) {
try {
await streamExtractExternal(url, directory)
return
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
retryCount++
core.debug(
`Failed to download artifact after ${retryCount} retries due to ${error.message}. Retrying in 5 seconds...`
)
// wait 5 seconds before retrying
await new Promise(resolve => setTimeout(resolve, 5000))
}
}
throw new Error(`Artifact download failed after ${retryCount} retries.`)
} | /**
* @github/local-action Unmodified
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/download/download-artifact.ts#L47-L65 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | resolveOrCreateDirectory | async function resolveOrCreateDirectory(
downloadPath = getGitHubWorkspaceDir()
): Promise<string> {
if (!(await exists(downloadPath))) {
core.debug(
`Artifact destination folder does not exist, creating: ${downloadPath}`
)
fs.mkdirSync(downloadPath, { recursive: true })
} else
core.debug(`Artifact destination folder already exists: ${downloadPath}`)
return downloadPath
} | /**
* @github/local-action Unmodified
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/download/download-artifact.ts#L215-L227 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | filterLatest | function filterLatest(artifacts: Artifact[]): Artifact[] {
artifacts.sort((a, b) => b.id - a.id)
const latestArtifacts: Artifact[] = []
const seenArtifactNames = new Set<string>()
for (const artifact of artifacts) {
if (!seenArtifactNames.has(artifact.name)) {
latestArtifacts.push(artifact)
seenArtifactNames.add(artifact.name)
}
}
return latestArtifacts
} | /**
* @github/local-action Unmodified
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/find/list-artifacts.ts#L137-L148 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | ZipUploadStream._transform | _transform(chunk: any, enc: any, cb: any): void {
cb(null, chunk)
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/upload/zip.ts#L25-L27 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | zipErrorCallback | const zipErrorCallback = (error: any): void => {
core.error('An error has occurred while creating the zip file for upload')
core.info(error)
throw new Error('An error has occurred during zip creation for the artifact')
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/upload/zip.ts#L84-L89 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | zipWarningCallback | const zipWarningCallback = (error: any): void => {
if (error.code === 'ENOENT') {
core.warning(
'ENOENT warning during artifact zip creation. No such file or directory'
)
core.info(error)
} else {
core.warning(
`A non-blocking warning has occurred during artifact zip creation: ${error.code}`
)
core.info(error)
}
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/artifact/internal/upload/zip.ts#L92-L104 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.constructor | constructor() {
this._buffer = ''
} | /**
* @github/local-action Unmodified
*
* Initialize with an empty buffer.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L80-L82 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.filePath | async filePath(): Promise<string> {
// Return the current value, if available.
if (this._filePath) return this._filePath
// Throw if the path is not set/empty.
if (!CoreMeta.stepSummaryPath)
throw new Error(
'Unable to find environment variable for $GITHUB_STEP_SUMMARY. Check if your runtime environment supports job summaries.'
)
try {
// Resolve the full path to the file.
CoreMeta.stepSummaryPath = path.resolve(
process.cwd(),
CoreMeta.stepSummaryPath
)
// If the file does not exist, create it. GitHub Actions runners normally
// create this file automatically. When testing with local-action, we do
// not know if the file already exists.
if (!fs.existsSync(CoreMeta.stepSummaryPath))
fs.writeFileSync(CoreMeta.stepSummaryPath, '', { encoding: 'utf8' })
// Test access to the file (read or write).
fs.accessSync(
CoreMeta.stepSummaryPath,
fs.constants.R_OK | fs.constants.W_OK
)
} catch {
throw new Error(
`Unable to access summary file: '${CoreMeta.stepSummaryPath}'. Check if the file has correct read/write permissions.`
)
}
this._filePath = CoreMeta.stepSummaryPath
return Promise.resolve(this._filePath)
} | /**
* @github/local-action Modified
*
* Finds the summary file path from the environment. Rejects if the
* environment variable is not set/empty or the file does not exist.
*
* @returns Step summary file path.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L92-L128 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.wrap | wrap(
tag: string,
content: string | null,
attrs: { [attribute: string]: string } = {}
): string {
const htmlAttrs: string = Object.entries(attrs)
.map(([key, value]) => ` ${key}="${value}"`)
.join('')
return !content
? `<${tag}${htmlAttrs}>`
: `<${tag}${htmlAttrs}>${content}</${tag}>`
} | /**
* @github/local-action Unmodified
*
* Wraps content in the provided HTML tag and adds any specified attributes.
*
* @param tag HTML tag to wrap. Example: 'html', 'body', 'div', etc.
* @param content The content to wrap within the tag.
* @param attrs A key-value list of HTML attributes to add.
* @returns Content wrapped in an HTML element.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L140-L152 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.write | async write(
options: SummaryWriteOptions = { overwrite: false }
): Promise<Summary> {
// Set the function to call based on the overwrite setting.
const writeFunc = options.overwrite ? fs.writeFileSync : fs.appendFileSync
// If the file does not exist, create it. GitHub Actions runners normally
// create this file automatically. When testing with local-action, we do not
// know if the file already exists.
const filePath: string = await this.filePath()
// Call the write function.
writeFunc(filePath, this._buffer, { encoding: 'utf8' })
// Empty the buffer.
return this.emptyBuffer()
} | /**
* @github/local-action Modified
*
* Writes the buffer to the summary file and empties the buffer. This can
* append (default) or overwrite the file.
*
* @param options Options for the write operation.
* @returns A promise that resolves to the Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L163-L179 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.clear | async clear(): Promise<Summary> {
return this.emptyBuffer().write({ overwrite: true })
} | /**
* @github/local-action Unmodified
*
* Clears the buffer and summary file.
*
* @returns A promise that resolve to the Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L188-L190 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.stringify | stringify(): string {
return this._buffer
} | /**
* @github/local-action Unmodified
*
* Returns the current buffer as a string.
*
* @returns Current buffer contents.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L199-L201 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.isEmptyBuffer | isEmptyBuffer(): boolean {
return this._buffer.length === 0
} | /**
* @github/local-action Unmodified
*
* Returns `true` the buffer is empty, `false` otherwise.
*
* @returns Whether the buffer is empty.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L210-L212 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.emptyBuffer | emptyBuffer(): Summary {
this._buffer = ''
return this
} | /**
* @github/local-action Unmodified
*
* Resets the buffer without writing to the summary file.
*
* @returns The Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L221-L224 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addRaw | addRaw(text: string, addEOL: boolean = false): Summary {
this._buffer += text
return addEOL ? this.addEOL() : this
} | /**
* @github/local-action Unmodified
*
* Adds raw text to the buffer.
*
* @param text The content to add.
* @param addEOL Whether to append `EOL` to the raw text (default: `false`).
*
* @returns The Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L236-L239 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addEOL | addEOL(): Summary {
return this.addRaw(EOL)
} | /**
* @github/local-action Unmodified
*
* Adds the operating system-specific `EOL` marker to the buffer.
*
* @returns The Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L248-L250 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addCodeBlock | addCodeBlock(code: string, lang?: string): Summary {
return this.addRaw(
this.wrap('pre', this.wrap('code', code), lang ? { lang } : {})
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a code block (\<code\>) to the buffer.
*
* @param code Content to render within the code block.
* @param lang Language to use for syntax highlighting.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L261-L265 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addList | addList(items: string[], ordered: boolean = false): Summary {
return this.addRaw(
this.wrap(
ordered ? 'ol' : 'ul',
items.map(item => this.wrap('li', item)).join('')
)
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a list (\<li\>) element to the buffer.
*
* @param items List of items to render.
* @param ordered Whether the list should be ordered.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L276-L283 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addTable | addTable(rows: SummaryTableRow[]): Summary {
return this.addRaw(
this.wrap(
'table',
// The table body consists of a list of rows, each with a list of cells.
rows
.map(row => {
const cells: string = row
.map(cell => {
// Cell is a string, return as-is.
if (typeof cell === 'string') return this.wrap('td', cell)
// Cell is a SummaryTableCell, extract the data and attributes.
return this.wrap(cell.header ? 'th' : 'td', cell.data, {
...(cell.colspan ? { colspan: cell.colspan } : {}),
...(cell.rowspan ? { rowspan: cell.rowspan } : {})
})
})
.join('')
return this.wrap('tr', cells)
})
.join('')
)
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a table (\<table\>) element to the buffer.
*
* @param rows Table rows to render.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L293-L318 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addDetails | addDetails(label: string, content: string): Summary {
return this.addRaw(
this.wrap('details', this.wrap('summary', label) + content)
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a details (\<details\>) element to the buffer.
*
* @param label Text for the \<summary\> element.
* @param content Text for the \<details\> container.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L329-L333 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addImage | addImage(
src: string,
alt: string,
options: SummaryImageOptions = {}
): Summary {
return this.addRaw(
this.wrap('img', null, {
src,
alt,
...(options.width ? { width: options.width } : {}),
...(options.height ? { height: options.height } : {})
})
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds an image (\<img\>) element to the buffer.
*
* @param src Path to the image to embed.
* @param alt Text description of the image.
* @param options Additional image attributes.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L345-L358 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addHeading | addHeading(text: string, level: number | string = 1): Summary {
// If level is a string, attempt to parse it as a number.
const levelAsNum = typeof level === 'string' ? parseInt(level) : level
// If level is less than 1 or greater than 6, default to `h1`.
const tag =
Number.isNaN(levelAsNum) || levelAsNum < 1 || levelAsNum > 6
? 'h1'
: `h${level}`
const element = this.wrap(tag, text)
return this.addRaw(element).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a heading (\<hX\>) element to the buffer.
*
* @param text Heading text to render.
* @param level Heading level. Defaults to `1`.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L369-L381 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addSeparator | addSeparator(): Summary {
return this.addRaw(this.wrap('hr', null)).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a horizontal rule (\<hr\>) element to the buffer.
*
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L390-L392 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addBreak | addBreak(): Summary {
return this.addRaw(this.wrap('br', null)).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a line break (\<br\>) to the buffer.
*
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L401-L403 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addQuote | addQuote(text: string, cite?: string): Summary {
return this.addRaw(
this.wrap('blockquote', text, cite ? { cite } : {})
).addEOL()
} | /**
* @github/local-action Modified
*
* Adds a block quote \<blockquote\> element to the buffer.
*
* @param text Quote text to render.
* @param cite (Optional) Citation URL.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L414-L418 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Summary.addLink | addLink(text: string, href: string): Summary {
return this.addRaw(this.wrap('a', text, { href })).addEOL()
} | /**
* @github/local-action Modified
*
* Adds an anchor (\<a\>) element to the buffer.
*
* @param text Text content to render.
* @param href Hyperlink to the target.
* @returns Summary instance for chaining.
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/core/summary.ts#L429-L431 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
local-action | github_2023 | github | typescript | Context.constructor | constructor() {
this.payload = {}
if (process.env.GITHUB_EVENT_PATH) {
console.log(process.env.GITHUB_EVENT_PATH)
if (existsSync(process.env.GITHUB_EVENT_PATH)) {
this.payload = JSON.parse(
readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })
)
} else {
const path = process.env.GITHUB_EVENT_PATH
process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${EOL}`)
}
}
this.eventName = process.env.GITHUB_EVENT_NAME as string
this.sha = process.env.GITHUB_SHA as string
this.ref = process.env.GITHUB_REF as string
this.workflow = process.env.GITHUB_WORKFLOW as string
this.action = process.env.GITHUB_ACTION as string
this.actor = process.env.GITHUB_ACTOR as string
this.job = process.env.GITHUB_JOB as string
this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT as string, 10)
this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER as string, 10)
this.runId = parseInt(process.env.GITHUB_RUN_ID as string, 10)
/* istanbul ignore next */
this.apiUrl = process.env.GITHUB_API_URL ?? 'https://api.github.com'
/* istanbul ignore next */
this.serverUrl = process.env.GITHUB_SERVER_URL ?? 'https://github.com'
/* istanbul ignore next */
this.graphqlUrl =
process.env.GITHUB_GRAPHQL_URL ?? 'https://api.github.com/graphql'
} | /**
* Hydrate the context from the environment
*/ | https://github.com/github/local-action/blob/9d6078726e3f3abcd0c64f5134629bcf88dcb2c5/src/stubs/github/context.ts#L28-L60 | 9d6078726e3f3abcd0c64f5134629bcf88dcb2c5 |
PI-Assistant | github_2023 | Lucky-183 | typescript | emitTreeLayer | function emitTreeLayer(layer: ReadonlyRangeTree[], colMap: Map<number, number>): string {
const line: string[] = [];
let curIdx: number = 0;
for (const {start, end, count} of layer) {
const startIdx: number = colMap.get(start)!;
const endIdx: number = colMap.get(end)!;
if (startIdx > curIdx) {
line.push(" ".repeat(startIdx - curIdx));
}
line.push(emitRange(count, endIdx - startIdx));
curIdx = endIdx;
}
return line.join("");
} | /**
*
* @param layer Sorted list of disjoint trees.
* @param colMap
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/ascii.ts#L80-L93 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | stringifyFunctionRootRange | function stringifyFunctionRootRange(funcCov: Readonly<FunctionCov>): string {
const rootRange: RangeCov = funcCov.ranges[0];
return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`;
} | /**
* Returns a string representation of the root range of the function.
*
* This string can be used to match function with same root range.
* The string is derived from the start and end offsets of the root range of
* the function.
* This assumes that `ranges` is non-empty (true for valid function coverages).
*
* @param funcCov Function coverage with the range to stringify
* @internal
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts#L118-L121 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | mergeRangeTrees | function mergeRangeTrees(trees: ReadonlyArray<RangeTree>): RangeTree | undefined {
if (trees.length <= 1) {
return trees[0];
}
const first: RangeTree = trees[0];
let delta: number = 0;
for (const tree of trees) {
delta += tree.delta;
}
const children: RangeTree[] = mergeRangeTreeChildren(trees);
return new RangeTree(first.start, first.end, delta, children);
} | /**
* @precondition Same `start` and `end` for all the trees
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts#L167-L178 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.fromSortedRanges | static fromSortedRanges(ranges: ReadonlyArray<RangeCov>): RangeTree | undefined {
let root: RangeTree | undefined;
// Stack of parent trees and parent counts.
const stack: [RangeTree, number][] = [];
for (const range of ranges) {
const node: RangeTree = new RangeTree(range.startOffset, range.endOffset, range.count, []);
if (root === undefined) {
root = node;
stack.push([node, range.count]);
continue;
}
let parent: RangeTree;
let parentCount: number;
while (true) {
[parent, parentCount] = stack[stack.length - 1];
// assert: `top !== undefined` (the ranges are sorted)
if (range.startOffset < parent.end) {
break;
} else {
stack.pop();
}
}
node.delta -= parentCount;
parent.children.push(node);
stack.push([node, range.count]);
}
return root;
} | /**
* @precodition `ranges` are well-formed and pre-order sorted
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts#L24-L51 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.split | split(value: number): RangeTree {
let leftChildLen: number = this.children.length;
let mid: RangeTree | undefined;
// TODO(perf): Binary search (check overhead)
for (let i: number = 0; i < this.children.length; i++) {
const child: RangeTree = this.children[i];
if (child.start < value && value < child.end) {
mid = child.split(value);
leftChildLen = i + 1;
break;
} else if (child.start >= value) {
leftChildLen = i;
break;
}
}
const rightLen: number = this.children.length - leftChildLen;
const rightChildren: RangeTree[] = this.children.splice(leftChildLen, rightLen);
if (mid !== undefined) {
rightChildren.unshift(mid);
}
const result: RangeTree = new RangeTree(
value,
this.end,
this.delta,
rightChildren,
);
this.end = value;
return result;
} | /**
* @precondition `tree.start < value && value < tree.end`
* @return RangeTree Right part
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts#L105-L135 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.toRanges | toRanges(): RangeCov[] {
const ranges: RangeCov[] = [];
// Stack of parent trees and counts.
const stack: [RangeTree, number][] = [[this, 0]];
while (stack.length > 0) {
const [cur, parentCount]: [RangeTree, number] = stack.pop()!;
const count: number = parentCount + cur.delta;
ranges.push({startOffset: cur.start, endOffset: cur.end, count});
for (let i: number = cur.children.length - 1; i >= 0; i--) {
stack.push([cur.children[i], count]);
}
}
return ranges;
} | /**
* Get the range coverages corresponding to the tree.
*
* The ranges are pre-order sorted.
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts#L142-L155 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | emitTreeLayer | function emitTreeLayer(layer: ReadonlyRangeTree[], colMap: Map<number, number>): string {
const line: string[] = [];
let curIdx: number = 0;
for (const {start, end, count} of layer) {
const startIdx: number = colMap.get(start)!;
const endIdx: number = colMap.get(end)!;
if (startIdx > curIdx) {
line.push(" ".repeat(startIdx - curIdx));
}
line.push(emitRange(count, endIdx - startIdx));
curIdx = endIdx;
}
return line.join("");
} | /**
*
* @param layer Sorted list of disjoint trees.
* @param colMap
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/ascii.ts#L80-L93 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | stringifyFunctionRootRange | function stringifyFunctionRootRange(funcCov: Readonly<FunctionCov>): string {
const rootRange: RangeCov = funcCov.ranges[0];
return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`;
} | /**
* Returns a string representation of the root range of the function.
*
* This string can be used to match function with same root range.
* The string is derived from the start and end offsets of the root range of
* the function.
* This assumes that `ranges` is non-empty (true for valid function coverages).
*
* @param funcCov Function coverage with the range to stringify
* @internal
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/merge.ts#L118-L121 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | mergeRangeTrees | function mergeRangeTrees(trees: ReadonlyArray<RangeTree>): RangeTree | undefined {
if (trees.length <= 1) {
return trees[0];
}
const first: RangeTree = trees[0];
let delta: number = 0;
for (const tree of trees) {
delta += tree.delta;
}
const children: RangeTree[] = mergeRangeTreeChildren(trees);
return new RangeTree(first.start, first.end, delta, children);
} | /**
* @precondition Same `start` and `end` for all the trees
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/merge.ts#L167-L178 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.fromSortedRanges | static fromSortedRanges(ranges: ReadonlyArray<RangeCov>): RangeTree | undefined {
let root: RangeTree | undefined;
// Stack of parent trees and parent counts.
const stack: [RangeTree, number][] = [];
for (const range of ranges) {
const node: RangeTree = new RangeTree(range.startOffset, range.endOffset, range.count, []);
if (root === undefined) {
root = node;
stack.push([node, range.count]);
continue;
}
let parent: RangeTree;
let parentCount: number;
while (true) {
[parent, parentCount] = stack[stack.length - 1];
// assert: `top !== undefined` (the ranges are sorted)
if (range.startOffset < parent.end) {
break;
} else {
stack.pop();
}
}
node.delta -= parentCount;
parent.children.push(node);
stack.push([node, range.count]);
}
return root;
} | /**
* @precodition `ranges` are well-formed and pre-order sorted
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts#L24-L51 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.split | split(value: number): RangeTree {
let leftChildLen: number = this.children.length;
let mid: RangeTree | undefined;
// TODO(perf): Binary search (check overhead)
for (let i: number = 0; i < this.children.length; i++) {
const child: RangeTree = this.children[i];
if (child.start < value && value < child.end) {
mid = child.split(value);
leftChildLen = i + 1;
break;
} else if (child.start >= value) {
leftChildLen = i;
break;
}
}
const rightLen: number = this.children.length - leftChildLen;
const rightChildren: RangeTree[] = this.children.splice(leftChildLen, rightLen);
if (mid !== undefined) {
rightChildren.unshift(mid);
}
const result: RangeTree = new RangeTree(
value,
this.end,
this.delta,
rightChildren,
);
this.end = value;
return result;
} | /**
* @precondition `tree.start < value && value < tree.end`
* @return RangeTree Right part
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts#L105-L135 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | RangeTree.toRanges | toRanges(): RangeCov[] {
const ranges: RangeCov[] = [];
// Stack of parent trees and counts.
const stack: [RangeTree, number][] = [[this, 0]];
while (stack.length > 0) {
const [cur, parentCount]: [RangeTree, number] = stack.pop()!;
const count: number = parentCount + cur.delta;
ranges.push({startOffset: cur.start, endOffset: cur.end, count});
for (let i: number = cur.children.length - 1; i >= 0; i--) {
stack.push([cur.children[i], count]);
}
}
return ranges;
} | /**
* Get the range coverages corresponding to the tree.
*
* The ranges are pre-order sorted.
*/ | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts#L142-L155 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
PI-Assistant | github_2023 | Lucky-183 | typescript | buildNullArray | function buildNullArray<T extends { __proto__: null }>(): T {
return { __proto__: null } as T;
} | // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like | https://github.com/Lucky-183/PI-Assistant/blob/2672d66e01ac6d8dedc840a9f23394ca26d6265f/QQMusicApi/node_modules/@jridgewell/trace-mapping/src/by-source.ts#L62-L64 | 2672d66e01ac6d8dedc840a9f23394ca26d6265f |
Microsoft-365-Copilot-Samples | github_2023 | OfficeDev | typescript | TokenValidator.constructor | constructor(options: TokenValidatorOptions) {
if (!options) {
throw new Error("options is required");
}
const cache = options.cache ?? true;
this.client = jwksClient({
cache,
cacheMaxAge: options.cacheMaxAge ?? 24 * 60 * 60 * 1000, // 24 hours in milliseconds
jwksUri: options.jwksUri,
});
if (cache) {
this.cacheWrapper = new TokenCacheWrapper(this.client, options);
this.client.getSigningKey = this.cacheWrapper.getCacheWrapper() as any;
}
} | /**
* Constructs a new instance of TokenValidator.
* @param {Object} options Configuration options for the TokenValidator.
* @param {boolean} [options.cache=true] Whether to cache the JWKS keys.
* @param {number} [options.cacheMaxAge=86400000] The maximum age of the cache in milliseconds (default is 24 hours).
* @param {string} options.jwksUri The URI to fetch the JWKS keys from.
* @throws {Error} If the options parameter is not provided.
*/ | https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/functions/middleware/tokenValidator.ts#L44-L60 | 159c86a02b84a4ebba05ec606411afc76bf9d9ab |
Microsoft-365-Copilot-Samples | github_2023 | OfficeDev | typescript | TokenValidator.validateToken | public async validateToken(token: string, options?: ValidateTokenOptions) {
const decoded = jwt.decode(token, { complete: true });
if (!decoded) {
throw new Error("jwt malformed");
}
// necessary to support multitenant apps
this.updateIssuer(decoded, options);
const key = await this.getSigningKey(decoded.header.kid);
const verifiedToken = jwt.verify(token, key, options) as EntraJwtPayload;
if (!options) {
return verifiedToken;
}
const validators = [
TokenValidator.validateIdtyp,
TokenValidator.validateVer,
TokenValidator.validateScopesAndRoles,
TokenValidator.validateAllowedTenants,
];
validators.forEach((validator) => validator(verifiedToken, options));
return verifiedToken;
} | /**
* Validates a JWT token.
* @param {string} token The JWT token to validate.
* @param {import('jsonwebtoken').VerifyOptions & { complete?: false } & { idtyp?: string, ver?: string, scp?: string[], roles?: string[] }} [options] Validation options.
* @property {string[]} [options.allowedTenants] The allowed tenants for the JWT token. Compared against the 'tid' claim.
* @property {string} [options.idtyp] The expected value of the 'idtyp' claim in the JWT token.
* @property {string[]} [options.roles] Roles expected in the 'roles' claim in the JWT token.
* @property {string[]} [options.scp] Scopes expected in the 'scp' claim in the JWT token.
* @property {string} [options.ver] The expected value of the 'ver' claim in the JWT token.
* @returns {Promise<import('jsonwebtoken').JwtPayload | string>} The decoded and verified JWT token.
* @throws {Error} If the token is invalid or the validation fails.
*/ | https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/functions/middleware/tokenValidator.ts#L74-L99 | 159c86a02b84a4ebba05ec606411afc76bf9d9ab |
Microsoft-365-Copilot-Samples | github_2023 | OfficeDev | typescript | TokenValidator.clearCache | public clearCache() {
this.cacheWrapper?.cache.reset();
} | /**
* Clears the cache used by the TokenValidator.
*/ | https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/functions/middleware/tokenValidator.ts#L155-L157 | 159c86a02b84a4ebba05ec606411afc76bf9d9ab |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.