repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
cosmo
github_2023
wundergraph
typescript
FederatedGraphRepository.bySubgraphLabels
public async bySubgraphLabels(data: { labels: Label[]; namespaceId: string; excludeContracts?: boolean; }): Promise<FederatedGraphDTO[]> { const uniqueLabels = normalizeLabels(data.labels); const graphs = await this.db .select({ id: targets.id, name: targets.name, }) ...
/** * bySubgraphLabels returns federated graphs whose label matchers satisfy the given subgraph labels. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/FederatedGraphRepository.ts#L650-L721
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
FederatedGraphRepository.addSchemaVersion
public addSchemaVersion({ targetId, composedSDL, clientSchema, compositionErrors, compositionWarnings, composedSubgraphs, composedById, schemaVersionId, isFeatureFlagComposition, featureFlagId, }: { targetId: string; schemaVersionId: string; composedSDL?: string; ...
/** * addSchemaVersion adds a new schema version to the given federated graph. When * the schema version is not composable the errors are stored in the compositionErrors * but the composedSchemaVersionId is not updated. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/FederatedGraphRepository.ts#L728-L829
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
FederatedGraphRepository.getLatestValidSchemaVersion
public async getLatestValidSchemaVersion(data: { targetId: string }) { const latestValidVersion = await this.db .select({ name: targets.name, schemaSDL: schemaVersion.schemaSDL, clientSchema: schemaVersion.clientSchema, schemaVersionId: schemaVersion.id, }) .from(ta...
// returns the latest valid schema version of a federated graph
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/FederatedGraphRepository.ts#L857-L895
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
FederatedGraphRepository.composeAndDeployGraphs
public composeAndDeployGraphs = ({ federatedGraphs, blobStorage, admissionConfig, actorId, chClient, }: { federatedGraphs: FederatedGraphDTO[]; blobStorage: BlobStorage; admissionConfig: { webhookJWTSecret: string; cdnBaseUrl: string; }; actorId: string; chClien...
/** * This method recomposes and deploys federated graphs and their respective contract graphs. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/FederatedGraphRepository.ts
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationInvitationRepository.getPendingInvitationsOfOrganization
public getPendingInvitationsOfOrganization(input: { organizationId: string; offset?: number; limit?: number; search?: string; }): Promise<OrganizationInvitationDTO[]> { const conditions: SQL<unknown>[] = [ eq(organizationInvitations.organizationId, input.organizationId), eq(organizatio...
// returns the members who have pending invites to the provided organization.
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationInvitationRepository.ts#L19-L53
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationInvitationRepository.getPendingInvitationsOfUser
public async getPendingInvitationsOfUser(input: { userId: string; }): Promise<(Omit<OrganizationDTO, 'billing' | 'subscription'> & { invitedBy: string | undefined })[]> { const users1 = alias(users, 'users1'); const pendingOrgInvites = await this.db .select({ id: organizations.id, n...
// returns the organizations to which the user has a pending invite.
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationInvitationRepository.ts#L76-L105
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationRepository.getFeatures
public async getFeatures(input: { organizationId: string; plan?: string }): Promise<Feature[]> { let plan = input.plan; if (!input.plan) { const billing = await this.db.query.organizationBilling.findFirst({ where: eq(organizationBilling.organizationId, input.organizationId), columns: { ...
/** * Get the features for an organization. A feature can be enabled or disabled and can have a limit. * Usually, a feature without a limit is just a boolean flag. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationRepository.ts#L503-L561
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationRepository.deleteOrganization
public deleteOrganization(organizationId: string, blobStorage: BlobStorage) { return this.db.transaction(async (tx) => { const fedGraphRepo = new FederatedGraphRepository(this.logger, tx, organizationId); const targetRepo = new TargetRepository(tx, organizationId); const graphs = await fedGraphRe...
/** This manually deletes graphs from db and blob storage. Everything else is deleted automatically by db constraints */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationRepository.ts#L859-L882
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationRepository.canUserBeDeleted
public async canUserBeDeleted(id: string): Promise<{ isSafe: boolean; soloOrganizations: OrganizationDTO[]; unsafeOrganizations: OrganizationDTO[]; }> { const { soloAdminManyMembersOrgs, soloAdminSoloMemberOrgs } = await this.adminMemberships({ userId: id, }); const isSafe = soloAdminMa...
/*** * Checks if the user can be deleted. * It returns with isSafe=false if the user is the only admin of one or more multi member organizations along with said organizations. * It also returns organizations where the user is the only member. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationRepository.ts#L1300-L1316
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OrganizationRepository.deactivateOrganization
public async deactivateOrganization(input: { organizationId: string; reason?: string; keycloakClient: Keycloak; keycloakRealm: string; deleteOrganizationQueue: DeleteOrganizationQueue; }) { const billingRepo = new BillingRepository(this.db); await billingRepo.cancelSubscription(input.organ...
/*** * Cancels Subscription * Removes any feature overrides * Sets deactivated to true. * Schedules deletion. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/OrganizationRepository.ts#L1324-L1361
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphRepository.listByFederatedGraph
public async listByFederatedGraph(data: { federatedGraphTargetId: string; published?: boolean; }): Promise<SubgraphDTO[]> { const target = await this.db.query.targets.findFirst({ where: and( eq(schema.targets.id, data.federatedGraphTargetId), eq(schema.targets.organizationId, this.or...
/** * Returns all subgraphs that are part of the federated graph. * Even if they have not been published yet. Optionally, you can set the `published` flag to true * to only return subgraphs that have been published with a version. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/SubgraphRepository.ts#L679-L734
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphRepository.getSDLFromLatestComposition
public async getSDLFromLatestComposition(data: { subgraphTargetId: string; federatedGraphTargetId: string }) { const fedRepo = new FederatedGraphRepository(this.logger, this.db, this.organizationId); const fedGraphSchemaVersion = await fedRepo.getLatestValidSchemaVersion({ targetId: data.federatedGraphTargetId ...
/** * Returns the latest valid schema version of a subgraph that was composed with a federated graph. * @param data */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/SubgraphRepository.ts#L1129-L1167
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
UserRepository.updateUser
public async updateUser(input: { id: string; active: boolean }) { await this.db .update(users) .set({ active: input.active, updatedAt: new Date() }) .where(eq(users.id, input.id)) .execute(); }
// only to update the active attribute
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/UserRepository.ts#L174-L180
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
AnalyticsRequestViewRepository.omitGroupedFilters
private omitGroupedFilters(name: AnalyticsViewGroupName, filters: AnalyticsFilter[]) { const baseFilters = this.getBaseFiltersForGroup(name); const allowedColumnNames = new Set(Object.entries(baseFilters).map(([_, f]) => f.columnName)); return filters.filter((f) => allowedColumnNames.has(f.field)); }
// in the generated sql queries
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/AnalyticsRequestViewRepository.ts#L670-L676
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
MetricsRepository.getRequestRateMetrics
public async getRequestRateMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, graphId, whereSql, queryParams, }: GetMetricsProps) { // to minutes const multiplier = rangeInHours * 60; // get request rate in last [range]h const queryRate = (start...
/** * Get request rate metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L53-L164
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryRate
const queryRate = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }>( ` SELECT round(sum(total) / ${multiplier}, 4) AS value FROM ( SELECT toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate, sum(TotalR...
// get request rate in last [range]h
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L67-L85
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
querySeries
const querySeries = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT toStartOfInterval(Times...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L115-L138
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
MetricsRepository.getLatencyMetrics
public async getLatencyMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, graphId, whereSql, queryParams, }: GetMetricsProps) { const queryLatency = (quantile: string, start: number, end: number) => { return this.client.queryPromise<{ value: number }>(...
/** * Get latency metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L169-L305
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryTop5
const queryTop5 = (quantile: string, start: number, end: number) => { return this.client.queryPromise<{ hash: string; name: string; value: string; isPersisted: boolean }>( ` WITH toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate SELECT Opera...
// get top 5 operations in last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L211-L241
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
querySeries
const querySeries = (quantile: string, start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT ...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L246-L279
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
MetricsRepository.getErrorMetrics
public async getErrorMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, graphId, whereSql, queryParams, }: GetMetricsProps) { // get request rate in last [range]h const queryPercentage = (start: number, end: number) => { return this.client.queryPro...
/** * Get error metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L310-L433
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryPercentage
const queryPercentage = (start: number, end: number) => { return this.client.queryPromise<{ errorPercentage: number }>( ` WITH toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate SELECT sum(totalErrors) AS errors, sum(totalRequests) AS requests,...
// get request rate in last [range]h
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L321-L345
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
getSeries
const getSeries = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT toStartOfInterval(Timesta...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L382-L407
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
MetricsRepository.getErrorRateMetrics
public async getErrorRateMetrics({ dateRange, granule, organizationId, graphId, whereSql, queryParams, }: GetMetricsProps) { // get requests in last [range] hours in series of [step] const series = await this.client.queryPromise<{ timestamp: string; requestRate: string; errorRate: stri...
/** * Get error rate metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L438-L482
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
MetricsRepository.mapSeries
protected mapSeries(diff: number, series: any[] = [], previousSeries?: any[]) { return series.map((s) => { const timestamp = new Date(s.timestamp + 'Z').getTime(); const prevTimestamp = toISO9075(new Date(timestamp - diff * 60 * 60 * 1000)); return { timestamp: String(timestamp), ...
/** * Merges series and previous series into one array, @todo could be handled in query directly. * @param diff * @param series * @param previousSeries * @returns */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/MetricsRepository.ts#L655-L668
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphMetricsRepository.getSubgraphRequestRateMetrics
public async getSubgraphRequestRateMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, subgraphId, whereSql, queryParams, }: GetSubgraphMetricsProps) { // to minutes const multiplier = rangeInHours * 60; // get request rate in last [range]h const...
/** * Get subgraph request rate metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L65-L176
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryRate
const queryRate = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }>( ` SELECT round(sum(total) / ${multiplier}, 4) AS value FROM ( SELECT toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate, sum(TotalR...
// get request rate in last [range]h
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L79-L97
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
querySeries
const querySeries = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT toStartOfInterval(Times...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L127-L150
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphMetricsRepository.getSubgraphLatencyMetrics
public async getSubgraphLatencyMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, subgraphId, whereSql, queryParams, }: GetSubgraphMetricsProps) { const queryLatency = (quantile: string, start: number, end: number) => { return this.client.queryPromise<...
/** * Get subgraph latency metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L181-L317
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryTop5
const queryTop5 = (quantile: string, start: number, end: number) => { return this.client.queryPromise<{ hash: string; name: string; value: string; isPersisted: boolean }>( ` WITH toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate SELECT Opera...
// get top 5 operations in last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L223-L253
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
querySeries
const querySeries = (quantile: string, start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT ...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L258-L291
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphMetricsRepository.getSubgraphErrorMetrics
public async getSubgraphErrorMetrics({ rangeInHours, granule, dateRange, prevDateRange, organizationId, subgraphId, whereSql, queryParams, }: GetSubgraphMetricsProps) { // get request rate in last [range]h const queryPercentage = (start: number, end: number) => { return t...
/** * Get error metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L322-L445
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
queryPercentage
const queryPercentage = (start: number, end: number) => { return this.client.queryPromise<{ errorPercentage: number }>( ` WITH toDateTime('${start}') AS startDate, toDateTime('${end}') AS endDate SELECT sum(totalErrors) AS errors, sum(totalRequests) AS requests,...
// get request rate in last [range]h
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L333-L357
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
getSeries
const getSeries = (start: number, end: number) => { return this.client.queryPromise<{ value: number | null }[]>( ` WITH toStartOfInterval(toDateTime('${start}'), INTERVAL ${granule} MINUTE) AS startDate, toDateTime('${end}') AS endDate SELECT toStartOfInterval(Timesta...
// get time series of last [range] hours
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L394-L419
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphMetricsRepository.getSubgraphErrorRateMetrics
public async getSubgraphErrorRateMetrics({ dateRange, granule, organizationId, subgraphId, whereSql, queryParams, }: GetSubgraphMetricsProps) { // get requests in last [range] hours in series of [step] const series = await this.client.queryPromise<{ timestamp: string; requestRate: stri...
/** * Get error rate metrics */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L450-L494
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
addFilterOption
const addFilterOption = (filter: string, value: string, filterLabel?: string) => { if (!filters[filter].options) { filters[filter].options = []; } let label = filterLabel || value; if (filter === 'clientVersion' && value === 'missing') { label = 'missing'; } else if (filte...
// filterLabelis the label for the values of the filters
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L647-L664
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SubgraphMetricsRepository.mapSeries
protected mapSeries(diff: number, series: any[] = [], previousSeries?: any[]) { return series.map((s) => { const timestamp = new Date(s.timestamp + 'Z').getTime(); const prevTimestamp = toISO9075(new Date(timestamp - diff * 60 * 60 * 1000)); return { timestamp: String(timestamp), ...
/** * Merges series and previous series into one array, @todo could be handled in query directly. * @param diff * @param series * @param previousSeries * @returns */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/SubgraphMetricsRepository.ts#L705-L718
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
getUnixTimeInSeconds
const getUnixTimeInSeconds = (timestamp: Date | number, offset?: number) => { let date: number; if (timestamp instanceof Date) { date = timestamp.getTime(); } else { date = timestamp; } if (offset) { date = date - offset * 60 * 60 * 1000; } return Math.round(date / 1000); };
/** * Get unix time in seconds * @param timestamp Date or unix timestamp in milliseconds * @param offset Offset in hours * @returns */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/repositories/analytics/util.ts#L374-L387
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
AccessTokenAuthenticator.authenticate
public async authenticate(accessToken: string, organizationSlug: string | null): Promise<AccessTokenAuthContext> { const userInfoData = await this.authUtils.getUserInfo(accessToken); const orgSlug = organizationSlug || userInfoData.groups[0].split('/')[1]; const organization = await this.orgRepo.bySlug(or...
/** * Authenticates the user with the given access token. Returns the user's organization ID and user's ID. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/AccessTokenAuthenticator.ts#L26-L62
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
ApiKeyAuthenticator.authenticate
public async authenticate(apiKey: string): Promise<ApiKeyAuthContext> { const apiKeyModel = await this.db.query.apiKeys.findFirst({ where: eq(schema.apiKeys.key, apiKey), with: { user: true, }, }); if (!apiKeyModel || !apiKeyModel.user) { throw new Error('Invalid api key'); ...
/** * Authenticates the user with the given api key. Returns the user's organization ID. * Due to authenticity of the JWT we can the user has access to the organization. * * @param apiKey */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/ApiKeyAuthenticator.ts#L30-L73
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
ApolloMigrator.fetchGraphDetails
public async fetchGraphDetails({ graphID }: { graphID: string }): Promise<{ success: boolean; fedGraphRoutingURL: string; subgraphs: MigrationSubgraph[]; errorMessage?: string; }> { const headers = new Headers(); headers.append('X-API-KEY', this.apiKey); headers.append('apollographql-clien...
// fetches the schemas of the subgraphs and the routing url of the federated graph
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/ApolloMigrator.ts#L99-L226
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
Authentication.authenticate
public async authenticate(headers: Headers): Promise<AuthContext> { try { /** * API keys are authenticated first. * First check for the token in the `Authorization` header */ const authorization = headers.get('authorization'); if (authorization) { const token = authori...
/** * Authenticate a user for an organization. * The function will first check for the token in the `Authorization` header and if that is not found, * it will check for the token in the `cosmo_user_session` cookie. In case of a cookie, the functions expects * the `cosmo-org-id` header to be set and will val...
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/Authentication.ts#L38-L107
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
Authorization.authorize
public async authorize({ headers, graph, db, authContext, }: { headers: Headers; graph: { targetId: string; targetType: 'subgraph' | 'federatedGraph'; }; db: PostgresJsDatabase<typeof schema>; authContext: AuthContext; }) { const { targetId, targetType } = graph; ...
/** * Authorize a user. * The function will check if the user has permissions to perform the action. * It must be called after the user is authenticated and always before a federated graph or subgraph action. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/Authorization.ts#L23-L118
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
BillingService.syncSubscriptionStatus
private async syncSubscriptionStatus(subscriptionId: string, organizationId: string) { const subscription = await this.stripe.subscriptions.retrieve(subscriptionId, { expand: ['default_payment_method', 'customer'], }); const values: NewBillingSubscription = { id: subscriptionId, organizat...
/** * Sync the subscription status with the database. It upserts a organizationBilling entry which represents the * customer in Stripe. It also upserts a billingSubscriptions entry which represents the subscription in Stripe. * */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/BillingService.ts#L237-L264
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
Keycloak.addKeycloakUser
public async addKeycloakUser({ email, realm, password, isPasswordTemp, groups, firstName, lastName, id, }: { email: string; realm?: string; password?: string; isPasswordTemp: boolean; groups?: string[]; firstName?: string; lastName?: string; id?: string;...
// creates a user in keycloak and returns the id
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/Keycloak.ts#L44-L82
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
Mailer.verifyConnection
public verifyConnection() { return this.client.verify(); }
/** * Verify the connection to the mail server is working. * (Authenticates with the mail server and returns true if successful, false otherwise) */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/Mailer.ts#L33-L35
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OidcProvider.createOidcProvider
public async createOidcProvider({ kcClient, kcRealm, organizationId, organizationSlug, alias, db, input, }: { kcClient: Keycloak; kcRealm: string; organizationId: string; organizationSlug: string; alias: string; db: PostgresJsDatabase<typeof schema>; input: Crea...
// creates the provider in keycloak, adds an entry into the db and then add the mappers in keycloak
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/OidcProvider.ts#L12-L52
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
OidcProvider.deleteOidcProvider
public async deleteOidcProvider({ kcClient, kcRealm, organizationSlug, orgCreatorUserId, alias, }: { kcClient: Keycloak; kcRealm: string; organizationSlug: string; orgCreatorUserId?: string; alias: string; }) { const keycloakUsers = await kcClient.getKeycloakSsoLoggedInUs...
// log them out and then delete the entry in the db
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/OidcProvider.ts#L164-L212
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SchemaUsageTrafficInspector.inspect
public async inspect( changes: InspectorSchemaChange[], filter: InspectorFilter, ): Promise<Map<string, InspectorOperationResult[]>> { const results: Map<string, InspectorOperationResult[]> = new Map(); for (const change of changes) { const where: string[] = []; // Used for arguments usag...
/** * Inspect the usage of a schema change in the last X days on real traffic and return the * affected operations. We will consider all available compositions. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/SchemaUsageTrafficInspector.ts#L40-L116
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
SchemaUsageTrafficInspector.schemaChangesToInspectorChanges
public schemaChangesToInspectorChanges( schemaChanges: SchemaDiff[], schemaCheckActions: SchemaCheckChangeAction[], ): InspectorSchemaChange[] { const operations = schemaChanges .map((change) => { // find the schema check action that matches the change const schemaCheckAction = schem...
/** * Convert schema changes to inspector changes. Will ignore a change if it is not inspectable. * Ultimately, will result in a breaking change because the change is not inspectable with the current implementation. */
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/SchemaUsageTrafficInspector.ts#L122-L141
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
WebSessionAuthenticator.authenticate
public async authenticate(headers: Headers): Promise<WebAuthAuthContext> { const cookieValue = headers.get('cookie'); if (cookieValue) { const cookies = cookie.parse(cookieValue); const token = cookies[userSessionCookieName]; if (token) { const decryptedJwt = await decrypt<UserSession...
/** * authenticate authenticates a user based on the presence of a JWT in a cookie. * This method also resolves the organization slug from the "cosmo-org-slug" header, * if the organization slug is not present in the header, an error is thrown. * You are still responsible for checking if the organization ex...
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/controlplane/src/core/services/WebSessionAuthenticator.ts#L27-L63
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
listener
const listener: typeof handler = (event) => savedHandler.current(event);
// Create event listener that calls handler function stored in ref
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/playground/src/lib/use-event-listener.ts#L71-L71
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
isRootTypeNode
const isRootTypeNode = (node: TypeField) => { return ROOT_TYPE_NAMES.has(node.typeName); };
// PUBSUB data sources cannot have root nodes other than
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/shared/src/router-config/builder.ts#L138-L140
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
listener
const listener: typeof handler = (event) => savedHandler.current(event);
// Create event listener that calls handler function stored in ref
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/studio/src/hooks/use-event-listener.ts#L71-L71
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
parseJSON
function parseJSON<T>(value: string | null): T | undefined { try { return value === "undefined" ? undefined : JSON.parse(value ?? ""); } catch { console.log("parsing error on", { value }); return undefined; } }
// A wrapper for "JSON.parse()"" to support "undefined" value
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/studio/src/hooks/use-session-storage.ts#L98-L105
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
handleResize
function handleResize() { // Set window width/height to state setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }
// Handler to call on window resize
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/studio/src/hooks/use-window-size.ts#L14-L20
40cfc416cc2869546b08978e922dabf4276964cc
cosmo
github_2023
wundergraph
typescript
castToType
function castToType(fieldType: any, fieldValue: any): any { if (isScalarType(fieldType)) { if (fieldType.name === "Int") { return parseInt(fieldValue); } else if (fieldType.name === "Float") { return parseFloat(fieldValue); } else if (fieldType.name === "Boolean") { return fieldValue ===...
// Helper function to cast field value to its respective type
https://github.com/wundergraph/cosmo/blob/40cfc416cc2869546b08978e922dabf4276964cc/studio/src/lib/schema-helpers.ts#L245-L259
40cfc416cc2869546b08978e922dabf4276964cc
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
BitonicSorter.constructor
constructor(context: GpuContext, nElements: number) { if (Math.log2(nElements) % 1 != 0) { throw new Error("nElements must be a power of 2"); } this.context = context; this.nElements = nElements; this.valuesBuffer = this.context.device.createBuffer({ size...
// The uniform buffers to use for each dispatch
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/bitonic.ts#L102-L149
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
getProjectionMatrix
function getProjectionMatrix(znear: number, zfar: number, fovX: number, fovY: number): Mat4 { const tanHalfFovY: number = Math.tan(fovY / 2); const tanHalfFovX: number = Math.tan(fovX / 2); const top: number = tanHalfFovY * znear; const bottom: number = -top; const right: number = tanHalfFovX * zne...
// for some reason this needs to be a bit different than the one in wgpu-matrix
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L16-L39
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
diagonal4x4
function diagonal4x4(x: number, y: number, z: number, w: number): Mat4 { const m = mat4.create(); m[0] = x; m[5] = y; m[10] = z; m[15] = w; return m; }
// useful for coordinate flips
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L42-L49
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Camera.dotZ
dotZ(): (v: Vec3) => number { const depthAxis = this.depthAxis(); return (v: Vec3) => { return vec3.dot(depthAxis, v); } }
// computes the depth of a point in camera space, for sorting
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L92-L97
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Camera.getPosition
getPosition(): Vec3 { const inverseViewMatrix = mat4.inverse(this.viewMatrix); return mat4.getTranslation(inverseViewMatrix); }
// gets the camera position in world space, for evaluating the spherical harmonics
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L100-L103
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Camera.translate
translate(x: number, y: number, z: number) { const viewInv = mat4.inverse(this.viewMatrix); mat4.translate(viewInv, [x, y, z], viewInv); mat4.inverse(viewInv, this.viewMatrix); }
// for camera interactions
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L112-L116
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Camera.rotate
rotate(x: number, y: number, z: number) { const viewInv = mat4.inverse(this.viewMatrix); mat4.rotateX(viewInv, y, viewInv); mat4.rotateY(viewInv, x, viewInv); mat4.rotateZ(viewInv, z, viewInv); mat4.inverse(viewInv, this.viewMatrix); }
// for camera interactions
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L119-L125
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Camera.depthAxis
private depthAxis(): Vec3 { return mat4.getAxis(mat4.transpose(this.viewMatrix), 2); }
// the depth axis is the third column of the transposed view matrix
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L128-L130
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
cameraFromJSON
function cameraFromJSON(rawCamera: CameraRaw, canvasW: number, canvasH: number): Camera { const fovX = focal2fov(rawCamera.fx, rawCamera.width); const fovY = focal2fov(rawCamera.fy, rawCamera.height); const projectionMatrix = getProjectionMatrix(0.2, 100, fovX, fovY); const R = mat3.create(...rawCamera...
// converting camera coordinate systems is always black magic :(
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/camera.ts#L262-L281
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
computeDepthShader
function computeDepthShader(itemsPerThread: number, numQuadsUnpadded: number): string { return ` @group(0) @binding(0) var<storage, read> vertices: array<vec3<f32>>; @group(0) @binding(1) var<storage, read_write> depths: array<f32>; @group(0) @binding(2) var<uniform> projMatrix: mat4x4<f32>; @compute @workgroup_si...
// the depth of each vertex is computed, the excess space is padded with +inf
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/depth_sorter.ts#L20-L40
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
copyToIndexBufferShader
function copyToIndexBufferShader(itemsPerThread: number, numQuadsUnpadded: number): string { return ` struct IndexVertex { vec1: u32, vec2: u32, vec3: u32, vec4: u32, vec5: u32, vec6: u32, }; @group(0) @binding(0) var<storage, read> indices: array<u32>; @group(0) @binding(1) var<storage, re...
// each quad index is repeated 6 times, once for each vertex
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/depth_sorter.ts#L43-L77
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
handlePlyChange
function handlePlyChange(event: any) { const file = event.target.files[0]; async function onFileLoad(arrayBuffer: ArrayBuffer) { if (currentRenderer) { await currentRenderer.destroy(); } const gaussians = new PackedGaussians(arrayBuffer); try { const cont...
// swap the renderer when the ply file changes
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/index.ts#L22-L46
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
loadDefaultPly
async function loadDefaultPly() { const url = "pc_short.ply"; loadingPopup.style.display = 'block'; // show loading popup const content = await fetch(url); const arrayBuffer = await content.arrayBuffer(); const gaussians = new PackedGaussians(arrayBuffer); const context = await Renderer.requestC...
// loads the default ply file (bundled with the source) at startup, useful for dev
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/index.ts#L49-L59
905b3c0fb8961e42c79ef97e64609e82383ca1c2
gaussian-splatting-web
github_2023
cvlab-epfl
typescript
Renderer.destroy
public async destroy(): Promise<void> { return new Promise((resolve, reject) => { this.destroyCallback = resolve; }); }
// destroy the renderer and return a promise that resolves when it's done (after the next frame)
https://github.com/cvlab-epfl/gaussian-splatting-web/blob/905b3c0fb8961e42c79ef97e64609e82383ca1c2/src/renderer.ts#L90-L94
905b3c0fb8961e42c79ef97e64609e82383ca1c2
generative-ai-on-aws
github_2023
generative-ai-on-aws
typescript
loadTTFAsArrayBuffer
function loadTTFAsArrayBuffer(): PluginOption { return { name: "load-ttf-as-array-buffer", async transform(_src, id) { if (id.endsWith(".ttf")) { return `export default new Uint8Array([ ${new Uint8Array(await promises.readFile(id))} ]).buffer`; } }, }; }
// used to load fonts server side for thumbnail generation
https://github.com/generative-ai-on-aws/generative-ai-on-aws/blob/abdd3c9729584196b021be75947f50fcd2f8fca5/99_chatbot/vite.config.ts#L7-L18
abdd3c9729584196b021be75947f50fcd2f8fca5
generative-ai-on-aws
github_2023
generative-ai-on-aws
typescript
innerProduct
function innerProduct(embeddingA: Embedding, embeddingB: Embedding) { return 1.0 - dot(embeddingA, embeddingB); }
// see here: https://github.com/nmslib/hnswlib/blob/359b2ba87358224963986f709e593d799064ace6/README.md?plain=1#L34
https://github.com/generative-ai-on-aws/generative-ai-on-aws/blob/abdd3c9729584196b021be75947f50fcd2f8fca5/99_chatbot/src/lib/server/sentenceSimilarity.ts#L6-L8
abdd3c9729584196b021be75947f50fcd2f8fca5
Weibo-archiver
github_2023
Chilfish
typescript
compressFolder
async function compressFolder(folderPath: string, outputPath: string) { const zip = new JSZip() const addFileToZip = async (filePath: string, relativePath: string) => { const data = fs.readFileSync(filePath) zip.file(relativePath, data) } const addFolderToZip = async (folderPath: string, relativePath:...
// 打包文件夹
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/release.ts#L7-L31
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
waitIDB
async function waitIDB() { const dbName = `uid-${config.value.uid}` while (idb.value.name !== dbName) await new Promise(r => setTimeout(r, 300)) }
/** * 等待 IDB 初始化完成 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/apps/monkey/src/stores/postStore.ts#L37-L42
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
reset
async function reset() { total.value = 0 pageSize.value = 20 configStore.setConfig({ curPage: 0, fetchedCount: 0, }) await setDB() await idb.value.clearDB() }
/** * 重置 fetch 状态 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/apps/monkey/src/stores/postStore.ts#L47-L57
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
add
async function add(newPost: Post) { await waitIDB() await idb.value.addDBPost(newPost) config.value.fetchedCount += 1 config.value.curPage = Math.ceil(config.value.fetchedCount / 20) }
/** * 添加帖子 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/apps/monkey/src/stores/postStore.ts#L62-L68
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
exportDatas
async function exportDatas() { const posts = await getAll() console.log('导出的数量:', posts.length) const followings = config.value.weiboOnly ? [] : await idb.value.getFollowings() const res = await exportData(posts, userInfo.value, followings) if (!res) return const scripts = 'h...
/** * 导出数据 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/apps/monkey/src/stores/postStore.ts#L104-L117
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
waitIDB
async function waitIDB() { const dbName = `uid-${publicStore.curUid}` while (idb.value.name !== dbName) await new Promise(r => setTimeout(r, 300)) }
/** * 等待 IDB 初始化完成 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/stores/post.ts#L67-L72
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
set
async function set( data: Post[], user: UserInfo, _followings?: UserBio[], isReplace = false, ) { await waitIDB() if (_followings && _followings.length) { await idb.value.clearFollowings() followings.value = _followings await idb.value.addFollowings(_followings) } c...
/** * 设置帖子数据,可选择是否替换或是追加合并 * @param data * @param user * @param _followings * @param isReplace */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/stores/post.ts#L81-L101
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
getAllImgs
async function getAllImgs() { if (allImages.length > 0) return allImages await waitIDB() const imgs = await idb.value.getImgs() // console.log('Get imgs', imgs) const result: Album[] = [] for (const { img, date, id } of imgs) { const year = date.getFullYear() const month = ...
/** * 获取所有图片,以月份分组 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/stores/post.ts#L228-L250
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
migrateUser
async function migrateUser() { if (DB_VERSION >= 4) return const dbName = `uid-${curUid.value || 0}` as UID const idb = new IDB(dbName) const userInDB = await idb.getUserInfo() if (userInDB) { importUser(userInDB) return await idb.close() } const posts = await idb.getAl...
/** * 从旧版中迁移 user 数据到 idb 中 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/stores/public.ts#L63-L101
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getDBPosts
async getDBPosts( page = 1, limit = 10, ) { const db = await this.idb const posts: Post[] = [] const ts = db.transaction(POST_STORE) let cursor = await ts.store.index('time').openCursor(this.lastRange, 'prev') if (!cursor) return posts try { const target = (page - 1) * ...
/** * 分页地获取帖子 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L95-L125
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getDBPostByTime
async getDBPostByTime(times: number[]) { const db = await this.idb const posts: Post[] = [] const ts = db.transaction(POST_STORE) const index = ts.store.index('time') for (const time of times) { const post = await index.get(time) if (post) posts.push(post) } return post...
/** * 从时间戳数组中获取帖子 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L130-L143
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getAllDBPosts
async getAllDBPosts() { if (this.posts.length) return this.posts const db = await this.idb const posts = await db.getAll(POST_STORE) this.posts = posts return posts }
/** * 获取所有帖子 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L148-L156
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getPostCount
async getPostCount() { const db = await this.idb return await db.count(POST_STORE) }
/** * 获取帖子总数 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L166-L169
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.addDBPosts
async addDBPosts( posts: Post[], isReplace = true, buildSearch = true, ) { const db = await this.idb if (isReplace) await db.clear(POST_STORE) const ts = db.transaction(POST_STORE, 'readwrite') const store = ts.store posts.forEach((post) => { post.created_at = dayjs(post...
/** * 批量覆盖添加或合并添加 * @param posts * @param isReplace 默认为 true 覆盖添加 * @param buildSearch 默认为 true 构建搜索 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L177-L212
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.clearDB
async clearDB() { const db = await this.idb await Promise.all([ db.clear(POST_STORE), db.clear(USER_STORE), db.clear(FLOWERINGS_STORE), ]) }
/** * 清空数据库 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L226-L234
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getSize
async getSize() { const estimate = await navigator.storage.estimate() const used = estimate.usage || 0 return (used / 1024 / 1024).toFixed(2) }
/** * 获取 IndexedDB 存储空间大小 * @returns 返回已使用的 IndexedDB 存储空间大小,单位 MB */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L245-L250
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.buildSearch
buildSearch( posts: Post[], ) { const docs = posts.map((post) => { return { time: post.created_at as number, text: `${post.text} ${post.retweeted_status?.text}` .replace(/<[^>]+>/g, ' ') // 移除所有 HTML 标签 .replace(/(undefined|查看图片|查看链接|转发微博)/, '') .replace(/&[...
/** * 构建 fuse 搜索实例 * @param posts * @returns 搜索函数 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L257-L303
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.filterByTime
async filterByTime( start: number, end: number, page: number, limit: number, ) { const db = await this.idb const posts: Post[] = [] const ts = db.transaction(POST_STORE) // 闭区间 const range = IDBKeyRange.bound(start, end) const index = ts.store.index('time') let cursor = a...
/** * 根据时间戳范围筛选帖子 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L308-L349
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.getUserInfo
async getUserInfo() { const db = await this.idb return await db.getAll(USER_STORE).then(users => users[0]) }
/** * 获取用户信息 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L354-L357
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
IDB.setUserInfo
async setUserInfo(user: UserInfo) { const db = await this.idb await db.put(USER_STORE, user) }
/** * 设置用户信息 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/core/src/utils/storage.ts#L362-L365
683c8ae0e4eb2195066382da52494422121bf590
Weibo-archiver
github_2023
Chilfish
typescript
parseCard
function parseCard(url_struct?: any[], card?: any): CardInfo | undefined { if (!url_struct || !card) return undefined const link = url_struct.find((e: any) => e.page_id === card.page_id)?.long_url const title = card.page_title === '' ? card.content1 : card.page_title let desc = card.content2 === '' ? card....
/** * 解析转发的卡片 */
https://github.com/Chilfish/Weibo-archiver/blob/683c8ae0e4eb2195066382da52494422121bf590/packages/shared/src/parse.ts#L75-L95
683c8ae0e4eb2195066382da52494422121bf590
actions-timeline
github_2023
Kesin11
typescript
main
const main = async () => {};
// It's a dummy file to do nothing at action main phase.
https://github.com/Kesin11/actions-timeline/blob/72725fdc576eac383c203aaf28f3ca76cabf1489/src/main.ts#L2-L2
72725fdc576eac383c203aaf28f3ca76cabf1489
actions-timeline
github_2023
Kesin11
typescript
filterSteps
const filterSteps = (steps: workflowJobSteps): workflowJobSteps => { return steps.filter((step) => step.status === "completed"); };
// Skip steps that is not status:completed (ex. status:queued, status:in_progress)
https://github.com/Kesin11/actions-timeline/blob/72725fdc576eac383c203aaf28f3ca76cabf1489/src/workflow_gantt.ts#L24-L26
72725fdc576eac383c203aaf28f3ca76cabf1489
actions-timeline
github_2023
Kesin11
typescript
filterJobs
const filterJobs = (jobs: WorkflowJobs): WorkflowJobs => { return jobs.filter((job) => job.conclusion !== "skipped"); };
// Skip jobs that is conclusion:skipped
https://github.com/Kesin11/actions-timeline/blob/72725fdc576eac383c203aaf28f3ca76cabf1489/src/workflow_gantt.ts#L29-L31
72725fdc576eac383c203aaf28f3ca76cabf1489
openbio
github_2023
vanxh
typescript
QrCode.encodeText
public static encodeText(text: string, ecl: QrCode.Ecc): QrCode { const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text); return QrCode.encodeSegments(segs, ecl); }
// ecl argument if it can be done without increasing the version.
https://github.com/vanxh/openbio/blob/242e7224198e706b35017f2f9852b2a1bbe69b7f/src/lib/qr/generator.tsx#L43-L46
242e7224198e706b35017f2f9852b2a1bbe69b7f
openbio
github_2023
vanxh
typescript
QrCode.encodeBinary
public static encodeBinary( data: Readonly<Array<byte>>, ecl: QrCode.Ecc, ): QrCode { const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data); return QrCode.encodeSegments([seg], ecl); }
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
https://github.com/vanxh/openbio/blob/242e7224198e706b35017f2f9852b2a1bbe69b7f/src/lib/qr/generator.tsx#L52-L58
242e7224198e706b35017f2f9852b2a1bbe69b7f
openbio
github_2023
vanxh
typescript
QrCode.encodeSegments
public static encodeSegments( segs: Readonly<Array<QrSegment>>, ecl: QrCode.Ecc, minVersion: int = 1, maxVersion: int = 40, mask: int = -1, boostEcl = true, ): QrCode { if ( !( QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && ...
// This is a mid-level API; the high-level API is encodeText() and encodeBinary().
https://github.com/vanxh/openbio/blob/242e7224198e706b35017f2f9852b2a1bbe69b7f/src/lib/qr/generator.tsx#L71-L154
242e7224198e706b35017f2f9852b2a1bbe69b7f