repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
agentcloud
github_2023
rnadigital
typescript
fetchWorkspaces
async function fetchWorkspaces() { try { log('Fetching airbyte workspaces...'); const workspacesApi = await getAirbyteApi(AirbyteApiType.WORKSPACES); return workspacesApi.listWorkspaces().then(res => res.data); } catch (e) { log('An error occurred while attempting to fetch Airbyte workspaces. %', e); } }
// Google Pub/Sub destination id
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/airbyte/setup.ts#L34-L42
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
fetchDestinationList
async function fetchDestinationList(workspaceId: string) { const response = await fetch( `${process.env.AIRBYTE_API_URL}/api/public/v1/destinations?workspaceId=${encodeURIComponent(workspaceId)}`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${await getAirbyteAuthToken()}` } } ); return response.json(); }
// Function to fetch the destination list
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/airbyte/setup.ts#L45-L57
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
createDestination
async function createDestination(workspaceId: string, provider: string) { const destinationConfiguration = await getDestinationConfiguration(provider); const response = await fetch(`${process.env.AIRBYTE_API_URL}/api/public/v1/destinations`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${await getAirbyteAuthToken()}` }, body: JSON.stringify({ name: provider === 'rabbitmq' ? 'RabbitMQ' : 'Google Pub/Sub', definitionId: destinationDefinitionId, workspaceId, configuration: destinationConfiguration }) }); return response.json(); }
// Function to create a destination
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/airbyte/setup.ts#L60-L76
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
deleteDestination
async function deleteDestination(destinationId: string) { const response = await fetch( `${process.env.AIRBYTE_API_URL}/api/public/v1/destinations/${destinationId}`, { method: 'DELETE', headers: { Authorization: `Bearer ${await getAirbyteAuthToken()}` } } ); }
// Function to delete a destination
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/airbyte/setup.ts#L79-L89
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
updateWebhookUrls
async function updateWebhookUrls(workspaceId: string) { const internalApi = await getAirbyteInternalApi(); const updateWorkspaceBody = { workspaceId, notificationSettings: { sendOnSuccess: { notificationType: ['slack'], slackConfiguration: { webhook: `${process.env.WEBAPP_WEBHOOK_HOST || process.env.URL_APP}/webhook/sync-successful` } }, sendOnBreakingChangeSyncsDisabled: { notificationType: ['slack'], slackConfiguration: { webhook: `${process.env.WEBAPP_WEBHOOK_HOST || process.env.URL_APP}/webhook/sync-problem?event=sendOnBreakingChangeSyncsDisabled` } }, sendOnBreakingChangeWarning: { notificationType: ['slack'], slackConfiguration: { webhook: `${process.env.WEBAPP_WEBHOOK_HOST || process.env.URL_APP}/webhook/sync-problem?event=sendOnBreakingChangeWarning` } }, sendOnFailure: { notificationType: ['slack'], slackConfiguration: { webhook: `${process.env.WEBAPP_WEBHOOK_HOST || process.env.URL_APP}/webhook/sync-problem?event=sendOnFailure` } } } }; const updateWorkspaceRes = await internalApi .updateWorkspace(null, updateWorkspaceBody) .then(res => res.data); return updateWorkspaceRes; }
// Function to update webhook URLs
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/airbyte/setup.ts#L169-L204
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
Permission.toJSON
toJSON() { return Object.entries(Metadata).reduce((acc, entry) => { acc[entry[0]] = { state: this.get(entry[0]), ...entry[1] }; return acc; }, {}); }
// Convert to a map of bit to metadata and state, for use in frontend
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/permissions/Permission.ts#L21-L29
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
Permission.applyInheritance
applyInheritance() { if (this.get(Permissions.ROOT)) { this.setAll(Permission.allPermissions); return; } if (this.get(Permissions.ORG_OWNER)) { this.setAll(ORG_BITS); this.set(Permissions.TEAM_OWNER, true); // Naturally, org owner has all team owner perms too } if (this.get(Permissions.TEAM_OWNER) || this.get(Permissions.TEAM_ADMIN)) { this.setAll(TEAM_BITS); } }
//TODO: move the data for these inheritances to the metadata structure, make the logic here dynamic
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/permissions/Permission.ts#L44-L56
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
GoogleStorageProvider.uploadLocalFile
async uploadLocalFile(filename, uploadedFile, contentType, isPublic = false): Promise<any> { log('Uploading file %s', filename); const file = this.#storageClient .bucket( isPublic === true ? process.env.NEXT_PUBLIC_GCS_BUCKET_NAME : process.env.NEXT_PUBLIC_GCS_BUCKET_NAME_PRIVATE ) .file(filename); try { await file.save(uploadedFile.data, { metadata: { contentType } }); log('File uploaded successfully.'); if (isPublic) { await file.makePublic(); } } catch (err) { log('File upload error:', err); throw err; } }
//Note: local file/assets just have an internal buffer, so we can probably remove this and use uploadBuffer everywhere
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/storage/google.ts#L46-L69
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
cn
const cn = (...inputs: ClassValue[]) => { return twMerge(clsx(inputs)); };
// We use clsx to conditionally join class names together and twMerge to merge Tailwind CSS classes with conflict resolution.
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/utils/cn.ts#L5-L7
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
VectorDBProxyClient.checkCollectionExists
static async checkCollectionExists(collectionId: IdOrStr): Promise<VectorResponseBody> { log('checkCollectionExists %s', collectionId); return fetch( `${process.env.VECTOR_APP_URL}/api/v1/check-collection-exists/${collectionId}` ).then(res => { return res.json(); }); }
// Method to check collection exists
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/vectorproxy/client.ts#L63-L70
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
VectorDBProxyClient.getVectorStorageForTeam
static async getVectorStorageForTeam(teamId: IdOrStr): Promise<VectorResponseBody> { log('getVectorStorageForTeam %s', teamId); return fetch(`${process.env.VECTOR_APP_URL}/api/v1/storage-size/${teamId}`).then(res => { return res.json(); }); }
// Method to get the total storage size for the team
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/vectorproxy/client.ts#L73-L78
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
VectorDBProxyClient.deleteCollection
static async deleteCollection(collectionId: IdOrStr): Promise<VectorResponseBody> { log('deleteCollection %s', collectionId); return fetch(`${process.env.VECTOR_APP_URL}/api/v1/collection/${collectionId}`, { method: 'DELETE' }).then(res => res.json()); }
// Method to delete a collection
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/lib/vectorproxy/client.ts#L81-L86
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
handleRouteChange
const handleRouteChange = () => posthog?.capture('$pageview');
// Track page views
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/pages/_app.tsx#L41-L41
9ebed808f9b49541882b384f29a1a79ca80fae50
agentcloud
github_2023
rnadigital
typescript
augmentJobs
async function augmentJobs(jobList) { const connectionsApi = await getAirbyteApi(AirbyteApiType.CONNECTIONS); const internalApi = await getAirbyteInternalApi(); const augmentedJobs = await Promise.all( jobList.map(async job => { // get the actual rows/bytes synced from the internal airbyte API because the official one only returns committed values try { const getConnectionSyncProgressBody = { connectionId: job?.connectionId }; const connectionSyncProgress = await internalApi .getConnectionSyncProgress(null, getConnectionSyncProgressBody) .then(res => res.data); if (connectionSyncProgress) { connectionSyncProgress.bytesEmitted && (job.bytesSynced = connectionSyncProgress.bytesEmitted); connectionSyncProgress.recordsEmitted && (job.rowsSynced = connectionSyncProgress.recordsEmitted); } } catch (e) { console.log(e); } // fetch and attach the full airbyte "connection" object based on the jobs connectionId let foundConnection; try { foundConnection = await connectionsApi .getConnection(job.connectionId) .then(res => res.data); if (foundConnection) { job.connection = foundConnection; } } catch (e) { log(e); } // fetch and attach the the datasource from mongo based on the jobs connectionId let foundDatasource; try { foundDatasource = await getDatasourceByConnectionId(job.connectionId); if (foundDatasource) { job.datasource = foundDatasource; // find the org -> ownerId -> account.stripe to know the limits for this connection let limitOwnerId; const datasourceOrg = await getOrgById(foundDatasource?.orgId); if (datasourceOrg) { limitOwnerId = datasourceOrg?.ownerId; } const ownerAccount = await getAccountById(limitOwnerId); job.stripe = ownerAccount?.stripe; } } catch (e) { log(e); } return job; }) ); return augmentedJobs; }
/* // await vectorLimitTaskQueue.add( // 'sync', // { // data: 'test' // }, // { removeOnComplete: true, removeOnFail: true } // ); */
https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/sync-server/main.ts#L33-L92
9ebed808f9b49541882b384f29a1a79ca80fae50
seanime
github_2023
5rahim
typescript
run
async function run() { try { console.log("\nTesting Buffer encoding/decoding") const originalString = "Hello, this is a string to encode!" const base64String = Buffer.from(originalString).toString("base64") console.log("Original String:", originalString) console.log("Base64 Encoded:", base64String) const decodedString = Buffer.from(base64String, "base64").toString("utf-8") console.log("Base64 Decoded:", decodedString) } catch (e) { console.error(e) } try { console.log("\nTesting AES") let message = "seanime" let key = CryptoJS.enc.Utf8.parse("secret key") console.log("Message:", message) let encrypted = CryptoJS.AES.encrypt(message, key) console.log("Encrypted without IV:", encrypted) // map[iv toString] console.log("Encrypted.toString():", encrypted.toString()) // AoHrnhJfbRht2idLHM82WdkIEpRbXufnA6+ozty9fbk= console.log("Encrypted.toString(CryptoJS.enc.Base64):", encrypted.toString(CryptoJS.enc.Base64)) // AoHrnhJfbRht2idLHM82WdkIEpRbXufnA6+ozty9fbk= let decrypted = CryptoJS.AES.decrypt(encrypted, key) console.log("Decrypted:", decrypted.toString(CryptoJS.enc.Utf8)) let iv = CryptoJS.enc.Utf8.parse("3134003223491201") encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv }) console.log("Encrypted with IV:", encrypted) // map[iv toString] decrypted = CryptoJS.AES.decrypt(encrypted, key) console.log("Decrypted without IV:", decrypted.toString(CryptoJS.enc.Utf8)) decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv }) console.log("Decrypted with IV:", decrypted.toString(CryptoJS.enc.Utf8)) // seanime } catch (e) { console.error(e) } try { console.log("\nTesting encoders") console.log("") let a = CryptoJS.enc.Utf8.parse("Hello, World!") console.log("Base64 Parsed:", a) let b = CryptoJS.enc.Base64.stringify(a) console.log("Base64 Stringified:", b) let c = CryptoJS.enc.Base64.parse(b) console.log("Base64 Parsed:", c) let d = CryptoJS.enc.Utf8.stringify(c) console.log("Base64 Stringified:", d) console.log("") let words = CryptoJS.enc.Latin1.parse("Hello, World!") console.log("Latin1 Parsed:", words) let latin1 = CryptoJS.enc.Latin1.stringify(words) console.log("Latin1 Stringified", latin1) words = CryptoJS.enc.Hex.parse("48656c6c6f2c20576f726c6421") console.log("Hex Parsed:", words) let hex = CryptoJS.enc.Hex.stringify(words) console.log("Hex Stringified", hex) words = CryptoJS.enc.Utf8.parse("𔭢") console.log("Utf8 Parsed:", words) let utf8 = CryptoJS.enc.Utf8.stringify(words) console.log("Utf8 Stringified", utf8) words = CryptoJS.enc.Utf16.parse("Hello, World!") console.log("Utf16 Parsed:", words) let utf16 = CryptoJS.enc.Utf16.stringify(words) console.log("Utf16 Stringified", utf16) words = CryptoJS.enc.Utf16LE.parse("Hello, World!") console.log("Utf16LE Parsed:", words) utf16 = CryptoJS.enc.Utf16LE.stringify(words) console.log("Utf16LE Stringified", utf16) } catch (e) { console.error("Error:", e) } }
/// <reference path="../crypto.d.ts" />
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/internal/extension_repo/goja_bindings/goja_crypto_test/crypto-example.ts#L4-L101
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
run
async function run() { try { console.log("\nTesting torrent file to magnet link") const url = "https://animetosho.org/storage/torrent/da9aad67b6f8bb82757bb3ef95235b42624c34f7/%5BSubsPlease%5D%20Make%20Heroine%20ga%20Oosugiru%21%20-%2011%20%281080p%29%20%5B58B3496A%5D.torrent" const data = await (await fetch(url)).text() const magnetLink = getMagnetLinkFromTorrentData(data) console.log("Magnet link:", magnetLink) } catch (e) { console.error(e) } }
/// <reference path="../crypto.d.ts" />
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/internal/extension_repo/goja_bindings/goja_torrent_test/torrent-utils-example.ts#L5-L21
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
getTagContent
const getTagContent = (xml: string, tag: string): string => { const regex = new RegExp(`<${tag}[^>]*>([^<]*)</${tag}>`) const match = xml.match(regex) return match ? match[1].trim() : "" }
// Helper to extract content between XML tags
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/internal/extension_repo/goja_torrent_test/my-torrent-provider.ts#L74-L78
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
getNyaaTagContent
const getNyaaTagContent = (xml: string, tag: string): string => { const regex = new RegExp(`<nyaa:${tag}[^>]*>([^<]*)</nyaa:${tag}>`) const match = xml.match(regex) return match ? match[1].trim() : "" }
// Helper to extract content from nyaa namespace tags
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/internal/extension_repo/goja_torrent_test/my-torrent-provider.ts#L81-L85
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
_handleSeaError
function _handleSeaError(data: any): string { if (typeof data === "string") return "Server Error: " + data const err = data?.error as string if (!err) return "Unknown error" if (err.includes("Too many requests")) return "AniList: Too many requests, please wait a moment and try again." try { const graphqlErr = JSON.parse(err) as any console.log("AniList error", graphqlErr) if (graphqlErr.graphqlErrors && graphqlErr.graphqlErrors.length > 0 && !!graphqlErr.graphqlErrors[0]?.message) { return "AniList error: " + graphqlErr.graphqlErrors[0]?.message } return "AniList error" } catch (e) { return "Error: " + err } }
//----------------------------------------------------------------------------------------------------------------------
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/api/client/requests.ts#L118-L139
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
onFullscreenChange
function onFullscreenChange(ev?: Event) { if (getCurrentWebviewWindow().label !== "main") return if (platform() === "macos") { // ev?.preventDefault() if (!document.fullscreenElement) { getCurrentWebviewWindow().setTitleBarStyle("overlay").then() setDisplayDragRegion(true) setShowTrafficLights(true) } else { setDisplayDragRegion(false) setShowTrafficLights(false) } } else { getCurrentWebviewWindow().isFullscreen().then((fullscreen) => { console.log("setting displayDragRegion to", !fullscreen) setShowTrafficLights(!fullscreen) setDisplayDragRegion(!fullscreen) }) } }
// Check if the window is in fullscreen mode, and hide the traffic lights & drag region if it is
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/_tauri/tauri-window-title-bar.tsx#L39-L60
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
handleError
const handleError = (event: ErrorEvent) => { logger("chapter-page").info("retrying") if (retries.current >= 3) { setImageStatus(IMAGE_STATUS.ERROR) return } setImageStatus(IMAGE_STATUS.RETRYING) retries.current = retries.current + 1 const timerId = setTimeout(() => { const img = event.target as HTMLImageElement if (!img) { return } const imgSrc = img.src img.src = imgSrc // Already removes itself from the list of timerIds timerIds.splice(timerIds.indexOf(timerId), 1) }, 1000) timerIds.push(timerId) }
/** * if an image errors retry 3 times * @param {*} event */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/manga/_containers/chapter-reader/_components/chapter-page.tsx#L134-L158
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
getRecurringNumber
function getRecurringNumber(arr: number[]): number | undefined { const counts = new Map<number, number>() arr.forEach(num => { counts.set(num, (counts.get(num) || 0) + 1) }) let highestCount = 0 let highestNumber: number | undefined counts.forEach((count, num) => { if (count > highestCount) { highestCount = count highestNumber = num } }) return highestNumber }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/manga/_lib/handle-chapter-reader.ts#L386-L404
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
changeUrl
function changeUrl(newUrl: string | undefined) { logger("MEDIASTREAM").info("[changeUrl] called,", "request url:", newUrl) if (prevUrlRef.current !== newUrl) { logger("MEDIASTREAM").info("Resetting playback error status") setPlaybackErrored(false) } setUrl(prevUrl => { if (prevUrl === newUrl) { logger("MEDIASTREAM").info("[changeUrl] URL has not changed") return prevUrl } prevUrlRef.current = prevUrl logger("MEDIASTREAM").info("[changeUrl] URL updated") return newUrl }) if (newUrl) { definedUrlRef.current = newUrl } }
/** * Changes the stream URL * @param newUrl */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/mediastream/_lib/handle-mediastream.ts#L309-L327
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
onProviderChange
function onProviderChange(provider: MediaProviderAdapter | null, nativeEvent: MediaProviderChangeEvent) { if (isHLSProvider(provider) && mediaContainer?.streamType === "transcode") { logger("MEDIASTREAM").info("[onProviderChange] Provider changed to HLS") provider.library = HLS provider.config = { ...mediastream_getHlsConfig(), } } else { logger("MEDIASTREAM").info("[onProviderChange] Provider changed to native") } }
//////////////////////////////////////////////////////////////
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/mediastream/_lib/handle-mediastream.ts#L333-L343
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
onFatalError
const onFatalError = () => { logger("ONLINESTREAM").error("onFatalError", { sameProvider: provider == currentProviderRef.current, }) if (provider == currentProviderRef.current) { setUrl(undefined) logger("ONLINESTREAM").error("Setting stream URL to undefined") toast.info("Playback error, changing server") logger("ONLINESTREAM").error("Player encountered a fatal error") setTimeout(() => { logger("ONLINESTREAM").error("erroredServers", erroredServers) if (videoSource?.server) { const otherServers = servers.filter((server) => server !== videoSource?.server && !erroredServers.includes(server)) if (otherServers.length > 0) { setErroredServers((prev) => [...prev, videoSource?.server]) setServer(otherServers[0]) } else { setProvider((prev) => providerExtensionOptions.find((p) => p.value !== prev)?.value ?? null) } } }, 500) } }
/** * Handle fatal errors * This function is called when the player encounters a fatal error * - Change the server if the server is errored * - Change the provider if all servers are errored */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/onlinestream/_lib/handle-onlinestream.ts#L269-L291
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
onCanPlay
const onCanPlay = () => { logger("ONLINESTREAM").info("Can play event", { previousCurrentTime: previousCurrentTimeRef.current, previousIsPlayingRef: previousIsPlayingRef.current, }) // When the onCanPlay event is received // Restore the previous time if set if (previousCurrentTimeRef.current > 0) { // Seek to the previous time Object.assign(playerRef.current ?? {}, { currentTime: previousCurrentTimeRef.current }) // Reset the previous time ref previousCurrentTimeRef.current = 0 logger("ONLINESTREAM").info("Seeking to previous time", { previousCurrentTime: previousCurrentTimeRef.current }) } // If the player was playing before the onCanPlay event, resume playing setTimeout(() => { if (previousIsPlayingRef.current) { playerRef.current?.play() logger("ONLINESTREAM").info("Resuming playback since past video was playing before the onCanPlay event") } }, 500) }
/** * Handle the onCanPlay event */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/onlinestream/_lib/handle-onlinestream.ts#L296-L319
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
handleChangeEpisodeNumber
const handleChangeEpisodeNumber = (epNumber: number) => { setEpisodeNumber(_ => { return epNumber }) }
// Episode
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/app/(main)/onlinestream/_lib/handle-onlinestream.ts#L379-L383
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
listener
const listener: typeof handler = event => savedHandler.current(event)
// Create event listener that calls handler function stored in ref
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/components/ui/core/hooks.ts#L38-L38
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
withValueFormatter
function withValueFormatter<T extends any, R extends any = any>(callback: (value: T) => R) { return { valueFormatter: callback, } }
/* ------------------------------------------------------------------------------------------------- * Value formatter * -----------------------------------------------------------------------------------------------*/
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/components/ui/datagrid/helpers.ts#L95-L99
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
userAgentContains
function userAgentContains(key: string): boolean { const userAgent = navigator.userAgent || "" return userAgent.includes(key) }
/** * Check if the user agent of the navigator contains a key. * * @private * @static * @param key - Key for which to perform a check. * @returns Determines if user agent of navigator contains a key */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/browser-detection.ts#L35-L39
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
getDeviceProfile
function getDeviceProfile(videoTestElement: HTMLVideoElement) { // MaxStaticBitrate seems to be for offline sync only return { MaxStreamingBitrate: 120_000_000, MaxStaticBitrate: 0, MusicStreamingTranscodingBitrate: Math.min(120_000_000, 192_000), DirectPlayProfiles: getDirectPlayProfiles(videoTestElement), TranscodingProfiles: getTranscodingProfiles(videoTestElement), ContainerProfiles: [], CodecProfiles: getCodecProfiles(videoTestElement), SubtitleProfiles: getSubtitleProfiles(), ResponseProfiles: getResponseProfiles(), } }
/** * Creates a device profile containing supported codecs for the active Cast device. * * @param videoTestElement - Dummy video element for compatibility tests */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/playback-profiles/index.ts#L39-L52
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
getGlobalMaxVideoBitrate
function getGlobalMaxVideoBitrate(): number | undefined { let isTizenFhd = false if ( isTizen() && "webapis" in window && typeof window.webapis === "object" && window.webapis && "productinfo" in window.webapis && typeof window.webapis.productinfo === "object" && window.webapis.productinfo && "isUdPanelSupported" in window.webapis.productinfo && typeof window.webapis.productinfo.isUdPanelSupported === "function" ) { isTizenFhd = !window.webapis.productinfo.isUdPanelSupported() } /* * TODO: These values are taken directly from Jellyfin-web. * The source of them needs to be investigated. */ if (isPs4()) { return 8_000_000 } if (isXbox()) { return 12_000_000 } if (isTizen() && isTizenFhd) { return 20_000_000 } }
/** * Gets the max video bitrate * * @returns Returns the MaxVideoBitrate */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/playback-profiles/helpers/codec-profiles.ts#L14-L46
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
createProfileCondition
function createProfileCondition( Property: ProfileConditionValue, Condition: ProfileConditionType, Value: string, IsRequired = false, ): ProfileCondition { return { Condition, Property, Value, IsRequired, } }
/** * Creates a profile condition object for use in device playback profiles. * * @param Property - Value for the property * @param Condition - Condition that the property must comply with * @param Value - Value to check in the condition * @param IsRequired - Whether this property is required * @returns - Constructed ProfileCondition object */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/playback-profiles/helpers/codec-profiles.ts#L57-L69
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
supportsAc3InHls
function supportsAc3InHls( videoTestElement: HTMLVideoElement, ): boolean | string { if (isTv()) { return true } if (videoTestElement.canPlayType) { return ( videoTestElement .canPlayType("application/x-mpegurl; codecs=\"avc1.42E01E, ac-3\"") .replace(/no/, "") || videoTestElement .canPlayType( "application/vnd.apple.mpegURL; codecs=\"avc1.42E01E, ac-3\"", ) .replace(/no/, "") ) } return false }
/** * Check if client supports AC3 in HLS stream * * @param videoTestElement - A HTML video element for testing codecs * @returns Determines if the browser has AC3 in HLS support */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/playback-profiles/helpers/hls-formats.ts#L16-L37
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
seanime
github_2023
5rahim
typescript
hasVc1Support
function hasVc1Support(videoTestElement: HTMLVideoElement): boolean { return !!( isTv() || videoTestElement.canPlayType("video/mp4; codecs=\"vc-1\"").replace(/no/, "") ) }
/** * Check if the client has support for the VC1 codec * * @param videoTestElement - A HTML video element for testing codecs * @returns Determines if browser has VC1 support */
https://github.com/5rahim/seanime/blob/4102b492873ee29b2ae31b2b0c9eefb64a8cc60d/seanime-web/src/lib/utils/playback-profiles/helpers/mp4-video-formats.ts#L100-L105
4102b492873ee29b2ae31b2b0c9eefb64a8cc60d
cmdk-sv
github_2023
huntabyte
typescript
normalizeEmptyLines
function normalizeEmptyLines(line: Token[]) { if (line.length === 0) { line.push({ types: ['plain'], content: '\n', empty: true }); } else if (line.length === 1 && line[0].content === '') { line[0].content = '\n'; line[0].empty = true; } }
// Empty lines need to contain a single empty token, denoted with { empty: true }
https://github.com/huntabyte/cmdk-sv/blob/c9e8931aa7cd0cca71fef94262df6883626f49b7/src/docs/highlight.ts#L8-L19
c9e8931aa7cd0cca71fef94262df6883626f49b7
mode-watcher
github_2023
svecosystem
typescript
createUserPrefersMode
function createUserPrefersMode() { const defaultValue = "system"; const storage = isBrowser ? localStorage : noopStorage; const initialValue = storage.getItem(getModeStorageKey()); let value = isValidMode(initialValue) ? initialValue : defaultValue; function getModeStorageKey() { return get(modeStorageKey); } const { subscribe, set: _set } = writable(value, () => { if (!isBrowser) return; const handler = (e: StorageEvent) => { if (e.key !== getModeStorageKey()) return; const newValue = e.newValue; if (isValidMode(newValue)) { _set((value = newValue)); } else { _set((value = defaultValue)); } }; addEventListener("storage", handler); return () => removeEventListener("storage", handler); }); function set(v: Mode) { _set((value = v)); storage.setItem(getModeStorageKey(), value); } return { subscribe, set, }; }
// derived from: https://github.com/CaptainCodeman/svelte-web-storage
https://github.com/svecosystem/mode-watcher/blob/68b144e9bfacdca2418e93a4bd86a893f42df8e5/packages/mode-watcher/src/lib/stores.ts#L72-L108
68b144e9bfacdca2418e93a4bd86a893f42df8e5
mode-watcher
github_2023
svecosystem
typescript
query
function query() { if (!isBrowser) return; const mediaQueryState = window.matchMedia("(prefers-color-scheme: light)"); set(mediaQueryState.matches ? "light" : "dark"); }
/** * Query system preferences and update the store. */
https://github.com/svecosystem/mode-watcher/blob/68b144e9bfacdca2418e93a4bd86a893f42df8e5/packages/mode-watcher/src/lib/stores.ts#L165-L169
68b144e9bfacdca2418e93a4bd86a893f42df8e5
mode-watcher
github_2023
svecosystem
typescript
tracking
function tracking(active: boolean) { track = active; }
/** * Enable or disable tracking of system preference changes. */
https://github.com/svecosystem/mode-watcher/blob/68b144e9bfacdca2418e93a4bd86a893f42df8e5/packages/mode-watcher/src/lib/stores.ts#L174-L176
68b144e9bfacdca2418e93a4bd86a893f42df8e5
mode-watcher
github_2023
svecosystem
typescript
disable
const disable = () => document.head.appendChild(style);
// Functions to insert and remove style element
https://github.com/svecosystem/mode-watcher/blob/68b144e9bfacdca2418e93a4bd86a893f42df8e5/packages/mode-watcher/src/lib/without-transition.ts#L26-L26
68b144e9bfacdca2418e93a4bd86a893f42df8e5
vue-virt-list
github_2023
kolarorz
typescript
getScrollOffset
const getScrollOffset = () => clientRefEl.value ? clientRefEl.value.scrollTop : 0;
// 获取当前的容器的滚动偏移量
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/real-list/index.tsx#L92-L93
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
checkScrollStatus
const checkScrollStatus = (currentScrollOffset: number) => { if (props.list.length <= 0) return; if (currentScrollOffset <= props.scrollDistance) { reactiveData.begin = props.list[0][props.itemKey]; if (props.list.length > props.pageSize) { reactiveData.end = props.list[props.list.length - props.pageSize - 1][props.itemKey]; } else { reactiveData.end = props.list[props.list.length - 1][props.itemKey]; } emitFunction?.toTop?.(props.list[0]); // ctx.emit('toTop', props.list[0]); isScrollBottom.value = false; isScrollTop.value = true; } // 内容总高度 = 列表总高度 + 头部插槽高度 + 尾部插槽高度 // reactiveData.listTotalSize + slotSize.headerSize + slotSize.footerSize // 滚动高度 + 可视区域高度 + 阈值 >= 内容总高度 if ( currentScrollOffset + props.scrollDistance >= reactiveData.listTotalSize + getSlotSize() - slotSize.clientSize ) { reactiveData.end = props.list[props.list.length - 1][props.itemKey]; if (props.list.length > props.pageSize) { reactiveData.begin = props.list[props.pageSize][props.itemKey]; } else { reactiveData.begin = props.list[0][props.itemKey]; } emitFunction?.toBottom?.(props.list[props.list.length - 1]); // ctx.emit('toBottom', props.list[props.list.length - 1]); isScrollBottom.value = true; isScrollTop.value = false; } };
/** * @description 判断当前滚动的状态,判断是否触顶或者触底 * @param currentScrollOffset 当前列表滚动的偏移量 */
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/real-list/index.tsx#L188-L221
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollIntoView
const scrollIntoView = (index: number) => { // 滚动指定元素到可视区域 const targetMin = getItemOffset(props.list[index]?.[props.itemKey]); const scrollTargetToView = async ( targetMin: number, resolve: (val?: unknown) => void, ) => { // 如果没有拿到目标元素的位置,那么就等一下再去拿 if (targetMin === -1) { setTimeout(() => { const offset = getItemOffset(props.list[index]?.[props.itemKey]); scrollTargetToView(offset, resolve); }, 3); return; } const currentSize = getItemSize(props.list[index]?.[props.itemKey]); const targetMax = targetMin + currentSize; const offsetMin = getScrollOffset(); const offsetMax = getScrollOffset() + slotSize.clientSize; if ( targetMin < offsetMin && offsetMin < targetMax && currentSize < slotSize.clientSize ) { // 如果目标元素上方看不到,底部看得到,那么滚动到顶部部看得到就行了 scrollToOffset(targetMin + slotSize.headerSize); resolve(); return; } if ( targetMin + slotSize.stickyHeaderSize < offsetMax && offsetMax < targetMax + slotSize.stickyHeaderSize && currentSize < slotSize.clientSize ) { // 如果目标元素上方看得到,底部看不到,那么滚动到底部看得到就行了 scrollToOffset( targetMax - slotSize.clientSize + slotSize.stickyHeaderSize, ); resolve(); return; } // 屏幕下方 if (targetMin + slotSize.stickyHeaderSize >= offsetMax) { await scrollToIndex(index); resolve(); return; } // 屏幕上方 if (targetMax <= offsetMin) { await scrollToIndex(index); } resolve(); // 在中间就不动了 }; return new Promise((resolve) => { scrollTargetToView(targetMin, resolve); }); };
/** * @description 将指定下标的元素滚动到可视区域 * @param index 目标元素下标 */
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/real-list/index.tsx#L249-L311
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
getCurrentFirstItem
const getCurrentFirstItem = () => { let currentKey = ''; const currentScrollOffset = getScrollOffset(); const preDistance = currentScrollOffset + slotSize.stickyHeaderSize - slotSize.headerSize; const distance = preDistance < 0 ? 0 : preDistance; for (const [key, value] of offsetMap) { if (value <= distance && value + getItemSize(key) > currentScrollOffset) { currentKey = key; break; } } return currentKey; };
/** * @description 获取当前可视区域内的第一个元素的key * @returns 当前可视区域的一个元素的key */
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/real-list/index.tsx#L322-L335
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollToIndex
const scrollToIndex = (index: number) => { // 滚动到指定元素 if (index < 0) return; // 如果要去的位置大于长度,那么就直接调用去底部的方法 if (index >= props.list.length - 1) { scrollToBottom(); return; } const offset = getItemOffset(props.list[index]?.[props.itemKey]); const scrollToTargetOffset = ( targetOffset: number, resolve: (val?: unknown) => void, ) => { if (targetOffset === -1) { setTimeout(() => { const offset = getItemOffset(props.list[index]?.[props.itemKey]); scrollToTargetOffset(offset, resolve); }, 3); return; } scrollToOffset(targetOffset + slotSize.headerSize); resolve(); }; return new Promise((resolve) => { scrollToTargetOffset(offset, resolve); }); };
/** * @description 将指定下标的元素滚动到可视区域第一个位置 * @param index 目标元素下标 */
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/real-list/index.tsx#L341-L368
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollToLastIndex
function scrollToLastIndex(newGridItems: number, oldGridItems: number) { const reactiveData = virtListRef?.value?.getReactiveData(); if (reactiveData) { const targetRowIndex = Math.floor( (reactiveData?.inViewBegin * oldGridItems) / newGridItems, ); nextTick(() => { virtListRef?.value?.scrollToIndex(targetRowIndex); }); } }
// 滚动到上次的index位置
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-grid/index.tsx#L67-L77
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
getItemPosByIndex
function getItemPosByIndex(index: number) { if (props.fixed) { return { top: (props.minSize + props.itemGap) * index, current: props.minSize + props.itemGap, bottom: (props.minSize + props.itemGap) * (index + 1), }; } const { itemKey } = props; let topReduce = slotSize.headerSize; for (let i = 0; i <= index - 1; i += 1) { const currentSize = getItemSize(props.list[i]?.[itemKey]); topReduce += currentSize; } const current = getItemSize(props.list[index]?.[itemKey]); return { top: topReduce, current, bottom: topReduce + current, }; }
// 通过下标来获取元素位置信息
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L145-L166
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollToIndex
async function scrollToIndex(index: number) { if (index < 0) { return; } // 如果要去的位置大于长度,那么就直接调用去底部的方法 if (index >= props.list.length - 1) { scrollToBottom(); return; } let { top: lastOffset } = getItemPosByIndex(index); scrollToOffset(lastOffset); // 这里不适用settimeout,因为无法准确把控延迟时间,3ms有可能页面还拿不到高度。 const fixToIndex = () => { const { top: offset } = getItemPosByIndex(index); scrollToOffset(offset); if (lastOffset !== offset) { lastOffset = offset; fixTaskFn = fixToIndex; return; } // 重置后如果不需要修正,将修正函数置空 fixTaskFn = null; }; fixTaskFn = fixToIndex; }
// expose 滚动到指定下标
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L174-L202
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
fixToIndex
const fixToIndex = () => { const { top: offset } = getItemPosByIndex(index); scrollToOffset(offset); if (lastOffset !== offset) { lastOffset = offset; fixTaskFn = fixToIndex; return; } // 重置后如果不需要修正,将修正函数置空 fixTaskFn = null; };
// 这里不适用settimeout,因为无法准确把控延迟时间,3ms有可能页面还拿不到高度。
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L190-L200
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollIntoView
async function scrollIntoView(index: number) { const { top: targetMin, bottom: targetMax } = getItemPosByIndex(index); const offsetMin = getOffset(); const offsetMax = getOffset() + slotSize.clientSize; const currentSize = getItemSize(props.list[index]?.[props.itemKey]); if ( targetMin < offsetMin && offsetMin < targetMax && currentSize < slotSize.clientSize ) { // 如果目标元素上方看不到,底部看得到,那么滚动到顶部部看得到就行了 scrollToOffset(targetMin); return; } if ( targetMin + slotSize.stickyHeaderSize < offsetMax && offsetMax < targetMax + slotSize.stickyHeaderSize && currentSize < slotSize.clientSize ) { // 如果目标元素上方看得到,底部看不到,那么滚动到底部看得到就行了 scrollToOffset( targetMax - slotSize.clientSize + slotSize.stickyHeaderSize, ); return; } // 屏幕下方 if (targetMin + slotSize.stickyHeaderSize >= offsetMax) { scrollToIndex(index); return; } // 屏幕上方 if (targetMax <= offsetMin) { scrollToIndex(index); return; } // 在中间就不动了 }
// expose 滚动到可视区域
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L204-L243
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollToTop
async function scrollToTop() { let count = 0; function loopScrollToTop() { count += 1; scrollToOffset(0); setTimeout(() => { if (count > 10) { return; } const directionKey = props.horizontal ? 'scrollLeft' : 'scrollTop'; // 因为纠正滚动条会有误差,所以这里需要再次纠正 if (clientRefEl?.value?.[directionKey] !== 0) { loopScrollToTop(); } }, 3); } loopScrollToTop(); }
// expose 滚动到顶部,这个和去第一个元素不同
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L245-L262
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
scrollToBottom
async function scrollToBottom() { let count = 0; function loopScrollToBottom() { count += 1; scrollToOffset(getTotalSize()); setTimeout(() => { // 做一次拦截,防止异常导致的死循环 if (count > 10) { return; } // 修复底部误差,因为缩放屏幕的时候,获取的尺寸都是小数,精度会有问题,这里把误差调整为2px if ( Math.abs( Math.round(reactiveData.offset + slotSize.clientSize) - Math.round(getTotalSize()), ) > 2 ) { loopScrollToBottom(); } }, 3); } loopScrollToBottom(); }
// expose 滚动到底部
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L264-L286
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
fixSelection
function fixSelection() { const selection = window.getSelection(); if (selection) { const { anchorNode, anchorOffset, focusNode, focusOffset } = selection; if ( anchorNode && anchorOffset !== null && focusNode !== null && focusOffset ) { requestAnimationFrame(() => { if (anchorOffset < focusOffset) { selection.setBaseAndExtent( anchorNode, anchorOffset, focusNode, focusOffset, ); } else { selection.setBaseAndExtent( focusNode, focusOffset, anchorNode, anchorOffset, ); } }); } } }
// 修复vue2-diff的bug导致的selection问题
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L289-L318
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
deletedList2Top
function deletedList2Top(deletedList: T[]) { calcListTotalSize(); let deletedListSize = 0; deletedList.forEach((item) => { deletedListSize += getItemSize(item[props.itemKey]); }); updateTotalVirtualSize(); scrollToOffset(reactiveData.offset - deletedListSize); calcRange(); }
// expose only
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L490-L499
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
addedList2Top
function addedList2Top(addedList: T[]) { calcListTotalSize(); let addedListSize = 0; addedList.forEach((item) => { addedListSize += getItemSize(item[props.itemKey]); }); updateTotalVirtualSize(); scrollToOffset(reactiveData.offset + addedListSize); forceFixOffset = true; abortFixOffset = false; calcRange(); }
// expose only
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-list/index.tsx#L501-L512
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
autoScroll
function autoScroll() { if (scrollElement !== null && scrollElementRect !== undefined) { // 每次先清除旧定时器 if (autoScrollTimer) { clearInterval(autoScrollTimer); autoScrollTimer = null; } // 判断是否在可视区域 if (clientElementRect) { if ( mouseX < clientElementRect.left || mouseX > clientElementRect.right || mouseY < clientElementRect.top || mouseY > clientElementRect.bottom ) { return; } } // 4等分 const equalPart = scrollElementRect.height / 4; const multiple = 20; if ( scrollElementRect.top < mouseY && mouseY < scrollElementRect.top + equalPart ) { const relative = (1 - (mouseY - scrollElementRect.top) / equalPart) * multiple; if (!autoScrollTimer) { autoScrollTimer = setInterval(() => { scrollElement!.scrollTop -= relative; }, 10); } } else if ( scrollElementRect.top + equalPart * 3 < mouseY && mouseY < scrollElementRect.bottom ) { const relative = ((mouseY - (scrollElementRect.top + equalPart * 3)) / equalPart) * multiple; if (!autoScrollTimer) { autoScrollTimer = setInterval(() => { scrollElement!.scrollTop += relative; }, 10); } } } }
// 自动滚动
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-tree/useDrag.ts#L179-L225
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
expandParents
const expandParents = (node: TreeNode) => { if (!node.isLeaf) { expandedKeysSet.value.add(node.key); } if (!node?.parent) return; expandParents(node.parent); };
// 展开节点需要展开所有parent节点
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/components/virt-tree/useExpand.ts#L56-L62
916cd43af515d7f295b3de84887f1279cb6cb92a
vue-virt-list
github_2023
kolarorz
typescript
vue3h2Slot
function vue3h2Slot<P>( ele: | Component< Readonly< P extends ComponentPropsOptions<Data> ? ExtractPropTypes<P> : P >, any, any, ComputedOptions, MethodOptions, {}, any > | string, props: Props, slots?: any, ) { const { attrs, on, ...rest } = props; let event: Record<string, () => void> = {}; if (on) { Object.entries(on).forEach((item) => { const [key, value] = item as [string, () => void]; const eventName = `on${key[0].toUpperCase() + key.slice(1)}`; event[eventName] = value; }); } return h(ele, { ...attrs, ...event, ...rest } as any, slots); }
// vue3 渲染slot时推荐使用functional
https://github.com/kolarorz/vue-virt-list/blob/916cd43af515d7f295b3de84887f1279cb6cb92a/src/utils/index.ts#L159-L186
916cd43af515d7f295b3de84887f1279cb6cb92a
directus-sync
github_2023
tractr
typescript
IdMapper.init
async init(): Promise<boolean> { if (!(await this.database.schema.hasTable(this.tableName))) { await this.database.schema.createTable(this.tableName, (table) => { table.increments('id').primary(); table.string('table').notNullable(); table.string('sync_id').notNullable(); table.string('local_id').notNullable(); table.timestamp('created_at').defaultTo(this.database.fn.now()); table.unique(['table', 'sync_id']); table.unique(['table', 'local_id']); table.index(['created_at']); }); return true; } return false; }
/** * Init the id mapper by creating the table if it doesn't exist * returns true if the table was created, false if it already existed */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L21-L36
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.getTableName
getTableName(): string { return this.tableName; }
/** * Get the table name */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L41-L43
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.getBySyncId
async getBySyncId(table: string, syncId: string): Promise<IdMap | null> { const result: IdMap = await this.database(this.tableName) .where({ table, sync_id: syncId }) .first(); return result || null; }
/** * Returns the local key for the given table and sync id */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L48-L53
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.getByLocalId
async getByLocalId( table: string, localId: string | number, ): Promise<IdMap | null> { const result: IdMap = await this.database(this.tableName) .where({ table, local_id: localId }) .first(); return result || null; }
/** * Returns the sync id for the given table and local id */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L58-L66
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.getAll
async getAll(table: string): Promise<IdMap[]> { return this.database(this.tableName).where({ table }); }
/** * Get all entries for the given table */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L71-L73
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.add
async add( table: string, localId: number | string, syncId?: string, ): Promise<string> { const finalSyncId = syncId ?? randomUUID(); await this.database(this.tableName).insert({ table, sync_id: finalSyncId, local_id: localId, }); return finalSyncId; }
/** * Adds a new entry to the id map * Generates a new sync id if not provided. * Sync id will be provided when restoring data, and not provided when backing up data. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L80-L92
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.removeBySyncId
async removeBySyncId(table: string, syncId: string): Promise<void> { await this.database(this.tableName) .where({ table, sync_id: syncId }) .delete(); }
/** * Removes an entry from the id map using the sync id */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L97-L101
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
IdMapper.removeByLocalId
async removeByLocalId( table: string, localId: number | string, ): Promise<void> { await this.database(this.tableName) .where({ table, local_id: localId }) .delete(); }
/** * Removes an entry from the id map using the local id */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/id-mapper.ts#L106-L113
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
Permissions.removeDuplicates
async removeDuplicates(keep: 'first' | 'last') { const policies = await this.getPoliciesCollectionsAndActions(); const output: DeletedPermission[] = []; for (const [policy, collections] of policies) { for (const [collection, actions] of collections) { for (const action of actions) { const permissions: Permission[] = await this.database(this.tableName) .where({ policy, collection, action }) .orderBy('id', 'asc'); if (permissions.length > 1) { // Log the duplicated permissions this.logger.warn( `Duplicated permissions for policy ${policy}, collection ${collection}, action ${action} (${permissions.length} permissions)`, ); // Keep the last permission and delete the rest const [toKeep, ...rest] = ( keep === 'first' ? permissions : permissions.reverse() ) as [Permission, ...Permission[]]; const ids = rest.map((permission) => permission.id); await this.database(this.tableName).whereIn('id', ids).delete(); output.push({ policy, collection, action, ids }); this.logger.info( `Deleted ${ids.length} duplicated permissions, keeping permission ${toKeep.id}`, ); } } } } return output; }
/** * Remove duplicated permissions */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/api/src/database/permissions.ts#L29-L64
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
cleanProgramOptions
function cleanProgramOptions(programOptions: Record<string, unknown>) { return programOptions; }
/** * Remove some default values from the program options that overrides the config file */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/program.ts#L20-L22
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
cleanCommandOptions
function cleanCommandOptions(commandOptions: Record<string, unknown>) { if (commandOptions.snapshot === true) { delete commandOptions.snapshot; } if (commandOptions.split === true) { delete commandOptions.split; } if (commandOptions.specs === true) { delete commandOptions.specs; } return commandOptions; }
/** * Remove some default values from the command options that overrides the config file */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/program.ts#L27-L38
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
commaSeparatedList
function commaSeparatedList(value: string) { return value.split(',').map((v) => v.trim()); }
/** * Split a comma separated list */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/program.ts#L65-L67
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
commaSeparatedListOrAll
function commaSeparatedListOrAll(value: string) { const v = value.trim(); if (v === '*' || v === 'all') { return v; } return commaSeparatedList(value); }
/** * Split a comma separated list unless the value is "all" or "*" */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/program.ts#L72-L78
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
MigrationClient.clearCache
async clearCache() { const directus = await this.get(); await directus.request(clearCache()); this.logger.debug('Cache cleared'); }
/** * This method clears the cache of the Directus instance */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/migration-client.ts#L50-L54
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
MigrationClient.compareWithDirectusVersion
protected async compareWithDirectusVersion( version: string, ): Promise<'equal' | 'greater' | 'smaller'> { const directusVersion = await this.getDirectusVersion(); const diff = compareVersions(version, directusVersion); if (diff === 0) { return 'equal'; } else if (diff > 0) { return 'greater'; } else { return 'smaller'; } }
/** * This method compares the Directus instance version with the given one. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/migration-client.ts#L102-L114
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
MigrationClient.validateDirectusVersion
async validateDirectusVersion() { const directusVersion = await this.getDirectusVersion(); if ((await this.compareWithDirectusVersion('10.0.0')) === 'greater') { throw new Error( `This CLI is not compatible with Directus ${directusVersion}. Please upgrade Directus to 10.0.0 (or higher).`, ); } if ((await this.compareWithDirectusVersion('11.0.0')) === 'greater') { throw new Error( `This CLI is not compatible with Directus ${directusVersion}. Please use \`npx directus-sync@2.2.0 [command]\` or upgrade Directus to 11.0.0 (or higher).`, ); } this.logger.debug(`Directus ${directusVersion} is compatible`); }
/** * This method validate that the Directus instance version is compatible with the current CLI version. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/migration-client.ts#L119-L132
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PingClient.test
async test() { const response = await this.fetch<unknown>( `/table/__ping_test__/sync_id/__ping_test__`, 'GET', ) .then(() => ({ success: true })) .catch((error: Error) => ({ error })); if ('success' in response) { return; // Should not happen } if (response.error.message === NO_ID_MAP_MESSAGE) { return; } throw response.error; }
/** Try to get a fake id map in order to check if the server is up and the extension is installed */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/ping-client.ts#L12-L29
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
FlowsCollection.create
protected async create( toCreate: WithSyncIdAndWithoutId<DirectusFlow>[], ): Promise<boolean> { const shouldRetry = toCreate.length > 0; const toCreateWithoutOperations = toCreate.map((flow) => { return { ...flow, operation: null, }; }); await super.create(toCreateWithoutOperations); return shouldRetry; }
/** * Override the methods in order to break dependency cycle between flows and operations * Always create new flows without reference to operations. Then update the flow once the operations are created. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/flows/collection.ts#L52-L64
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PermissionsDataClient.query
async query<T extends object = DirectusPermission>( query: Query<DirectusPermission>, ): Promise<T[]> { const values = await super.query(query); return values.filter((value) => !!value.id) as T[]; }
/** * Returns the admins permissions. These are static permissions that are not stored in the database. * We must discard them as they can't be updated and have no id. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/permissions/data-client.ts#L30-L35
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PermissionsDataDiffer.getExistingIds
protected async getExistingIds( localIds: string[], ): Promise<{ id: DirectusId }[]> { const permissions = await this.dataClient.query({ filter: { id: { _in: localIds.map(Number), }, }, limit: -1, fields: ['id', 'policy', 'collection', 'action'], } as Query<DirectusPermission>); return permissions.map(({ id }) => ({ id })); }
/** * Add more fields in the request to get id field * https://github.com/directus/directus/issues/21965 */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/permissions/data-differ.ts#L35-L49
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PoliciesIdMapperClient.create
async create(localId: string | number, syncId?: string): Promise<string> { const adminPolicyId = await this.getAdminPolicyId(); if (localId === adminPolicyId) { return await super.create(localId, this.adminPolicyPlaceholder); } const publicPolicyId = await this.getPublicPolicyId(); if (localId === publicPolicyId) { return await super.create(localId, this.publicPolicyPlaceholder); } return await super.create(localId, syncId); }
/** * Force admin and public policies placeholders for the admin and public policies. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/policies/id-mapper-client.ts#L36-L46
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PoliciesIdMapperClient.getBySyncId
async getBySyncId(syncId: string): Promise<IdMap | undefined> { const idMap = await super.getBySyncId(syncId); if (!idMap) { // Automatically create the default admin policy id map if it doesn't exist if (syncId === this.adminPolicyPlaceholder) { const adminPolicyId = await this.getAdminPolicyId(); if (adminPolicyId) { await super.create(adminPolicyId, this.adminPolicyPlaceholder); this.logger.debug( `Created admin policy id map with local id ${adminPolicyId}`, ); return await super.getBySyncId(syncId); } } // Automatically create the default public policy id map if it doesn't exist else if (syncId === this.publicPolicyPlaceholder) { const publicPolicyId = await this.getPublicPolicyId(); if (publicPolicyId) { await super.create(publicPolicyId, this.publicPolicyPlaceholder); this.logger.debug( `Created public policy id map with local id ${publicPolicyId}`, ); return await super.getBySyncId(syncId); } } } return idMap; }
/** * Create the sync id of the admin and public policies on the fly, as it already has been synced. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/policies/id-mapper-client.ts#L51-L79
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PoliciesIdMapperClient.getAdminPolicyId
protected async getAdminPolicyId() { if (!this.adminPolicyFetched) { const directus = await this.migrationClient.get(); const adminRoleId = await this.rolesIdMapperClient.getAdminRoleId(); const [policy] = await directus.request( readPolicies({ fields: ['id'], filter: { _and: [ { roles: { role: { _eq: adminRoleId } } }, { admin_access: { _eq: true } }, ], }, limit: 1, }), ); if (!policy) { this.logger.debug( 'Cannot find the admin policy attached to the admin role', ); } this.adminPolicyId = policy?.id; this.adminPolicyFetched = true; } return this.adminPolicyId; }
/** * Returns the default admin policy, attached to the admin role. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/policies/id-mapper-client.ts#L84-L111
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
PoliciesIdMapperClient.getPublicPolicyId
protected async getPublicPolicyId() { if (!this.publicPolicyFetched) { const directus = await this.migrationClient.get(); const [policy] = await directus.request( readPolicies({ fields: ['id'], filter: { _and: [ { roles: { role: { _null: true } } }, { _or: [ { roles: { sort: { _eq: 1 } } }, // Allow to find the policy even if the sort is not set. // This may occur after migrations from 10.x to 11.x { roles: { sort: { _null: true } } }, ], }, ], }, limit: 1, }), ); if (!policy) { this.logger.debug('Cannot find the public policy'); } this.publicPolicyId = policy?.id; this.publicPolicyFetched = true; } return this.publicPolicyId; }
/** * Returns the default public policy, where role = null */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/policies/id-mapper-client.ts#L116-L147
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
RolesIdMapperClient.getAdminRoleId
async getAdminRoleId() { if (!this.adminRoleId) { const directus = await this.migrationClient.get(); const { role } = await directus.request( readMe({ fields: ['role'], }), ); this.adminRoleId = role as string; } return this.adminRoleId; }
/** * This method return the role of the current user as the Admin role */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/roles/id-mapper-client.ts#L33-L44
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
RolesIdMapperClient.create
async create(localId: string | number, syncId?: string): Promise<string> { const adminRoleId = await this.getAdminRoleId(); if (localId === adminRoleId) { return await super.create(localId, this.adminRolePlaceholder); } return await super.create(localId, syncId); }
/** * Force admin role placeholder for the admin role. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/roles/id-mapper-client.ts#L49-L55
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
RolesIdMapperClient.getBySyncId
async getBySyncId(syncId: string): Promise<IdMap | undefined> { // Automatically create the default admin role id map if it doesn't exist if (syncId === this.adminRolePlaceholder) { const idMap = await super.getBySyncId(syncId); if (idMap) { return idMap; } const adminRoleId = await this.getAdminRoleId(); await super.create(adminRoleId, this.adminRolePlaceholder); this.logger.debug( `Created admin role id map with local id ${adminRoleId}`, ); } return await super.getBySyncId(syncId); }
/** * Create the sync id of the admin role on the fly, as it already has been synced. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/collections/roles/id-mapper-client.ts#L60-L74
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
ConfigService.getLogger
protected getLogger() { const baseLogger = Container.get<pino.Logger>(LOGGER); return getChildLogger(baseLogger, 'config'); }
/** * Returns a temporary logger as it may be changed by another one with specific options * See loader.ts file for more information */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/config/config.ts#L232-L235
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.push
async push(data: SeedData): Promise<boolean> { // Convert data to the expected format const sourceData = data.map(({ _sync_id, ...rest }) => ({ ...rest, _syncId: _sync_id, })); // Get the diff between source and target data const { toCreate, toUpdate, toDelete } = await this.dataDiffer.getDiff(sourceData); let shouldRetryCreate = false; let shouldRetryUpdate = false; // Process items based on meta configuration if (this.meta.create) { shouldRetryCreate = await this.create(toCreate); } if (this.meta.update) { shouldRetryUpdate = await this.update(toUpdate); } if (this.meta.delete) { await this.delete(toDelete); } return shouldRetryCreate || shouldRetryUpdate; }
/** * Push the seed data to the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L46-L74
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.cleanUp
async cleanUp() { const dangling = await this.dataDiffer.getDanglingIds(); await this.removeDangling(dangling); this.idMapper.clearCache(); }
/** * Clean up dangling dangling items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L79-L83
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.create
protected async create( toCreate: WithSyncId<DirectusUnknownType>[], ): Promise<boolean> { let shouldRetry = false; for (const sourceItem of toCreate) { try { const mappedItem = await this.dataMapper.mapSyncIdToLocalId(sourceItem); if (!mappedItem) { shouldRetry = true; continue; } const { _syncId, ...createPayload } = mappedItem; if (this.meta.preserve_ids) { createPayload.id = _syncId as DirectusId; } const newItem = await this.dataClient.create(createPayload); const primaryKey = await this.getPrimaryKey(newItem); await this.idMapper.create(primaryKey, _syncId); this.logger.debug(sourceItem, 'Created item'); } catch (error) { await this.handleCreationError(error, sourceItem); } } this.debugOrInfo(toCreate.length > 0, `Created ${toCreate.length} items`); if (shouldRetry) { this.logger.warn('Some items could not be created and will be retried'); } return shouldRetry; }
/** * Create new items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L88-L121
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.update
protected async update( toUpdate: { sourceItem: WithSyncId<DirectusUnknownType>; targetItem: WithSyncId<DirectusUnknownType>; diffItem: Partial<WithSyncId<DirectusUnknownType>>; }[], ): Promise<boolean> { let shouldRetry = false; for (const { targetItem, diffItem } of toUpdate) { const mappedItem = await this.dataMapper.mapSyncIdToLocalId(diffItem); if (!mappedItem) { shouldRetry = true; continue; } const primaryKey = await this.getPrimaryKey(targetItem); await this.dataClient.update(primaryKey, mappedItem); this.logger.debug(diffItem, `Updated ${primaryKey}`); } this.debugOrInfo(toUpdate.length > 0, `Updated ${toUpdate.length} items`); if (shouldRetry) { this.logger.warn('Some items could not be updated and will be retried'); } return shouldRetry; }
/** * Update existing items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L126-L153
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.delete
protected async delete(toDelete: { local_id: string; sync_id: string }[]) { for (const item of toDelete) { await this.dataClient.delete(item.local_id); await this.idMapper.removeBySyncId(item.sync_id); this.logger.debug(item, `Deleted ${item.local_id}`); } this.debugOrInfo(toDelete.length > 0, `Deleted ${toDelete.length} items`); }
/** * Delete items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L158-L165
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.removeDangling
protected async removeDangling( dangling: { local_id: string; sync_id: string }[], ) { for (const item of dangling) { await this.idMapper.removeBySyncId(item.sync_id); this.logger.debug(item, `Removed dangling id map`); } this.debugOrInfo( dangling.length > 0, `Removed ${dangling.length} dangling items`, ); }
/** * Remove dangling items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L170-L181
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.handleCreationError
protected async handleCreationError( error: unknown, item: WithSyncId<DirectusUnknownType>, ): Promise<void> { const flattenError = unwrapDirectusRequestError(error); if (this.meta.preserve_ids && flattenError.code === 'RECORD_NOT_UNIQUE') { const [existingItem] = await this.dataClient.queryByPrimaryField( item._syncId, ); if (existingItem) { this.logger.warn( { item }, `Item ${item._syncId} already exists but id map was missing. Will recreate id map.`, ); await this.idMapper.create( await this.getPrimaryKey(existingItem), item._syncId, ); return; } throw new Error( `Cannot find item that should already exist. Previous error: ${flattenError.message}`, ); } throw error; }
/** * Handle creation errors */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L186-L215
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.getPrimaryKey
protected async getPrimaryKey(item: DirectusUnknownType): Promise<string> { const primaryFieldName = await this.getPrimaryFieldName(); return item[primaryFieldName] as string; }
/** * Get the primary key from an item */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L220-L223
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.getPrimaryFieldName
protected async getPrimaryFieldName(): Promise<string> { return (await this.schemaClient.getPrimaryField(this.collection)).name; }
/** * Get the primary field name */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L228-L230
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedCollection.diff
async diff(data: SeedData) { // Convert data to the expected format const sourceData = data.map(({ _sync_id, ...rest }) => ({ ...rest, _syncId: _sync_id, })); // Get the diff between source and target data const { toCreate, toUpdate, toDelete, unchanged, dangling } = await this.dataDiffer.getDiff(sourceData); // Log dangling items this.debugOrInfo( dangling.length > 0, `Dangling id maps: ${dangling.length} item(s)`, ); for (const idMap of dangling) { this.logger.debug(idMap, `Will remove dangling id map`); } // Log items to create this.debugOrInfo( toCreate.length > 0, `To create: ${toCreate.length} item(s)`, ); for (const item of toCreate) { this.logger.info(item, `Will create item`); } // Log items to update this.debugOrInfo( toUpdate.length > 0, `To update: ${toUpdate.length} item(s)`, ); for (const { targetItem, diffItem } of toUpdate) { const primaryKey = await this.getPrimaryKey(targetItem); this.logger.info(diffItem, `Will update item (${primaryKey})`); } // Log items to delete this.debugOrInfo( toDelete.length > 0, `To delete: ${toDelete.length} item(s)`, ); for (const item of toDelete) { this.logger.info(item, `Will delete item (${item.local_id})`); } // Log unchanged items this.logger.debug(`Unchanged: ${unchanged.length} item(s)`); for (const item of unchanged) { const primaryKey = await this.getPrimaryKey(item); this.logger.debug(`Item ${primaryKey} is unchanged`); } }
/** * Display the diff between source and target data */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/collection.ts#L235-L289
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataClient.query
async query<T extends DirectusUnknownType>(query: Query<T>): Promise<T[]> { const directus = await this.migrationClient.get(); const response = await directus.request<T | T[]>( readMany(this.collection, query), ); if (Array.isArray(response)) { return response; } // Some collections return a single object instead of an array if (!response || typeof response !== 'object') { return []; } return [response]; }
/** * Request data from the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-client.ts#L29-L45
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataClient.queryByPrimaryField
async queryByPrimaryField<T extends DirectusUnknownType>( values: string | string[], query: Query<T> = {}, ): Promise<T[]> { const primaryField = await this.schemaClient.getPrimaryField( this.collection, ); const isNumber = primaryField.type === Type.Integer; const isArray = Array.isArray(values); const castedValues = isNumber ? isArray ? values.map(Number) : Number(values) : values; const filter: Query<T> = Array.isArray(castedValues) ? { filter: { [primaryField.name]: { _in: castedValues } } } : { filter: { [primaryField.name]: { _eq: castedValues } } }; return await this.query<T>(deepmerge(filter, query)); }
/** * Query by primary field (one or multiple values) */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-client.ts#L50-L70
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataClient.create
async create<T extends DirectusUnknownType>(data: Partial<T>): Promise<T> { const directus = await this.migrationClient.get(); return await directus.request<T>(createOne(this.collection, data)); }
/** * Create a new item in the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-client.ts#L75-L78
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataClient.update
async update<T extends DirectusUnknownType>( key: DirectusId, data: Partial<T>, ): Promise<T> { const directus = await this.migrationClient.get(); return await directus.request<T>(updateOne(this.collection, key, data)); }
/** * Update an item in the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-client.ts#L83-L89
20afa386e3c75e7eedfd6b629b323b8a34636e9f