repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
homarr
github_2023
homarr-labs
typescript
LdapClient.bindAsync
public async bindAsync({ distinguishedName, password }: BindOptions) { return await this.client.bind(distinguishedName, password); }
/** * Binds to the LDAP server with the provided distinguishedName and password. * @param distinguishedName distinguishedName to bind to * @param password password to bind with * @returns void */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/providers/credentials/ldap-client.ts#L33-L35
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
LdapClient.searchAsync
public async searchAsync({ base, options }: SearchOptions) { const { searchEntries } = await this.client.search(base, options); return searchEntries.map((entry) => { return { ...objectEntries(entry) .map(([key, value]) => [key, LdapClient.convertEntryPropertyToString(value)] as const) .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {} as Record<string, string>), dn: LdapClient.getEntryDn(entry), } as { [key: string]: string; dn: string; }; }); }
/** * Search for entries in the LDAP server. * @param base base DN to start the search * @param options search options * @returns list of search results */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/providers/credentials/ldap-client.ts#L43-L57
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
LdapClient.getEntryDn
private static getEntryDn(entry: Entry) { try { return decodeURIComponent(entry.dn.replace(/(?<!\\)\\([0-9a-fA-F]{2})/g, "%$1")); } catch { throw new Error(`Cannot resolve distinguishedName for the entry ${entry.dn}`); } }
/** * dn is the only attribute returned with special characters formatted in UTF-8 (Bad for any letters with an accent) * Regex replaces any backslash followed by 2 hex characters with a percentage unless said backslash is preceded by another backslash. * That can then be processed by decodeURIComponent which will turn back characters to normal. * @param entry search entry from ldap * @returns normalized distinguishedName */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/providers/credentials/ldap-client.ts#L76-L82
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
LdapClient.disconnectAsync
public async disconnectAsync() { await this.client.unbind(); }
/** * Disconnects the client from the LDAP server. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/providers/credentials/ldap-client.ts#L87-L89
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => authorizeWithLdapCredentialsAsync(null as unknown as Database, { name: "test", password: "test", });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/providers/test/ldap-authorization.spec.ts#L33-L37
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await adapter.getUserByEmail?.(email);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/auth/test/adapter.spec.ts#L62-L62
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
main
const main = async () => { const sitemapXml = await fetchSitemapAsync(); const sitemapData = parseXml(sitemapXml); const paths = mapSitemapXmlToPaths(sitemapData); // Adding sitemap as it's not in the sitemap.xml and we need it for this file paths.push("/sitemap.xml"); const sitemapPathType = createSitemapPathType(paths); await updateSitemapTypeFileAsync(sitemapPathType); };
/** * This script fetches the sitemap.xml and generates the HomarrDocumentationPath type * which is used for typesafe documentation links */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/definitions/src/docs/codegen.ts#L65-L73
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
SabnzbdIntegration.deleteItemAsync
public async deleteItemAsync({ id, progress }: DownloadClientItem, fromDisk: boolean): Promise<void> { await this.sabNzbApiCallAsync(progress !== 1 ? "queue" : "history", { name: "delete", archive: fromDisk ? "0" : "1", value: id, del_files: fromDisk ? "1" : "0", }); }
//Will stop working as soon as the finished files is moved to completed folder.
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/download-client/sabnzbd/sabnzbd-integration.ts#L94-L101
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
HomeAssistantIntegration.triggerToggleAsync
public async triggerToggleAsync(entityId: string) { try { const response = await this.postAsync("/api/services/homeassistant/toggle", { entity_id: entityId, }); return response.ok; } catch (err) { logger.error(`Failed to fetch from '${this.url("/")}': ${err as string}`); return false; } }
/** * Triggers a toggle action for a specific entity. * * @param entityId - The ID of the entity to toggle. * @returns A boolean indicating whether the toggle action was successful. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/homeassistant/homeassistant-integration.ts#L47-L58
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
HomeAssistantIntegration.getAsync
private async getAsync(path: `/api/${string}`) { return await fetchWithTrustedCertificatesAsync(this.url(path), { headers: this.getAuthHeaders(), }); }
/** * Makes a GET request to the Home Assistant API. * It includes the authorization header with the API key. * @param path full path to the API endpoint * @returns the response from the API */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/homeassistant/homeassistant-integration.ts#L74-L78
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
HomeAssistantIntegration.postAsync
private async postAsync(path: `/api/${string}`, body: Record<string, string>) { return await fetchWithTrustedCertificatesAsync(this.url(path), { headers: this.getAuthHeaders(), body: JSON.stringify(body), method: "POST", }); }
/** * Makes a POST request to the Home Assistant API. * It includes the authorization header with the API key. * @param path full path to the API endpoint * @param body the body of the request * @returns the response from the API */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/homeassistant/homeassistant-integration.ts#L87-L93
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
HomeAssistantIntegration.getAuthHeaders
private getAuthHeaders() { return { Authorization: `Bearer ${this.getSecretValue("apiKey")}`, }; }
/** * Returns the headers required for authorization. * @returns the authorization headers */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/homeassistant/homeassistant-integration.ts#L99-L103
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
JellyfinIntegration.getApiAsync
private async getApiAsync() { const httpsAgent = await createAxiosCertificateInstanceAsync(); if (this.hasSecretValue("apiKey")) { const apiKey = this.getSecretValue("apiKey"); return this.jellyfin.createApi(this.url("/").toString(), apiKey, httpsAgent); } const apiClient = this.jellyfin.createApi(this.url("/").toString(), undefined, httpsAgent); // Authentication state is stored internally in the Api class, so now // requests that require authentication can be made normally. // see https://typescript-sdk.jellyfin.org/#usage await apiClient.authenticateUserByName(this.getSecretValue("username"), this.getSecretValue("password")); return apiClient; }
/** * Constructs an ApiClient synchronously with an ApiKey or asynchronously * with a username and password. * @returns An instance of Api that has been authenticated */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/jellyfin/jellyfin-integration.ts#L69-L82
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
LidarrIntegration.getCalendarEventsAsync
async getCalendarEventsAsync(start: Date, end: Date, includeUnmonitored = true): Promise<CalendarEvent[]> { const url = this.url("/api/v1/calendar", { start, end, unmonitored: includeUnmonitored, }); const response = await fetchWithTrustedCertificatesAsync(url, { headers: { "X-Api-Key": super.getSecretValue("apiKey"), }, }); const lidarrCalendarEvents = await z.array(lidarrCalendarEventSchema).parseAsync(await response.json()); return lidarrCalendarEvents.map((lidarrCalendarEvent): CalendarEvent => { return { name: lidarrCalendarEvent.title, subName: lidarrCalendarEvent.artist.artistName, description: lidarrCalendarEvent.overview, thumbnail: this.chooseBestImageAsURL(lidarrCalendarEvent), date: lidarrCalendarEvent.releaseDate, mediaInformation: { type: "audio", }, links: this.getLinksForLidarrCalendarEvent(lidarrCalendarEvent), }; }); }
/** * Gets the events in the Lidarr calendar between two dates. * @param start The start date * @param end The end date * @param includeUnmonitored When true results will include unmonitored items of the Tadarr library. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/media-organizer/lidarr/lidarr-integration.ts#L26-L53
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
RadarrIntegration.getCalendarEventsAsync
async getCalendarEventsAsync(start: Date, end: Date, includeUnmonitored = true): Promise<CalendarEvent[]> { const url = this.url("/api/v3/calendar", { start, end, unmonitored: includeUnmonitored, }); const response = await fetchWithTrustedCertificatesAsync(url, { headers: { "X-Api-Key": super.getSecretValue("apiKey"), }, }); const radarrCalendarEvents = await z.array(radarrCalendarEventSchema).parseAsync(await response.json()); return radarrCalendarEvents.map((radarrCalendarEvent): CalendarEvent => { const dates = radarrReleaseTypes .map((type) => (radarrCalendarEvent[type] ? { type, date: radarrCalendarEvent[type] } : undefined)) .filter((date) => date) as AtLeastOneOf<Exclude<CalendarEvent["dates"], undefined>[number]>; return { name: radarrCalendarEvent.title, subName: radarrCalendarEvent.originalTitle, description: radarrCalendarEvent.overview, thumbnail: this.chooseBestImageAsURL(radarrCalendarEvent), date: dates[0].date, dates, mediaInformation: { type: "movie", }, links: this.getLinksForRadarrCalendarEvent(radarrCalendarEvent), }; }); }
/** * Gets the events in the Radarr calendar between two dates. * @param start The start date * @param end The end date * @param includeUnmonitored When true results will include unmonitored items of the Tadarr library. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/media-organizer/radarr/radarr-integration.ts#L18-L49
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
ReadarrIntegration.getCalendarEventsAsync
async getCalendarEventsAsync( start: Date, end: Date, includeUnmonitored = true, includeAuthor = true, ): Promise<CalendarEvent[]> { const url = this.url("/api/v1/calendar", { start, end, unmonitored: includeUnmonitored, includeAuthor, }); const response = await fetchWithTrustedCertificatesAsync(url, { headers: { "X-Api-Key": super.getSecretValue("apiKey"), }, }); const readarrCalendarEvents = await z.array(readarrCalendarEventSchema).parseAsync(await response.json()); return readarrCalendarEvents.map((readarrCalendarEvent): CalendarEvent => { return { name: readarrCalendarEvent.title, subName: readarrCalendarEvent.author.authorName, description: readarrCalendarEvent.overview, thumbnail: this.chooseBestImageAsURL(readarrCalendarEvent), date: readarrCalendarEvent.releaseDate, mediaInformation: { type: "audio", }, links: this.getLinksForReadarrCalendarEvent(readarrCalendarEvent), }; }); }
/** * Gets the events in the Lidarr calendar between two dates. * @param start The start date * @param end The end date * @param includeUnmonitored When true results will include unmonitored items of the Tadarr library. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/media-organizer/readarr/readarr-integration.ts#L26-L59
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
SonarrIntegration.getCalendarEventsAsync
async getCalendarEventsAsync(start: Date, end: Date, includeUnmonitored = true): Promise<CalendarEvent[]> { const url = this.url("/api/v3/calendar", { start, end, unmonitored: includeUnmonitored, includeSeries: true, includeEpisodeFile: true, includeEpisodeImages: true, }); const response = await fetchWithTrustedCertificatesAsync(url, { headers: { "X-Api-Key": super.getSecretValue("apiKey"), }, }); const sonarCalendarEvents = await z.array(sonarrCalendarEventSchema).parseAsync(await response.json()); return sonarCalendarEvents.map( (sonarCalendarEvent): CalendarEvent => ({ name: sonarCalendarEvent.title, subName: sonarCalendarEvent.series.title, description: sonarCalendarEvent.series.overview, thumbnail: this.chooseBestImageAsURL(sonarCalendarEvent), date: sonarCalendarEvent.airDateUtc, mediaInformation: { type: "tv", episodeNumber: sonarCalendarEvent.episodeNumber, seasonNumber: sonarCalendarEvent.seasonNumber, }, links: this.getLinksForSonarCalendarEvent(sonarCalendarEvent), }), ); }
/** * Gets the events in the Sonarr calendar between two dates. * @param start The start date * @param end The end date * @param includeUnmonitored When true results will include unmonitored items of the Sonarr library. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/media-organizer/sonarr/sonarr-integration.ts#L16-L48
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
OverseerrIntegration.requestMediaAsync
public async requestMediaAsync(mediaType: "movie" | "tv", id: number, seasons?: number[]): Promise<void> { const url = this.url("/api/v1/request"); const response = await fetchWithTrustedCertificatesAsync(url, { method: "POST", body: JSON.stringify({ mediaType, mediaId: id, seasons, }), headers: { "X-Api-Key": this.getSecretValue("apiKey"), "Content-Type": "application/json", }, }); if (response.status !== 201) { throw new Error( `Status code ${response.status} does not match the expected status code. The request was likely not created. Response: ${await response.text()}`, ); } }
/** * Request a media. See https://api-docs.overseerr.dev/#/request/post_request * @param mediaType The media type to request. Can be "movie" or "tv". * @param id The Overseerr ID of the media to request. * @param seasons A list of the seasons that should be requested. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/src/overseerr/overseerr-integration.ts#L63-L82
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
BaseIntegrationMock.testConnectionAsync
public async testConnectionAsync(): Promise<void> {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/base.spec.ts#L15-L15
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await integration.fakeTestConnectionAsync(props);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/base.spec.ts#L50-L50
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await homeAssistantIntegration.testConnectionAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/home-assistant.spec.ts#L24-L24
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await nzbGetIntegration.testConnectionAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/nzbget.spec.ts#L25-L25
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await nzbGetIntegration.pauseQueueAsync();
// Acts
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/nzbget.spec.ts#L55-L55
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await nzbGetIntegration.resumeQueueAsync();
// Acts
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/nzbget.spec.ts#L73-L73
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
getAsync
const getAsync = async () => await nzbGetIntegration.getClientJobsAndStatusAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/nzbget.spec.ts#L56-L56
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await nzbGetIntegration.deleteItemAsync(item, true);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/nzbget.spec.ts#L128-L128
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await piHoleIntegration.testConnectionAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/pi-hole.spec.ts#L35-L35
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.testConnectionAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L24-L24
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.pauseQueueAsync();
// Acts
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L54-L54
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.resumeQueueAsync();
// Acts
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L72-L72
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
getAsync
const getAsync = async () => await sabnzbdIntegration.getClientJobsAndStatusAsync();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L55-L55
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.pauseItemAsync(item);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L127-L127
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.resumeItemAsync(item);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L147-L147
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await sabnzbdIntegration.deleteItemAsync({ ...item, progress: 0 } as DownloadClientItem, false);
// Act - fromDisk already doesn't work for sabnzbd, so only test deletion itself.
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/integrations/test/sabnzbd.spec.ts#L166-L167
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
createFindCallback
const createFindCallback = <TApp extends OldmarrApp | BookmarkApp>( app: TApp, convertApp: (app: TApp) => DbAppWithoutId, ) => { const oldApp = convertApp(app); return (dbApp: DbAppWithoutId) => oldApp.href === dbApp.href && oldApp.name === dbApp.name && oldApp.iconUrl === dbApp.iconUrl && oldApp.description === dbApp.description; };
/** * Creates a callback to be used in a find method that compares the old app with the new app * @param app either an oldmarr app or a bookmark app * @param convertApp a function that converts the app to a new app * @returns a callback that compares the old app with the new app and returns true if they are the same */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/old-import/src/import-apps.ts#L81-L92
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
addMappingFor
const addMappingFor = <TApp extends OldmarrApp | BookmarkApp>( apps: TApp[], appMappings: AppMapping[], existingAppsWithHref: InferSelectModel<typeof appsTable>[], convertApp: (app: TApp) => DbAppWithoutId, ) => { for (const app of apps) { const previous = appMappings.find(createFindCallback(app, convertApp)); if (previous) { previous.ids.push(app.id); continue; } const existing = existingAppsWithHref.find(createFindCallback(app, convertApp)); if (existing) { appMappings.push({ ids: [app.id], newId: existing.id, name: existing.name, href: existing.href, iconUrl: existing.iconUrl, description: existing.description, exists: true, }); continue; } appMappings.push({ ids: [app.id], newId: createId(), ...convertApp(app), exists: false, }); } };
/** * Adds mappings for the given apps to the appMappings array * @param apps apps to add mappings for * @param appMappings existing app mappings * @param existingAppsWithHref existing apps with href * @param convertApp a function that converts the app to a new app */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/old-import/src/import-apps.ts#L101-L135
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
convertApp
const convertApp = (app: OldmarrApp): DbAppWithoutId => ({ name: app.name, href: app.behaviour.externalUrl === "" ? app.url : app.behaviour.externalUrl, iconUrl: app.appearance.iconUrl, description: app.behaviour.tooltipDescription ?? null, });
/** * Converts an oldmarr app to a new app * @param app oldmarr app * @returns new app */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/old-import/src/import-apps.ts#L142-L147
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
convertBookmarkApp
const convertBookmarkApp = (app: BookmarkApp): DbAppWithoutId => ({ ...app, description: null, });
/** * Converts a bookmark app to a new app * @param app bookmark app * @returns new app */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/old-import/src/import-apps.ts#L154-L157
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
mapProxmoxSecrets
const mapProxmoxSecrets = (decryptedProperties: PreparedIntegration["properties"]) => { const apiToken = decryptedProperties.find((property) => property.field === "apiKey"); if (!apiToken?.value) return []; let splitValues = apiToken.value.split("@"); if (splitValues.length <= 1) return []; const [user, ...rest] = splitValues; splitValues = rest.join("@").split("!"); if (splitValues.length <= 1) return []; const [realm, ...rest2] = splitValues; splitValues = rest2.join("!").split("="); if (splitValues.length <= 1) return []; const [tokenId, ...rest3] = splitValues; const secret = rest3.join("="); return [ { field: "username" as const, value: user, }, { field: "realm" as const, value: realm, }, { field: "tokenId" as const, value: tokenId, }, { field: "apiKey" as const, value: secret, }, ]; };
/** * Proxmox secrets have bee split up from format `user@realm!tokenId=secret` to separate fields */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/old-import/src/mappers/map-integration.ts#L75-L118
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
ChannelSubscriptionTracker.subscribe
public static subscribe(channelName: string, callback: SubscriptionCallback) { logger.debug(`Adding redis channel callback channel='${channelName}'`); // We only want to activate the listener once if (!this.listenerActive) { this.activateListener(); this.listenerActive = true; } const channelSubscriptions = this.subscriptions.get(channelName) ?? new Map<string, SubscriptionCallback>(); const id = randomUUID(); // If there are no subscriptions to the channel, subscribe to it if (channelSubscriptions.size === 0) { logger.debug(`Subscribing to redis channel channel='${channelName}'`); void this.redis.subscribe(channelName); } logger.debug(`Adding redis channel callback channel='${channelName}' id='${id}'`); channelSubscriptions.set(id, callback); this.subscriptions.set(channelName, channelSubscriptions); // Return a function to unsubscribe return () => { logger.debug(`Removing redis channel callback channel='${channelName}' id='${id}'`); const channelSubscriptions = this.subscriptions.get(channelName); if (!channelSubscriptions) return; channelSubscriptions.delete(id); // If there are no subscriptions to the channel, unsubscribe from it if (channelSubscriptions.size >= 1) { return; } logger.debug(`Unsubscribing from redis channel channel='${channelName}'`); void this.redis.unsubscribe(channelName); this.subscriptions.delete(channelName); }; }
/** * Subscribes to a channel. * @param channelName name of the channel * @param callback callback function to be called when a message is received * @returns a function to unsubscribe from the channel */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/redis/src/lib/channel-subscription-tracker.ts#L28-L69
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
ChannelSubscriptionTracker.activateListener
private static activateListener() { logger.debug("Activating listener"); this.redis.on("message", (channel, message) => { const channelSubscriptions = this.subscriptions.get(channel); if (!channelSubscriptions) { logger.warn(`Received message on unknown channel channel='${channel}'`); return; } for (const [id, callback] of channelSubscriptions.entries()) { // Don't log messages from the logging channel as it would create an infinite loop if (channel !== "pubSub:logging") { logger.debug(`Calling subscription callback channel='${channel}' id='${id}'`); } void callback(message); } }); }
/** * Activates the listener for the redis client. */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/redis/src/lib/channel-subscription-tracker.ts#L74-L91
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
getFirstMediaProperty
const getFirstMediaProperty = (feedObject: object) => { for (const mediaProperty of mediaProperties) { let propertyIndex = 0; let objectAtPath: object = feedObject; while (propertyIndex < mediaProperty.path.length) { const key = mediaProperty.path[propertyIndex]; if (key === undefined) { break; } const propertyEntries = Object.entries(objectAtPath); const propertyEntry = propertyEntries.find(([entryKey]) => entryKey === key); if (!propertyEntry) { break; } // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const [_, propertyEntryValue] = propertyEntry; objectAtPath = propertyEntryValue as object; propertyIndex++; } const validationResult = z.string().url().safeParse(objectAtPath); if (!validationResult.success) { continue; } logger.debug(`Found an image in the feed entry: ${validationResult.data}`); return validationResult.data; } return null; };
/** * The RSS and Atom standards are poorly adhered to in most of the web. * We want to show pretty background images on the posts and therefore need to extract * the enclosure (aka. media images). This function uses the dynamic properties defined above * to search through the possible paths and detect valid image URLs. * @param feedObject The object to scan for. * @returns the value of the first path that is found within the object */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/request-handler/src/rss-feeds.ts#L74-L103
d508fd466d942a15196918742f768e57a6971e09
isme-nest-serve
github_2023
zclzone
typescript
PermissionService.remove
async remove(id: number) { const permission = await this.permissionRepo.findOne({ where: { id }, relations: { roles: true }, }); if (!permission) throw new BadRequestException('权限不存在或者已删除'); if (permission.roles?.length) throw new BadRequestException('当前权限存在已授权的角色,不允许删除!'); await this.permissionRepo.remove(permission); return true; }
// TODO 递归删除所有子孙权限
https://github.com/zclzone/isme-nest-serve/blob/c5b9c66d5dbade39a309dbb400a264b48c9d05a6/src/modules/permission/permission.service.ts#L64-L74
c5b9c66d5dbade39a309dbb400a264b48c9d05a6
isme-nest-serve
github_2023
zclzone
typescript
SharedService.handleTree
public handleTree(data: any[], id?: string, parentId?: string, children?: string) { const config = { id: id || 'id', parentId: parentId || 'parentId', childrenList: children || 'children', }; const childrenListMap = {}; const nodeIds = {}; const tree = []; for (const d of data) { const parentId = d[config.parentId]; if (childrenListMap[parentId] == null) { childrenListMap[parentId] = []; } nodeIds[d[config.id]] = d; childrenListMap[parentId].push(d); } for (const d of data) { const parentId = d[config.parentId]; if (nodeIds[parentId] == null) { tree.push(d); } } for (const t of tree) { adaptToChildrenList(t); } function adaptToChildrenList(o) { if (childrenListMap[o[config.id]] !== null) { o[config.childrenList] = childrenListMap[o[config.id]]; } if (o[config.childrenList]) { for (const c of o[config.childrenList]) { adaptToChildrenList(c); } } } return tree; }
/** * 构造树型结构数据 */
https://github.com/zclzone/isme-nest-serve/blob/c5b9c66d5dbade39a309dbb400a264b48c9d05a6/src/shared/shared.service.ts#L16-L58
c5b9c66d5dbade39a309dbb400a264b48c9d05a6
alnitak
github_2023
wangzmgit
typescript
getPartition
const getPartition = async () => { const res = await getPartitionAPI(partitionType); if (res.data.code === statusCode.OK) { partitionList.value = res.data.data.partitions; } }
//所有分区
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/hooks/partition-hooks.ts#L8-L13
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
getPartitionName
const getPartitionName = (id: number) => { const subpartition = partitionList.value.find((item) => { return item.id === id; }) const partition = partitionList.value.find((item) => { return item.id === subpartition?.parentId; }) return `${partition?.name}/${subpartition?.name}`; }
// 获取分区名
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/hooks/partition-hooks.ts#L16-L26
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
sendEmailCodeAsync
const sendEmailCodeAsync = async (email: string, captchaId: string) => { //禁用发送按钮 disabledSend.value = true; try { const res = await sendEmailCodeAPI({ email, captchaId }) if (res.data.code === statusCode.OK) { message.success('发送成功'); //开启倒计时 let count = 0; let tag = setInterval(() => { if (++count >= 60) { clearInterval(tag); disabledSend.value = false; sendBtnText.value = '发送验证码'; return; } sendBtnText.value = `${60 - count}秒`; }, 1000); } else { disabledSend.value = false; } return res.data; } catch { disabledSend.value = false; sendBtnText.value = '发送验证码'; message.error('发送失败'); } }
//通知
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/hooks/send-code-hooks.ts#L12-L39
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
setRouterHistory
const setRouterHistory = async (history: RouteLocationNormalized) => { const index = routerHistory.value.findIndex(item => item.path === history.path); const data = { ...history, }; if (!~index) { routerHistory.value.push(data); } else { routerHistory.value[index] = data; } }
/** * 存储路由历史记录 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/history-store.ts#L22-L32
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
removeRouterHistory
const removeRouterHistory = (index: number) => { const { path: curPath } = router.currentRoute.value; const finalIndex = routerHistory.value.length - 1; // 是否为当前页面 if (curPath === routerHistory.value[index].path) { // 少于等于一个元素,删除后列表为空,跳转到首页 if (routerHistory.value.length <= 1) { router.push("/"); } // 如果为最后一个元素,删除后跳转到前一个元素页面 else if (index === finalIndex) { router.push(routerHistory.value[index - 1].path); } // 不为最后一个元素,即删除后后面还有元素,跳转到后一个元素页面 else { router.push(routerHistory.value[index + 1].path); } } routerHistory.value.splice(index, 1); }
/** * 删除单个路由历史记录 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/history-store.ts#L36-L55
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
clearRouterHistory
const clearRouterHistory = () => { routerHistory.value = []; }
/** * 清除路由历史记录 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/history-store.ts#L60-L62
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
addKeepAliveInclude
const addKeepAliveInclude = (routeName: string) => { if (!keepAliveInclude.value.includes(routeName)) { keepAliveInclude.value.push(routeName); } }
/** 添加keep-alive include字段 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/history-store.ts#L65-L69
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
getMenu
const getMenu = async () => { const res = await getUserMenuAPI(); if (res.data.code === statusCode.OK) { return res.data.data.menus; } return []; }
// 获取路由数据
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/menu-store.ts#L12-L18
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
createMenuList
const createMenuList = async () => { const menus = await getMenu(); // 处理路由 const routerList = asyncRouterHandle(menus); routerList.forEach((item) => { router.addRoute('layout', item); }) // 处理菜单数据 // @ts-ignore list.value = await handelMenu(menus); isMenuLoaded.value = true; }
/** 根据routes创建菜单列表 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/menu-store.ts#L70-L82
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
login
const login = async () => { const { redirect = "/" } = router.currentRoute.value.query; // 获取用户信息 await getUserInfo(); window.$message.success("登陆成功,正在跳转..."); const redirectUrl = decodeURIComponent(redirect as string); router.push(redirectUrl); }
/** 登录 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/user-store.ts#L18-L25
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
logout
const logout = () => { window.$dialog.error({ title: "警告", content: "确认退出账号吗?", negativeText: "取消", positiveText: "确认", onPositiveClick: async () => { await logoutAPI(storageData.get('refreshToken')); storageData.remove("token"); storageData.remove('refreshToken'); router.push({ name: "login" }); window.$message.success("退出账号成功"); }, }); }
/** 登出 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/user-store.ts#L28-L43
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
alnitak
github_2023
wangzmgit
typescript
getUserInfo
const getUserInfo = async () => { const res = await getUserInfoAPI(); if (res.data.code === statusCode.OK) { userInfo.value = res.data.data.userInfo; } const roleRes = await getRoleInfoAPI(); if (roleRes.data.code === statusCode.OK) { homePage.value = roleRes.data.data.role.homePage; } }
/** 获取用户信息 */
https://github.com/wangzmgit/alnitak/blob/6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905/web/admin-client/src/stores/modules/user-store.ts#L46-L56
6e2e0dd5d30ec7325927f23cb65a8f9f2de8c905
holy-loader
github_2023
tomcru
typescript
HolyProgress.constructor
constructor(customSettings?: Partial<HolyProgressProps>) { this.settings = { ...DEFAULTS, ...customSettings }; this.progressN = null; this.bar = null; }
/** * Create a HolyProgress instance. * @param {Partial<HolyProgressProps>} [customSettings] - Optional custom settings to override defaults. */
https://github.com/tomcru/holy-loader/blob/2b4b63b53b3216cdb883653c4f15bea671b23db2/src/HolyProgress.ts#L82-L86
2b4b63b53b3216cdb883653c4f15bea671b23db2
holy-loader
github_2023
tomcru
typescript
HolyProgress.getTransformStrategy
private readonly setTo = (n: number): HolyProgress => { const isStarted = typeof this.progressN === 'number'; n = clamp(n, this.settings.initialPosition, 1); this.progressN = n === 1 ? null : n; const progressBar = this.getOrCreateBar(!isStarted); if (!progressBar) { return this; } repaintElement(progressBar); queue((next) => { if (!this.bar) { return; } Object.assign(this.bar.style, this.barPositionCSS(n), { transition: `all ${this.settings.speed}ms ${this.settings.easing}`, }); if (n === 1) { progressBar.style.transition = 'none'; progressBar.style.opacity = '1'; repaintElement(progressBar); setTimeout(() => { progressBar.style.transition = `all ${this.settings.speed}ms linear`; progressBar.style.opacity = '0'; setTimeout(() => { this.removeBarFromDOM(); next(); }, this.settings.speed); this.removeSpinnerFromDOM(); }, this.settings.speed); } else { setTimeout(next, this.settings.speed); } }); return this; }
/** * Creates and initializes a new progress bar element in the DOM. * It sets up the necessary styles and appends the element to the document body. * @private * @param {boolean} fromStart - Indicates if the bar is created from the start position. * @returns {HTMLElement | null} The created progress bar element, or null if creation fails. */
https://github.com/tomcru/holy-loader/blob/2b4b63b53b3216cdb883653c4f15bea671b23db2/src/HolyProgress.ts
2b4b63b53b3216cdb883653c4f15bea671b23db2
holy-loader
github_2023
tomcru
typescript
HolyLoader
const HolyLoader = ({ color = DEFAULTS.color, initialPosition = DEFAULTS.initialPosition, height = DEFAULTS.height, easing = DEFAULTS.easing, speed = DEFAULTS.speed, zIndex = DEFAULTS.zIndex, boxShadow = DEFAULTS.boxShadow, showSpinner = DEFAULTS.showSpinner, ignoreSearchParams = DEFAULTS.ignoreSearchParams, dir = DEFAULTS.dir, }: HolyLoaderProps): null => { const holyProgressRef = React.useRef<HolyProgress | null>(null); React.useEffect(() => { const startProgress = (): void => { if (holyProgressRef.current === null) { return; } try { holyProgressRef.current.start(); } catch (error) {} }; const stopProgress = (): void => { if (holyProgressRef.current === null) { return; } try { holyProgressRef.current.complete(); } catch (error) {} }; /** * Flag to prevent redundant patching of History API methods. * This is essential to avoid pushState & replaceState increasingly nesting * within patched versions of itself */ let isHistoryPatched = false; /** * Enhances browser history methods (pushState and replaceState) to ensure that the * progress indicator is appropriately halted when navigating through single-page applications */ const stopProgressOnHistoryUpdate = (): void => { if (isHistoryPatched) { return; } const originalPushState = history.pushState.bind(history); history.pushState = (...args) => { const url = args[2]; if ( url && isSamePathname(window.location.href, url) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, url)) ) { originalPushState(...args); return; } stopProgress(); originalPushState(...args); }; // This is crucial for Next.js Link components using the 'replace' prop. const originalReplaceState = history.replaceState.bind(history); history.replaceState = (...args) => { const url = args[2]; if ( url && isSamePathname(window.location.href, url) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, url)) ) { originalReplaceState(...args); return; } stopProgress(); originalReplaceState(...args); }; isHistoryPatched = true; }; /** * Handles click events on anchor tags, starting the progress bar for page navigation. * It checks for various conditions to decide whether to start the progress bar or not. * * @param {MouseEvent} event The mouse event triggered by clicking an anchor tag. */ const handleClick = (event: MouseEvent): void => { try { const target = event.target as HTMLElement; const anchor = target.closest('a'); /** * The target attribute can have custom values which might have the link open in external contexts * Links with custom `target` values, '_blank', '_parent', or '_top' are therefore treated as external. */ const anchorOpensExternally = anchor?.target && anchor.target !== '_self'; if ( anchor === null || anchorOpensExternally || anchor.hasAttribute('download') || event.ctrlKey || event.metaKey || // Skip if URL points to a different domain !isSameHost(window.location.href, anchor.href) || // Skip if URL is a same-page anchor (href="#", href="#top", etc.). isSamePageAnchor(window.location.href, anchor.href) || // Skip if URL uses a non-http/https protocol (mailto:, tel:, etc.). !toAbsoluteURL(anchor.href).startsWith('http') || // Skip if the URL is the same as the current page (isSamePathname(window.location.href, anchor.href) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, anchor.href))) ) { return; } startProgress(); } catch (error) { stopProgress(); } }; try { if (holyProgressRef.current === null) { holyProgressRef.current = new HolyProgress({ color, height, initialPosition, easing, speed, zIndex, boxShadow, showSpinner, dir }); } document.addEventListener('click', handleClick); document.addEventListener(START_HOLY_EVENT, startProgress); document.addEventListener(STOP_HOLY_EVENT, stopProgress); stopProgressOnHistoryUpdate(); } catch (error) {} return () => { document.removeEventListener('click', handleClick); document.removeEventListener(START_HOLY_EVENT, startProgress); document.removeEventListener(STOP_HOLY_EVENT, stopProgress); }; }, [holyProgressRef]); return null; };
/** * HolyLoader is a React component that provides a customizable top-loading progress bar. * * @param {HolyLoaderProps} props The properties for configuring the HolyLoader. * @returns {null} */
https://github.com/tomcru/holy-loader/blob/2b4b63b53b3216cdb883653c4f15bea671b23db2/src/index.tsx#L97-L256
2b4b63b53b3216cdb883653c4f15bea671b23db2
holy-loader
github_2023
tomcru
typescript
stopProgressOnHistoryUpdate
const stopProgressOnHistoryUpdate = (): void => { if (isHistoryPatched) { return; } const originalPushState = history.pushState.bind(history); history.pushState = (...args) => { const url = args[2]; if ( url && isSamePathname(window.location.href, url) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, url)) ) { originalPushState(...args); return; } stopProgress(); originalPushState(...args); }; // This is crucial for Next.js Link components using the 'replace' prop. const originalReplaceState = history.replaceState.bind(history); history.replaceState = (...args) => { const url = args[2]; if ( url && isSamePathname(window.location.href, url) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, url)) ) { originalReplaceState(...args); return; } stopProgress(); originalReplaceState(...args); }; isHistoryPatched = true; };
/** * Enhances browser history methods (pushState and replaceState) to ensure that the * progress indicator is appropriately halted when navigating through single-page applications */
https://github.com/tomcru/holy-loader/blob/2b4b63b53b3216cdb883653c4f15bea671b23db2/src/index.tsx#L143-L182
2b4b63b53b3216cdb883653c4f15bea671b23db2
holy-loader
github_2023
tomcru
typescript
handleClick
const handleClick = (event: MouseEvent): void => { try { const target = event.target as HTMLElement; const anchor = target.closest('a'); /** * The target attribute can have custom values which might have the link open in external contexts * Links with custom `target` values, '_blank', '_parent', or '_top' are therefore treated as external. */ const anchorOpensExternally = anchor?.target && anchor.target !== '_self'; if ( anchor === null || anchorOpensExternally || anchor.hasAttribute('download') || event.ctrlKey || event.metaKey || // Skip if URL points to a different domain !isSameHost(window.location.href, anchor.href) || // Skip if URL is a same-page anchor (href="#", href="#top", etc.). isSamePageAnchor(window.location.href, anchor.href) || // Skip if URL uses a non-http/https protocol (mailto:, tel:, etc.). !toAbsoluteURL(anchor.href).startsWith('http') || // Skip if the URL is the same as the current page (isSamePathname(window.location.href, anchor.href) && (ignoreSearchParams || hasSameQueryParameters(window.location.href, anchor.href))) ) { return; } startProgress(); } catch (error) { stopProgress(); } };
/** * Handles click events on anchor tags, starting the progress bar for page navigation. * It checks for various conditions to decide whether to start the progress bar or not. * * @param {MouseEvent} event The mouse event triggered by clicking an anchor tag. */
https://github.com/tomcru/holy-loader/blob/2b4b63b53b3216cdb883653c4f15bea671b23db2/src/index.tsx#L190-L225
2b4b63b53b3216cdb883653c4f15bea671b23db2
editor
github_2023
blokkli
typescript
Extractor.addFiles
addFiles(files: string[]) { return Promise.all(files.map((v) => this.handleFile(v))) }
/** * Add files by path. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/scripts/texts/app.ts#L128-L130
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.handleFile
async handleFile(filePath: string) { const source = await this.readFile(filePath) const extractions = this.getExtractions(source, filePath) extractions.forEach((extraction) => { this.texts[extraction.key] = extraction }) }
/** * Read the file and extract the texts. * * Returns a promise containing a boolean that indicated if the given file * should trigger a rebuild of the query. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/scripts/texts/app.ts#L138-L144
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.getExtractions
getExtractions(source: string, filePath: string) { const extractions: Extraction[] = [] if (source.includes('$t(')) { extractions.push(...this.extractSingle(source, filePath)) } if (source.includes('defineBlokkliFeature(')) { extractions.push(...this.extractFeatureSettings(source, filePath)) } return extractions }
/** * Find all possible extractions from the given source. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/scripts/texts/app.ts#L149-L159
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.extractSingle
extractSingle(source: string, filePath: string): Extraction[] { return extractFunctionCalls('$t(', source) .map((code) => { try { const tree = parse(code, { ecmaVersion: 'latest', }) let extractedTree: any = null extractedTree = extractText(tree) return extractedTree } catch (e) { this.handleError(filePath, code, e) } }) .filter(falsy) }
/** * Extract the single text method calls. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/scripts/texts/app.ts#L177-L193
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.readFile
readFile(filePath: string) { return fs.promises.readFile(filePath).then((v) => { return v.toString() }) }
/** * Read the given file and return its contents. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/scripts/texts/app.ts#L265-L269
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
applies
const applies = (path: string): Promise<string | undefined> => { const filePath = srcResolver.resolve(path) // Check that only the globally possible file types are used. if (!POSSIBLE_EXTENSIONS.includes(extname(filePath))) { return Promise.resolve(undefined) } // Get all files based on pattern and check if there is a match. return resolveFiles(srcDir, importPattern, { followSymbolicLinks: false, }).then((files) => { return files.find((v) => v === filePath) }) }
// Checks if the given file path is handled by this module.
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/module.ts#L816-L830
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.addFiles
addFiles(files: string[]): Promise<boolean[]> { return Promise.all(files.map((v) => this.handleFile(v))) }
/** * Add files by path. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L61-L63
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.handleFile
async handleFile(filePath: string): Promise<boolean> { const fileSource = await this.readFile(filePath) const extracted = this.extractSingle(fileSource, filePath) if (!extracted) { if (this.definitions[filePath]) { this.definitions[filePath] = undefined return true } if (this.fragmentDefinitions[filePath]) { this.fragmentDefinitions[filePath] = undefined return true } return false } if ('bundle' in extracted.definition) { const icon = await this.getIcon(filePath) const proxyComponent = await this.getContextComponent(filePath, 'proxy') const diffComponent = await this.getContextComponent(filePath, 'diff') if ( this.definitions[filePath] && this.definitions[filePath]?.source === extracted.source ) { return false } const extension = path.extname(filePath) const componentFileName = path.basename(filePath, extension) this.definitions[filePath] = { filePath, definition: extracted.definition, icon, proxyComponent, diffComponent, chunkName: (extracted.definition.chunkName || 'global') as any, componentName: 'BlokkliComponent_' + extracted.definition.bundle + '_' + componentFileName, source: extracted.source, fileSource, hasBlokkliField: fileSource.includes('<BlokkliField') || fileSource.includes('<blokkli-field') || fileSource.includes(':is="BlokkliField"'), } } else if ('name' in extracted.definition) { if ( this.fragmentDefinitions[filePath] && this.fragmentDefinitions[filePath]?.source === extracted.source ) { return false } this.fragmentDefinitions[filePath] = { filePath, definition: extracted.definition, chunkName: (extracted.definition.chunkName || 'global') as any, componentName: 'BlokkliFragmentComponent_' + extracted.definition.name, source: extracted.source, fileSource, } } return true }
/** * Read the file and extract the blokkli component definitions. * * Returns a promise containing a boolean that indicated if the given file * should trigger a rebuild of the query. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L97-L167
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.extractSingle
extractSingle( code: string, filePath: string, ): | { definition: | ExtractedBlockDefinitionInput | ExtractedFragmentDefinitionInput source: string } | undefined { const pattern = `(${this.composableName}|${this.fragmentComposableName})` + '\\((\\{.+?\\})\\)' const rgx = new RegExp(pattern, 'gms') const source = rgx.exec(code)?.[2] if (source) { try { const definition = eval(`(${source})`) return { definition, source } } catch (e) { console.error( `Failed to parse component "${filePath}": ${this.composableName} does not contain a valid object literal. No variables and methods are allowed inside ${this.composableName}().`, e, ) } } }
/** * Extract the single text method calls. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L172-L199
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.readFile
readFile(filePath: string) { return fs.promises.readFile(filePath).then((v) => { return v.toString() }) }
/** * Read the given file and return its contents. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L204-L208
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.generateDefinitionTemplate
generateDefinitionTemplate( globalOptions: BlockDefinitionOptionsInput = {}, ): string { const definitionDeclarations = Object.values(this.definitions) .filter(falsy) .map((v) => { return `const ${v.componentName}: DefinitionItem = ${v.source}` }, {}) const allDefinitions = Object.values(this.definitions) .filter(falsy) .reduce<string[]>((acc, v) => { const bundle = v.definition.bundle const renderFor = v.definition.renderFor if (renderFor) { const renderForList = Array.isArray(renderFor) ? renderFor : [renderFor] renderForList.forEach((entry) => { if ('parentBundle' in entry) { acc.push( `${bundle}__parent_block_${entry.parentBundle}: ${v.componentName}`, ) } else if ('fieldList' in entry) { acc.push( `${bundle}__field_list_type_${entry.fieldList}: ${v.componentName}`, ) } else if ('fieldListType' in entry) { acc.push( `${bundle}__field_list_type_${entry.fieldListType}: ${v.componentName}`, ) } }) } else { acc.push(`${bundle}: ${v.componentName}`) } return acc // return `${v.definition.bundle}: ${v.source}` }, []) const allFragmentDefinitions = Object.values(this.fragmentDefinitions) .filter(falsy) .map((v) => { return `${v.definition.name}: ${v.source}` }) const icons = Object.values(this.definitions) .filter(falsy) .reduce<Record<string, string>>((acc, v) => { if (v.icon) { acc[v.definition.bundle] = v.icon } return acc }, {}) const buildContextComponents = ( name: keyof Pick<ExtractedDefinition, 'diffComponent' | 'proxyComponent'>, ) => { const proxyComponents = Object.values(this.definitions).reduce< Record<string, string> >((acc, v) => { if (v?.[name]) { acc[v.definition.bundle] = v[name] } return acc }, {}) const imports = Object.entries(proxyComponents) .map(([bundle, proxyComponentPath]) => { return `import ${name}_${bundle} from '${proxyComponentPath}'` }) .join('\n') const maps = Object.keys(proxyComponents) .map((bundle) => { return `'${bundle}': ${name}_${bundle}` }) .join(', \n') return { imports, maps, } } const proxy = buildContextComponents('proxyComponent') const diff = buildContextComponents('diffComponent') const allFragmentNames = Object.values(this.fragmentDefinitions) .filter(falsy) .map((v) => `'${v.definition.name}'`) .join(' | ') return `import type { GlobalOptionsKey, ValidFieldListTypes, BlockBundleWithNested } from './generated-types' import type { BlockDefinitionInput, BlockDefinitionOptionsInput, FragmentDefinitionInput } from '#blokkli/types' export const globalOptions = ${JSON.stringify(globalOptions, null, 2)} as const ${proxy.imports} ${diff.imports} type DefinitionItem = BlockDefinitionInput<BlockDefinitionOptionsInput, GlobalOptionsKey[]> ${definitionDeclarations.join('\n')} const PROXY_COMPONENTS: Record<string, any> = { ${proxy.maps} } const DIFF_COMPONENTS: Record<string, any> = { ${diff.maps} } export const icons: Record<string, string> = ${JSON.stringify(icons)} export const definitionsMap: Record<string, DefinitionItem> = { ${allDefinitions.join(',\n')} } export const fragmentDefinitionsMap: Record<string, FragmentDefinitionInput<BlockDefinitionOptionsInput, GlobalOptionsKey[]>> = { ${allFragmentDefinitions.join(',\n')} } export type BlokkliFragmentName = ${allFragmentNames || 'never'} export const definitions: BlockDefinitionInput<any, GlobalOptionsKey[]>[] = Object.values(definitionsMap) export const fragmentDefinitions: FragmentDefinitionInput<any, GlobalOptionsKey[]>[] = Object.values(fragmentDefinitionsMap) /** * Get the block definition for the given field and parent context. */ export function getDefinition(bundle: string, fieldListType: ValidFieldListTypes, parentBundle?: BlockBundleWithNested): BlockDefinitionInput<Record<string, any>, GlobalOptionsKey[]>|undefined { const forFieldListType = bundle + '__field_list_type_' + fieldListType if (definitionsMap[forFieldListType]) { return definitionsMap[forFieldListType] } if (parentBundle) { const forParentBundle = bundle + '__parent_block_' + parentBundle if (definitionsMap[forParentBundle]) { return definitionsMap[forParentBundle] } } return definitionsMap[bundle] } export function getBlokkliItemProxyComponent(bundle: string): any { return PROXY_COMPONENTS[bundle] } export function getBlokkliItemDiffComponent(bundle: string): any { return DIFF_COMPONENTS[bundle] } /** * Get the definition of the default block component. */ export function getDefaultDefinition(bundle: string): BlockDefinitionInput<Record<string, any>, GlobalOptionsKey[]>|undefined { return definitionsMap[bundle] } export const getFragmentDefinition = (name: string): FragmentDefinitionInput<Record<string, any>, GlobalOptionsKey[]>|undefined => fragmentDefinitionsMap[name] ` }
/** * Generate the template. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L213-L374
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.generateOptionsSchema
generateOptionsSchema( globalOptions: BlockDefinitionOptionsInput = {}, ): string { const schema = Object.values(this.definitions) .filter(falsy) .reduce<Record<string, any>>((acc, v) => { const existing = acc[v.definition.bundle] || {} acc[v.definition.bundle] = defu(existing, v.definition.options || {}) const globalOptionKeys: string[] = v.definition.globalOptions || [] globalOptionKeys.forEach((name) => { if (globalOptions[name]) { acc[v.definition.bundle][name] = globalOptions[name] } }) return acc }, {}) const sorted = sortObjectKeys(schema) return JSON.stringify(sorted, null, 2) }
/** * Generate the options schema. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L379-L401
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.generateDefaultGlobalOptions
generateDefaultGlobalOptions( globalOptions: BlockDefinitionOptionsInput = {}, ): string { const defaults = Object.entries(globalOptions).reduce<Record<string, any>>( (acc, [key, option]) => { if (option.default) { acc[key] = { default: option.default, type: option.type, } } return acc }, {}, ) return `import type { BlockOptionDefinition } from '#blokkli/types/blokkOptions' type GlobalOptionsDefaults = { type: BlockOptionDefinition['type'] default: any } export const bundlesWithVisibleLanguage: string[] = ${JSON.stringify(this.getBundlesWithGlobalOptions(BK_VISIBLE_LANGUAGES))} export const bundlesWithHiddenGlobally: string[] = ${JSON.stringify(this.getBundlesWithGlobalOptions(BK_HIDDEN_GLOBALLY))} export const globalOptionsDefaults: Record<string, GlobalOptionsDefaults> = ${JSON.stringify( defaults, null, 2, )} as const` }
/** * Generate the default global options values template. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L416-L446
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.generateImportsTemplate
generateImportsTemplate(chunkNames: string[]): string { const chunkImports = chunkNames .filter((v) => v !== 'global') .map((chunkName) => { return `${chunkName}: () => import('#blokkli/chunk-${chunkName}')` }) const nonGlobalChunkMapping = Object.values(this.definitions).reduce< Record<string, string> >((acc, v) => { if (v && v.chunkName !== 'global') { acc['block_' + v.definition.bundle] = v.chunkName } return acc }, {}) const nonGlobalFragmentChunkMapping = Object.values( this.fragmentDefinitions, ).reduce<Record<string, string>>((acc, v) => { if (v && v.chunkName !== 'global') { acc['fragment_' + v.definition.name] = v.chunkName } return acc }, {}) return ` import { defineAsyncComponent } from '#imports' ${this.generateChunkGroup('global', 'global', this.definitions)} ${this.generateChunkGroup( 'global', 'globalFragments', this.fragmentDefinitions, )} const chunks: Record<string, () => Promise<any>> = { ${chunkImports.join(',\n ')} } const chunkMapping: Record<string, string> = ${JSON.stringify( nonGlobalChunkMapping, null, 2, )} const fragmentChunkMapping: Record<string, string> = ${JSON.stringify( nonGlobalFragmentChunkMapping, null, 2, )} export function getBlokkliItemComponent(bundle: string, fieldListType?: string, parentBundle?: string): any { const forFieldListType = 'block_' + bundle + '__field_list_type_' + fieldListType if (global[forFieldListType]) { return global[forFieldListType] } if (parentBundle) { const forParentBundle = 'block_' + bundle + '__parent_block_' + parentBundle if (global[forParentBundle]) { return global[forParentBundle] } } const key = 'block_' + bundle if (global[key]) { return global[key] } const chunkName = chunkMapping[key] if (chunkName) { return defineAsyncComponent(() => chunks[chunkName]().then(chunk => { return chunk.default[key] })) } } export function getBlokkliFragmentComponent(name: string): any { const key = 'fragment_' + name if (globalFragments[key]) { return globalFragments[key] } const chunkName = fragmentChunkMapping[key] if (chunkName) { return defineAsyncComponent(() => chunks[chunkName]().then(chunk => { return chunk.default[key] })) } } ` }
/** * Generate the template. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L584-L670
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
BlockExtractor.generateChunkGroup
generateChunkGroup( chunkName: string, exportName: string, inputDefinitions: Record< string, ExtractedDefinition | ExtractedFragmentDefinition | undefined >, addExport?: boolean, ): string { const definitions = Object.values(inputDefinitions) .filter((v) => { return v?.chunkName === chunkName }) .filter(falsy) const imports = definitions.map((v) => { return `import ${v.componentName} from '${v.filePath}'` }) const map = definitions.reduce<string[]>((acc, v) => { if ('bundle' in v.definition) { const bundle = v.definition.bundle const renderFor = v.definition.renderFor if (!renderFor) { acc.push(`block_${v.definition.bundle}: ${v.componentName}`) } else { const renderForList = Array.isArray(renderFor) ? renderFor : [renderFor] renderForList.forEach((entry) => { if ('parentBundle' in entry) { acc.push( `block_${bundle}__parent_block_${entry.parentBundle}: ${v.componentName}`, ) } else if ('fieldList' in entry) { acc.push( `block_${bundle}__field_list_type_${entry.fieldList}: ${v.componentName}`, ) } else if ('fieldListType' in entry) { acc.push( `block_${bundle}__field_list_type_${entry.fieldListType}: ${v.componentName}`, ) } }) } } else { acc.push(`fragment_${v.definition.name}: ${v.componentName}`) } return acc }, []) let content = ` ${imports.join('\n')} const ${exportName}: Record<string, any> = { ${map.join(',\n ')} } ` if (addExport) { content += `export default ${exportName}` } return content }
/** * Generate the template. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/BlockExtractor.ts#L675-L735
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.addFiles
addFiles(files: string[]): Promise<boolean[]> { return Promise.all(files.map((v) => this.handleFile(v))) }
/** * Add files by path. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/FeatureExtractor.ts#L31-L33
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.handleFile
async handleFile(filePath: string): Promise<boolean> { const fileSource = await this.readFile(filePath) const extracted = this.extractSingle(fileSource, filePath) if (!extracted) { if (this.definitions[filePath]) { this.definitions[filePath] = undefined return true } return false } const { definition, source } = extracted // New file that didn't previously contain a blokkli component definition. if (!this.definitions[filePath]) { const regex = /\/Features\/([^/]+)\// const componentName = filePath.match(regex)?.[1] || '' this.definitions[filePath] = { id: definition.id, componentName, componentPath: filePath, filePath, definition, source, } return true } // If the the definition didn't change, return. if (this.definitions[filePath]?.definition === definition) { return false } // Update the definition. this.definitions[filePath]!.definition = definition return true }
/** * Read the file and extract the blokkli component definitions. * * Returns a promise containing a boolean that indicated if the given file * should trigger a rebuild of the query. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/FeatureExtractor.ts#L41-L79
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.extractSingle
extractSingle( code: string, filePath: string, ): { definition: FeatureDefinition<any>; source: string } | undefined { const pattern = this.composableName + '\\((\\{.+?\\})\\)' const rgx = new RegExp(pattern, 'gms') const source = rgx.exec(code)?.[1] if (source) { try { const definition = eval(`(${source})`) return { definition, source } } catch (e) { console.error( `Failed to parse component "${filePath}": ${this.composableName} does not contain a valid object literal. No variables and methods are allowed inside ${this.composableName}().`, e, ) } } }
/** * Extract the single text method calls. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/FeatureExtractor.ts#L84-L102
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
Extractor.readFile
readFile(filePath: string) { return fs.promises.readFile(filePath).then((v) => { return v.toString() }) }
/** * Read the given file and return its contents. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/Extractor/FeatureExtractor.ts#L107-L111
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
getDroppableFieldConfig
const getDroppableFieldConfig: DrupalAdapter['getDroppableFieldConfig'] = () => { return Promise.resolve(config.droppableFieldConfig) }
// @TODO: Required property.
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/runtime/adapter/drupal/graphqlMiddleware.ts#L528-L531
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
onVisibilityChange
const onVisibilityChange = () => { isPressingControl.value = false isPressingSpace.value = false }
/** * When the tab becomes inactive we set key modifier states to false. * * This solves a potential problem where someone might switch tabs using the * control key, which would keep CTRL being active when coming back to the * window, even though the key isn't being pressed anymore. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/runtime/helpers/keyboardProvider.ts#L88-L91
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
estreeToObject
function estreeToObject( expression: ObjectExpression, ): BlockDefinitionInput<BlockDefinitionOptionsInput, []> { return Object.fromEntries( expression.properties .map((prop) => { if (prop.type === 'Property' && 'name' in prop.key) { if (prop.value.type === 'Literal') { return [prop.key.name, prop.value.value] } else if (prop.value.type === 'ObjectExpression') { return [prop.key.name, estreeToObject(prop.value)] } else if (prop.value.type === 'ArrayExpression') { return [ prop.key.name, prop.value.elements .map((v) => { if (v && 'value' in v) { return v.value } }) .filter(falsy), ] } } return null }) .filter(falsy), ) }
/** * Build an object from an ObjectExpression. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/vitePlugin/index.ts#L37-L65
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
editor
github_2023
blokkli
typescript
buildRuntimeDefinition
function buildRuntimeDefinition( definition: BlockDefinitionInput<BlockDefinitionOptionsInput, []>, ): RuntimeDefinitionInput { const runtimeDefinition: RuntimeDefinitionInput = { bundle: definition.bundle, } if (definition.options) { runtimeDefinition.options = {} Object.entries(definition.options).forEach( ([optionKey, optionDefinition]) => { runtimeDefinition.options![optionKey] = { type: optionDefinition.type, default: optionDefinition.default, } }, ) } if (definition.globalOptions) { runtimeDefinition.globalOptions = definition.globalOptions } return runtimeDefinition }
/** * Build the runtime type definition from the full definition. * * During runtime, only the option default values and the array of globel * options are needed. */
https://github.com/blokkli/editor/blob/6bb2c62ad38c80d06c1f171ba76151a599f3bb99/src/vitePlugin/index.ts#L73-L96
6bb2c62ad38c80d06c1f171ba76151a599f3bb99
ragflow
github_2023
infiniflow
typescript
onError
function onError(error: Error) { console.error(error); }
// Catch any errors that occur during Lexical updates and log them
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/components/prompt-editor/index.tsx#L28-L30
6daae7f2263540f54aba1422e14ff199470bfbf3
ragflow
github_2023
infiniflow
typescript
useCallbackRef
function useCallbackRef<T extends (...args: never[]) => unknown>( callback: T | undefined, ): T { const callbackRef = React.useRef(callback); React.useEffect(() => { callbackRef.current = callback; }); // https://github.com/facebook/react/issues/19240 return React.useMemo( () => ((...args) => callbackRef.current?.(...args)) as T, [], ); }
/** * @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx */
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/hooks/use-callback-ref.ts#L11-L25
6daae7f2263540f54aba1422e14ff199470bfbf3
ragflow
github_2023
infiniflow
typescript
Converter.constructor
constructor() { this.keyGenerator = new KeyGenerator(); }
// key is node id, value is combo
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/pages/add-knowledge/components/knowledge-graph/util.ts#L24-L26
6daae7f2263540f54aba1422e14ff199470bfbf3
ragflow
github_2023
infiniflow
typescript
buildOperatorParams
const buildOperatorParams = (operatorName: string) => pipe( removeUselessDataInTheOperator(operatorName), // initializeOperatorParams(operatorName), // Final processing, for guarantee );
// initialize data for operators without parameters
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/pages/flow/utils.ts#L122-L126
6daae7f2263540f54aba1422e14ff199470bfbf3
ragflow
github_2023
infiniflow
typescript
buildCategorizeObjectFromList
const buildCategorizeObjectFromList = (list: Array<ICategorizeItem>) => { return list.reduce<ICategorizeItemResult>((pre, cur) => { if (cur?.name) { pre[cur.name] = omit(cur, 'name'); } return pre; }, {}); };
/** * Convert the list in the following form into an object * { "items": [ { "name": "Categorize 1", "description": "111", "examples": "ddd", "to": "Retrieval:LazyEelsStick" } ] } */
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/pages/flow/form/categorize-form/hooks.ts#L22-L29
6daae7f2263540f54aba1422e14ff199470bfbf3
ragflow
github_2023
infiniflow
typescript
handleChange
const handleChange = (path: SegmentedValue) => { // navigate(path as string); setCurrentPath(path as string); };
// const currentPath = useMemo(() => {
https://github.com/infiniflow/ragflow/blob/6daae7f2263540f54aba1422e14ff199470bfbf3/web/src/pages/home/header.tsx#L57-L60
6daae7f2263540f54aba1422e14ff199470bfbf3
onchainkit
github_2023
coinbase
typescript
handleSlippageChange
const handleSlippageChange = (event: React.ChangeEvent<HTMLInputElement>) => { const value = event.target.value; setInputValue(value); if (setDefaultMaxSlippage) { if (value === '') { setDefaultMaxSlippage(0); } else { const numValue = Number.parseFloat(value); if (!Number.isNaN(numValue) && numValue >= 0) { setDefaultMaxSlippage(numValue); } } } };
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO Refactor this component
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/playground/nextjs-app-router/components/form/swap-config.tsx#L18-L32
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
deposit
const deposit = async ({ config, from, bridgeParams }: DepositParams) => { if (!bridgeParams.recipient) { throw new Error('Recipient is required'); } if (chainId !== from.id) { await switchChainAsync({ chainId: from.id }); } setStatus('depositPending'); try { // Native ETH if (bridgeParams.token.address === '') { const txHash = await writeContractAsync({ abi: StandardBridgeABI, functionName: 'bridgeETHTo', args: [bridgeParams.recipient, MIN_GAS_LIMIT, EXTRA_DATA], address: config.contracts.l1StandardBridge, value: parseEther(bridgeParams.amount), chainId: from.id, }); await waitForTransactionReceipt(wagmiConfig, { hash: txHash, confirmations: 1, chainId: from.id, }); } else { // ERC20 if (!bridgeParams.token.remoteToken) { throw new Error('Remote token address is required for ERC-20 tokens'); } const formattedAmount = parseUnits( bridgeParams.amount, bridgeParams.token.decimals, ); // Bridge address is OptimismPortal for depositing custom gas tokens const bridgeAddress = bridgeParams.token.isCustomGasToken ? config.contracts.optimismPortal : config.contracts.l1StandardBridge; // Approve the L1StandardBridge to spend tokens const approveTx = await writeContractAsync({ abi: ERC20ABI, functionName: 'approve', args: [bridgeAddress, formattedAmount], address: bridgeParams.token.address, }); await waitForTransactionReceipt(wagmiConfig, { hash: approveTx, confirmations: 1, chainId: from.id, }); let bridgeTxHash: Hex; // Bridge the tokens if (bridgeParams.token.isCustomGasToken) { bridgeTxHash = await writeContractAsync({ abi: OptimismPortalABI, functionName: 'depositERC20Transaction', args: [ bridgeParams.recipient, formattedAmount, BigInt(0), BigInt(MIN_GAS_LIMIT), false, EXTRA_DATA, ], address: bridgeAddress, }); } else { bridgeTxHash = await writeContractAsync({ abi: StandardBridgeABI, functionName: 'bridgeERC20To', args: [ bridgeParams.token.address, bridgeParams.token.remoteToken, // TODO: manually calculate the salted address bridgeParams.recipient, formattedAmount, MIN_GAS_LIMIT, EXTRA_DATA, ], address: bridgeAddress, }); } await waitForTransactionReceipt(wagmiConfig, { hash: bridgeTxHash, confirmations: 1, chainId: from.id, }); } setStatus('depositSuccess'); } catch (error) { if (isUserRejectedRequestError(error)) { console.error('User rejected request'); setStatus('depositRejected'); } else { setStatus('error'); } } };
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ignore
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/appchain/bridge/hooks/useDeposit.ts#L32-L138
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
withdraw
const withdraw = async () => { if (!bridgeParams.recipient) { throw new Error('Recipient is required'); } setWithdrawStatus('withdrawPending'); try { // Switch networks to the appchain if (chainId !== config.chainId) { await switchChainAsync({ chainId: config.chainId }); } let transactionHash: Hex = '0x'; // Custom gas token if (bridgeParams.token.isCustomGasToken) { transactionHash = await writeContractAsync({ abi: L2_TO_L1_MESSAGE_PASSER_ABI, functionName: 'initiateWithdrawal', args: [bridgeParams.recipient, BigInt(MIN_GAS_LIMIT), EXTRA_DATA], address: APPCHAIN_L2_TO_L1_MESSAGE_PASSER_ADDRESS, chainId: config.chainId, value: parseEther(bridgeParams.amount), }); } else if (bridgeParams.token.address === '') { // Native ETH transactionHash = await writeContractAsync({ abi: StandardBridgeABI, functionName: 'bridgeETHTo', args: [bridgeParams.recipient, MIN_GAS_LIMIT, EXTRA_DATA], address: APPCHAIN_BRIDGE_ADDRESS, value: parseEther(bridgeParams.amount), chainId: config.chainId, }); } else { // ERC-20 if (!bridgeParams.token.remoteToken) { throw new Error('Remote token is required'); } const formattedAmount = parseUnits( bridgeParams.amount, bridgeParams.token.decimals, ); const approveTx = await writeContractAsync({ abi: erc20Abi, functionName: 'approve', args: [APPCHAIN_BRIDGE_ADDRESS, formattedAmount], address: bridgeParams.token.address, chainId: config.chainId, }); await waitForTransactionReceipt(wagmiConfig, { hash: approveTx, confirmations: 1, }); transactionHash = await writeContractAsync({ abi: StandardBridgeABI, functionName: 'bridgeERC20To', args: [ bridgeParams.token.remoteToken, bridgeParams.token.address, bridgeParams.recipient, formattedAmount, MIN_GAS_LIMIT, EXTRA_DATA, ], address: APPCHAIN_BRIDGE_ADDRESS, chainId: config.chainId, }); } setWithdrawStatus('withdrawSuccess'); return transactionHash; } catch (error) { if (isUserRejectedRequestError(error)) { console.error('User rejected request'); setWithdrawStatus('withdrawRejected'); } else { console.error('Error', error); setWithdrawStatus('error'); } } };
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ignore
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/appchain/bridge/hooks/useWithdraw.ts#L73-L157
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
proveAndFinalizeWithdrawal
const proveAndFinalizeWithdrawal = async () => { if (!withdrawal || withdrawal.length === 0) { console.error('no withdrawals to prove'); return; } setWithdrawStatus('claimPending'); // Build proof const output = await getOutput({ config, chain, wagmiConfig, }); const slot = getWithdrawalHashStorageSlot({ withdrawalHash: withdrawal[0].withdrawalHash, }); const [proof, block] = await Promise.all([ // On the L2ToL1MessagePasser on the appchain getProof(wagmiConfig, { address: APPCHAIN_L2_TO_L1_MESSAGE_PASSER_ADDRESS, storageKeys: [slot], blockNumber: output.l2BlockNumber, chainId: config.chainId, }), getBlock(wagmiConfig, { blockNumber: output.l2BlockNumber, chainId: config.chainId, }), ]); const args = { l2OutputIndex: output.outputIndex, outputRootProof: { version: OUTPUT_ROOT_PROOF_VERSION, stateRoot: block.stateRoot, messagePasserStorageRoot: proof.storageHash, latestBlockhash: block.hash, }, withdrawalProof: maybeAddProofNode( keccak256(slot), proof.storageProof[0].proof, ), withdrawal: withdrawal[0], }; try { // Switch networks to Base if (chainId !== chain.id) { await switchChainAsync({ chainId: chain.id }); } // Finalize the withdrawal await writeContractAsync({ abi: OptimismPortalABI, address: config.contracts.optimismPortal, functionName: 'proveAndFinalizeWithdrawalTransaction', args: [ withdrawal[0], args.l2OutputIndex, args.outputRootProof, args.withdrawalProof, ], chainId: chain.id, }); setWithdrawStatus('claimSuccess'); } catch (error) { if (isUserRejectedRequestError(error)) { console.error('User rejected request'); setWithdrawStatus('claimRejected'); } else { setWithdrawStatus('error'); } } };
/* v8 ignore start */
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/appchain/bridge/hooks/useWithdraw.ts#L195-L268
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
TestComponent
const TestComponent = ({ amount = '5' }: { amount?: string }) => { const { setFundAmountFiat } = useFundContext(); return ( <> <button type="button" onClick={() => setFundAmountFiat(amount)} data-testid="setAmount" > Set Amount </button> <button type="button" onClick={() => setFundAmountFiat('1')} data-testid="setAmount1" > Set amount to 1 </button> <FundCardPaymentMethodDropdown /> </> ); };
// Test component to access and modify context
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/fund/components/FundCardPaymentMethodDropdown.test.tsx#L38-L59
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
TestHelperComponent
const TestHelperComponent = () => { const { fundAmountFiat, fundAmountCrypto, exchangeRate, exchangeRateLoading, setFundAmountFiat, setFundAmountCrypto, } = useFundContext(); return ( <div> <span data-testid="test-value-fiat">{fundAmountFiat}</span> <span data-testid="test-value-crypto">{fundAmountCrypto}</span> <span data-testid="test-value-exchange-rate">{exchangeRate}</span> <span data-testid="loading-state"> {exchangeRateLoading ? 'loading' : 'not-loading'} </span> <button type="button" data-testid="set-fiat-amount" onClick={() => setFundAmountFiat('100')} /> <button type="button" data-testid="set-crypto-amount" onClick={() => setFundAmountCrypto('1')} /> <button type="button" data-testid="set-fiat-amount-zero" onClick={() => setFundAmountFiat('0')} /> <button type="button" data-testid="set-crypto-amount-zero" onClick={() => setFundAmountCrypto('0')} /> </div> ); };
// Test component to access context values
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/fund/components/FundCardSubmitButton.test.tsx#L70-L110
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
mockMessageEvent
const mockMessageEvent = (data: any, origin = DEFAULT_ORIGIN) => new MessageEvent('message', { data, origin });
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/fund/utils/subscribeToWindowMessage.test.ts#L11-L12
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
handlePointerDownCapture
const handlePointerDownCapture = (event: PointerEvent) => { if (disableOutsideClick) { return; } if (!(event.target instanceof Node)) { return; } const target = event.target; if (triggerRef?.current?.contains(target)) { handleTriggerClick(event); return; } if (!isClickInsideLayer(target)) { onDismiss?.(); } };
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO Refactor this component
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/internal/components/DismissableLayer.tsx#L51-L70
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
getCurrentBreakpoint
const getCurrentBreakpoint = () => { const entries = Object.entries(BREAKPOINTS) as [string, string][]; for (const [key, query] of entries) { if (window.matchMedia(query).matches) { return key; } } return 'md'; };
// get the current breakpoint based on media queries
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/internal/hooks/useBreakpoints.ts#L21-L29
afcc29e362654e2fd7bc60908a0cc122b0d281c4
onchainkit
github_2023
coinbase
typescript
handleResize
const handleResize = () => { setCurrentBreakpoint(getCurrentBreakpoint()); };
// listen changes in the window size
https://github.com/coinbase/onchainkit/blob/afcc29e362654e2fd7bc60908a0cc122b0d281c4/src/internal/hooks/useBreakpoints.ts#L35-L37
afcc29e362654e2fd7bc60908a0cc122b0d281c4