repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
scalar | github_2023 | scalar | typescript | isValidTokenUrl | function isValidTokenUrl(url: string): boolean {
return url.trim().length > 0
} | // Validate token URL | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/mock-server/src/utils/getOpenAuthTokenUrls.ts#L33-L35 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | addTokenUrl | const addTokenUrl = (url?: string) => {
if (url && isValidTokenUrl(url)) {
tokenUrls.add(getPathFromUrl(url))
}
} | // Helper to safely add valid token URLs | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/mock-server/src/utils/getOpenAuthTokenUrls.ts#L57-L61 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | checkForMethod | const checkForMethod = (identifier: Identifier) => {
const method = identifier?.escapedText?.toLowerCase()
return method?.match(/^(get|post|put|patch|delete|head|options)$/)
? (method as OpenAPIV3_1.HttpMethods)
: null
} | /** Check if identifier is a supported http method */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/nextjs-openapi/src/path.ts#L22-L28 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | extractPathParams | const extractPathParams = (
node: ParameterDeclaration,
program: Program,
): OpenAPIV3_1.ParameterObject[] => {
// Traverse to the params with type guards
if (
node &&
isParameter(node) &&
node.type &&
isTypeLiteralNode(node.type) &&
node.type.members[0] &&
isPropertySignature(node.type.... | /**
* Takes a parameter node and returns a path parameter schema
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/nextjs-openapi/src/path.ts#L43-L71 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseSemver | const parseSemver = (
version: string,
): { major: number; minor: number; patch: number } => {
const [major, minor = 0, patch = 0] = version
.split('.')
.map((part) => parseInt(part, 10))
return { major, minor, patch }
} | // Parse the strings into numbers | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/semver.ts#L6-L13 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | flattenChildren | const flattenChildren = (childUids: string[]) =>
childUids.reduce(
(prev, uid) => {
const request = oldData.requests[uid]
// Request
if (request) {
prev.requestUids.add(uid)
// Security
request.securitySchemeUids?.forEach((s) => prev.authUids.add(s))
... | /** To grab requests and tags we must traverse children, also for security */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/v-2.1.0/migration.ts#L19-L49 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | migrateAuth | const migrateAuth = (
scheme: v_0_0_0.SecurityScheme,
): NonNullable<v_2_1_0.Collection['auth']>[string] => {
if (scheme.type === 'apiKey')
// ApiKey
return { type: 'apiKey', name: scheme.name, value: scheme.value ?? '' }
// HTTP
if (scheme.type === 'http')
return {
type: 'h... | /** Migrate values from old securitySchemes to the new auth */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/v-2.1.0/migration.ts#L52-L107 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | migrateFlow | const migrateFlow = (flow: Flow): Oauth2['flow'] => {
const base = {
refreshUrl: flow.refreshUrl || '',
selectedScopes: flow.selectedScopes || [],
scopes: flow.scopes || {},
} as const
if (flow.type === 'implicit')
return {
...flow,
...base,
'type': 'implicit... | /** Specifically handle each oauth2 flow */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/v-2.1.0/migration.ts#L225-L262 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | getNameKey | const getNameKey = (scheme: v_0_0_0.SecurityScheme) => {
switch (scheme?.type) {
case 'apiKey':
return `${capitalize(scheme.in)}`
case 'http': {
return `${capitalize(scheme.scheme)} Authentication`
}
case 'oauth2':
return camelToTitleWords(scheme.flow.type)
case... | /** Generate a nameKey based on the type of oauth */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/v-2.1.0/migration.ts#L265-L279 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | migrateSecurityScheme | const migrateSecurityScheme = (
scheme: v_2_1_0.SecurityScheme,
auth: v_2_1_0.Collection['auth'][string],
): v_2_2_0.SecurityScheme | null => {
// API Key
if (scheme.type === 'apiKey' && auth.type === 'apiKey') {
return {
...scheme,
value: auth.value,
}
}
// HTTP
if (scheme.type === '... | /** Migrate security scheme from v-2.1.0 to v-2.2.0 */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/migrations/v-2.2.0/migration.ts#L6-L105 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | guessFromFormat | function guessFromFormat(schema: Record<string, any>, fallback: string = '') {
return genericExampleValues[schema.format] ?? fallback
} | /**
* We can use the `format` to generate some random values.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/spec-getters/getExampleFromSchema.ts#L39-L41 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | cache | function cache(schema: Record<string, any>, result: unknown) {
// Avoid unnecessary WeakMap operations for primitive values
if (typeof result !== 'object' || result === null) {
return result
}
resultCache.set(schema, result)
return result
} | /** Store result in the cache, and return the result */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/spec-getters/getExampleFromSchema.ts#L47-L56 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | getParamsFromObject | function getParamsFromObject(
obj: AnyObject,
prefix = '',
): {
name: string
value: any
}[] {
return Object.entries(obj).flatMap(([key, value]) => {
const newKey = prefix ? `${prefix}[${key}]` : key
if (typeof value === 'object' && value !== null) {
return getParamsFromObject(value, newKey)
... | /**
* Transform the object into a nested array of objects
* that represent the key-value pairs of the object.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/spec-getters/getRequestBodyFromOperation.ts#L15-L31 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | arrayToUidMap | function arrayToUidMap<T extends { uid: string }>(array: T[]) {
return array.reduce<Record<string, T>>((map, item) => {
map[item.uid] = item
return map
}, {})
} | /** Convert an array of objects into a map of objects by UID */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/transforms/export-spec.test.ts#L11-L16 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | checkName | function checkName(name: string) {
if (exampleNames.has(name)) {
const base = name.split(' ')
const end = Number.parseInt(base.at(-1) ?? 'NaN', 10)
if (Number.isNaN(end)) {
base.push('1')
} else {
base[base.length - 1] = `${end + 1}`
}
return che... | /** Increment non-unique names */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/transforms/export-spec.ts#L67-L81 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | findSchemeUidByKey | const findSchemeUidByKey = (key: string, securitySchemes: SecurityScheme[]) =>
securitySchemes.find((s) => s.nameKey === key)?.uid | // Little helper | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/transforms/import-spec.test.ts#L123-L124 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | getFallbackUrl | function getFallbackUrl() {
if (typeof window === 'undefined') {
return undefined
}
if (typeof window?.location?.origin !== 'string') {
return undefined
}
return window.location.origin
} | /**
* Fallback to the current window.location.origin, if available
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/oas-utils/src/transforms/import-spec.ts#L569-L579 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | add | const add = (item: T) => {
entityMap[item.uid] = item
mutationMap[item.uid] = new Mutation(item, maxNumberRecords)
onChange()
} | /** Adds a new item to the record of tracked items and creates a new mutation tracking instance */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/handlers.ts#L40-L44 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation._unsavedMutate | _unsavedMutate<K extends MutationPath<DataType>>(
path: K,
value: PathValue<DataType, K>,
) {
setNestedValue(this.parentData, path, value)
this.runSideEffects(path)
} | /** Mutate without saving a record. Private function. */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L68-L74 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation.addSideEffect | addSideEffect(
triggers: string[],
effect: MutationEffect<DataType>,
name: string,
immediate = true,
) {
this.sideEffects.push({ triggers, effect, name })
if (immediate) {
effect(this.parentData)
if (this.debug) {
console.info(`Running mutation side effect: ${name}`, 'debug... | /** Side effects must take ONLY an object of the specified type and act on it */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L77-L90 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation.runSideEffects | runSideEffects(path: MutationPath<DataType>) {
this.sideEffects.forEach(({ effect, triggers, name }) => {
const triggerEffect =
triggers.some((trigger) => path.includes(trigger)) || path.length < 1
if (triggerEffect) {
effect(this.parentData)
if (this.debug) {
console.i... | /** Runs all side effects that match the path trigger */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L93-L104 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation.mutate | mutate<K extends MutationPath<DataType>>(
/** Path to nested set */
path: K,
/** New value to set */
value: PathValue<DataType, K>,
/** Optional explicit previous value. Otherwise the current value will be used */
previousValue: PathValue<DataType, K> | null = null,
) {
// If already rolle... | /** Mutate an object with the new property value and run side effects */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L107-L141 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation.undo | undo() {
if (this.idx < 0 || this.records.length < 1) return false
if (this.debug) console.info('Undoing Mutation', 'debug')
const record = this.records[this.idx]
this.idx -= 1
if (record) this._unsavedMutate(record.path, record.prev)
return true
} | /** Undo the previous mutation */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L144-L154 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Mutation.redo | redo() {
if (this.idx > this.records.length - 2) return false
if (this.debug) console.info('Redoing Mutation', 'debug')
const record = this.records[this.idx + 1]
this.idx += 1
if (record) this._unsavedMutate(record.path, record.value)
return true
} | /** Roll forward to the next available mutation if its exists */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/object-utils/src/mutator-record/mutations.ts#L157-L167 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Validator.validate | async validate(
filesystem: Filesystem,
options?: ThrowOnErrorOption,
): Promise<ValidateResult> {
const entrypoint = filesystem.find((file) => file.isEntrypoint)
const specification = entrypoint?.specification
// TODO: How does this work with a filesystem?
this.specification = specification
... | /**
* Checks whether a specification is valid and all references can be resolved.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/lib/Validator/Validator.ts#L53-L142 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | Validator.getAjvValidator | async getAjvValidator(version: OpenApiVersion) {
// Schema loaded already
if (this.ajvValidators[version]) {
return this.ajvValidators[version]
}
// Load OpenAPI Schema
const schema = OpenApiSpecifications[version]
// Load JSON Schema
const AjvClass = jsonSchemaVersions[schema.$schem... | /**
* Ajv JSON schema validator
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/lib/Validator/Validator.ts#L147-L177 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | normalizeArray | function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
let up = 0
for (let i = parts.length - 1; i >= 0; i--) {
const last = parts[i]
if (last === '.') {
parts.splice(i, 1)
} else if (last === '..') {
parts.splice(i, 1)
up++
}... | // @ts-nocheck | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/polyfills/path.ts#L28-L52 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | dereference | function dereference(
schema: AnyObject,
filesystem: Filesystem,
entrypoint: FilesystemEntry,
// references to resolved object
resolvedSchemas: WeakSet<object>,
// error output
errors: ErrorObject[],
options?: ResolveReferencesOptions,
): void {
if (schema === null || resolvedSchemas.has(schema)) ret... | /**
* Resolves the circular reference to an object and deletes the $ref properties (in-place).
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/utils/resolveReferences.ts#L94-L163 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | resolveUri | function resolveUri(
// 'foobar.json#/foo/bar'
uri: string,
options: ResolveReferencesOptions,
// { filename: './foobar.json '}
file: FilesystemEntry,
// [ { filename: './foobar.json '} ]
filesystem: Filesystem,
// a function to resolve references in external file
resolve: (file: FilesystemEntry) => ... | /**
* Resolves a URI to a part of the specification
*
* The output is not necessarily dereferenced
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/utils/resolveReferences.ts#L170-L261 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | eq | const eq = (x) => (y) => x === y | // Basic | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/utils/betterAjvErrors/utils.ts#L2-L2 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | isXError | const isXError = (x) => (error) => error.keyword === x | // Error | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/openapi-parser/src/utils/betterAjvErrors/utils.ts#L10-L10 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createContainer | const createContainer = () => {
let _container: Element | null = null
if (specScriptTag) {
_container = document.createElement('div')
specScriptTag?.parentNode?.insertBefore(_container, specScriptTag)
} else {
_container = specElement || specUrlElement || document.body
}
return _co... | // If it’s a script tag, we can’t mount the Vue.js app inside that tag. | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/play-button/src/index.ts#L58-L67 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createAppFactory | const createAppFactory = async () => {
const specUrl = getSpecUrl()
const parsedSpec: Spec = reactive(await parse(specUrl))
if (!container) {
console.error('Could not find a mount point for API References')
return null
}
const { open } = await createApiClientModal({
el: containe... | // Wrap create app in factory for re-loading | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/play-button/src/index.ts#L72-L136 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | extractTags | function extractTags(
items: PostmanCollection['item'],
): OpenAPIV3_1.TagObject[] {
const tags: OpenAPIV3_1.TagObject[] = []
function processTagItem(item: any, parentPath: string = '') {
if (item.item) {
const currentPath = parentPath
? `${parentPath} > ${item.name}`
: item.name
... | /**
* Extracts tags from Postman collection folders
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/convert.ts#L15-L39 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createApiKeyConfig | function createApiKeyConfig(): SecurityConfig {
return {
scheme: {
type: 'apiKey',
name: 'api_key',
in: 'header',
},
requirement: { [AUTH_SCHEMES.API_KEY]: [] },
}
} | /**
* Creates security configuration for API key authentication
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/authHelpers.ts#L26-L35 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createBasicConfig | function createBasicConfig(): SecurityConfig {
return {
scheme: {
type: 'http',
scheme: 'basic',
},
requirement: { [AUTH_SCHEMES.BASIC]: [] },
}
} | /**
* Creates security configuration for Basic authentication
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/authHelpers.ts#L40-L48 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createBearerConfig | function createBearerConfig(): SecurityConfig {
return {
scheme: {
type: 'http',
scheme: 'bearer',
},
requirement: { [AUTH_SCHEMES.BEARER]: [] },
}
} | /**
* Creates security configuration for Bearer token authentication
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/authHelpers.ts#L53-L61 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createOAuth2Config | function createOAuth2Config(): SecurityConfig {
return {
scheme: {
type: 'oauth2',
flows: {
authorizationCode: {
authorizationUrl: OAUTH2_DEFAULTS.AUTHORIZE_URL,
tokenUrl: OAUTH2_DEFAULTS.TOKEN_URL,
scopes: {},
},
},
},
requirement: { [AUTH_S... | /**
* Creates security configuration for OAuth2 authentication
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/authHelpers.ts#L66-L80 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createNoAuthConfig | function createNoAuthConfig(): SecurityConfig {
return {
scheme: {},
requirement: {},
}
} | /**
* Creates security configuration for no authentication
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/authHelpers.ts#L85-L90 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | findVariable | function findVariable(
collection: PostmanCollection,
key: string,
): Variable | undefined {
return collection.variable?.find((v) => v.key === key)
} | /**
* Finds a specific variable in the collection by its key
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/externalDocsHelper.ts#L14-L19 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseParametersFromDescription | function parseParametersFromDescription(description: string): {
descriptionWithoutTable: string
parametersFromTable: OpenAPIV3_1.ParameterObject[]
} {
const lines = description.split('\n')
let inTable = false
const tableLines: string[] = []
const descriptionLines: string[] = []
for (let i = 0; i < lines.... | // Helper function to parse parameters from the description if it is markdown | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/itemHelpers.ts#L187-L251 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | extractOperationInfo | function extractOperationInfo(name: string | undefined) {
if (!name) return { operationId: undefined, summary: undefined }
// First check if the string ends with something in brackets
const match = name.match(/\[([^[\]]{0,1000})\]$/)
if (!match) return { operationId: undefined, summary: name }
// Get the op... | // Instead of using regex with \s*, let's split this into two steps | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/itemHelpers.ts#L254-L269 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | findVariable | function findVariable(
collection: PostmanCollection,
key: string,
): Variable | undefined {
return collection.variable?.find((v) => v.key === key)
} | /**
* Finds a specific variable in the collection by its key
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/licenseContactHelper.ts#L26-L31 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | processLicense | function processLicense(
collection: PostmanCollection,
): OpenAPIV3_1.LicenseObject | undefined {
const nameVar = findVariable(collection, VARIABLE_KEYS.LICENSE.NAME)
if (!nameVar?.value || typeof nameVar.value !== 'string') return undefined
const urlVar = findVariable(collection, VARIABLE_KEYS.LICENSE.URL)
... | /**
* Processes license information from collection variables
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/licenseContactHelper.ts#L36-L48 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | processContact | function processContact(
collection: PostmanCollection,
): OpenAPIV3_1.ContactObject | undefined {
const nameVar = findVariable(collection, VARIABLE_KEYS.CONTACT.NAME)
const urlVar = findVariable(collection, VARIABLE_KEYS.CONTACT.URL)
const emailVar = findVariable(collection, VARIABLE_KEYS.CONTACT.EMAIL)
if ... | /**
* Processes contact information from collection variables
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/licenseContactHelper.ts#L53-L70 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | extractPathVariablesFromPathArray | function extractPathVariablesFromPathArray(
pathArray: (string | { type: string; value: string })[],
): string[] {
const variables: string[] = []
const variableRegex = /{{\s*([\w.-]+)\s*}}/
pathArray.forEach((segment) => {
const segmentString = typeof segment === 'string' ? segment : segment.value
cons... | /**
* Helper function to extract variables from the url.path array.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/parameterHelpers.ts#L77-L92 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | processItems | function processItems(items: (Item | ItemGroup)[], domains: Set<string>) {
items.forEach((item) => {
if ('item' in item && Array.isArray(item.item)) {
processItems(item.item, domains)
} else if ('request' in item) {
const request = item.request
if (typeof request !== 'string') {
cons... | /**
* Recursively processes collection items to extract server URLs
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/serverHelpers.ts#L8-L36 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseStatusCodeFromLine | function parseStatusCodeFromLine(line: string): number | null {
const patterns = [
/pm\.response\.to\.have\.status\((\d{3})\)/,
/pm\.expect\(pm\.response\.code\)\.to\.(?:eql|equal)\((\d{3})\)/,
/pm\.expect\(pm\.response\.status\)\.to\.(?:eql|equal)\(['"](\d{3})['"]\)/,
]
for (const pattern of pattern... | /**
* Parses a line of script to extract a status code.
* Supports patterns like:
* - pm.response.to.have.status(201)
* - pm.expect(pm.response.code).to.eql(202)
* - pm.expect(pm.response.status).to.equal(201)
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/statusCodeHelpers.ts#L40-L55 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseUrl | function parseUrl(urlString: string): ParsedUrl {
const url = new URL(urlString)
return {
protocol: url.protocol,
hostname: url.hostname,
port: url.port,
}
} | /**
* Parses a URL string into its component parts.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/postman-to-openapi/src/helpers/urlHelpers.ts#L8-L15 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | upsertKeyValue | function upsertKeyValue(
obj: Record<string, string> | Record<string, string[]> | undefined,
keyToChange: string,
value: string[],
) {
const keyToChangeLower = keyToChange.toLowerCase()
if (!obj) {
return
}
// Add to modified headers
if (Array.isArray(obj[MODIFIED_HEADERS_KEY])) {
obj[MODIFIED... | // In this file you can include the rest of your app’s specific main process | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/index.ts#L387-L420 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | handleFileOpen | async function handleFileOpen() {
console.info('[handleFileOpen] Open file dialog …')
const { canceled, filePaths } = await dialog.showOpenDialog({
filters: [
{ name: 'OpenAPI Documents', extensions: ['*.yml', '*.yaml', '*.json'] },
],
})
if (!canceled) {
return filePaths[0]
}
return un... | /**
* Open the native file dialog
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/index.ts#L425-L439 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | handleReadFile | async function handleReadFile(
_: IpcMainInvokeEvent | undefined,
filePath: string,
) {
if (filePath) {
console.info('[handleReadFile] Reading', filePath, '…')
return fs.promises.readFile(filePath, 'utf-8')
}
return undefined
} | /**
* Read the file content
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/index.ts#L444-L455 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | handleFileOpenMenuItem | async function handleFileOpenMenuItem(mainWindow: BrowserWindow) {
const filePath = await handleFileOpen()
if (!filePath) {
return
}
const content = await handleReadFile(undefined, filePath)
if (!content) {
return
}
mainWindow.webContents.send('importFile', content)
} | /**
* Handle the "Open…" menu item
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/index.ts#L460-L474 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | openAppLink | async function openAppLink(appLink?: string) {
// Check whether an app link is given
if (typeof appLink !== 'string') {
return
}
// Strip `scalar://`, decode URI
const url = decodeURIComponent(appLink.replace('scalar://', ''))
// Check whether it’s an URL
if (!url.length) {
return
}
// Find... | /**
* Takes a `scalar://` app link, fetches the content and passes it to the renderer process
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/index.ts#L479-L529 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseHtml | function parseHtml(html?: string) {
// Check whether it could be HTML
if (!html?.includes('<')) {
return undefined
}
// data-url="*"
const dataUrlMatch = html.match(/data-url=["']([^"']+)["']/)
if (dataUrlMatch?.[1]) {
return dataUrlMatch[1]
}
// spec-url="*"
const specUrlMatch = html.match... | /**
* Go through the HTML and try to find the OpenAPI document URL
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/resolve.ts#L71-L108 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | makeRelativeUrlsAbsolute | function makeRelativeUrlsAbsolute(baseUrl: string, path: string) {
// Check whether the path is already absolute
if (path.startsWith('http://') || path.startsWith('https://')) {
return path
}
// Combine the URL and the relative path
try {
const { href } = new URL(path, baseUrl)
return href
} c... | /**
* URLs can be relative, but we need absolute URLs eventually.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/resolve.ts#L113-L130 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | parseEmbeddedOpenApi | function parseEmbeddedOpenApi(html: string): object | undefined {
const match = html.match(
/<script[^>]*data-configuration=['"]([^'"]+)['"][^>]*>(.*?)<\/script>/,
)
if (!match) return undefined
try {
const configString = decodeHtmlEntities(match[1])
const config = JSON.parse(configString)
if ... | /**
* Parse embedded OpenAPI document from HTML
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/resolve.ts#L135-L156 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | decodeHtmlEntities | function decodeHtmlEntities(text: string): string {
const entities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
} as const
return text.replace(
new RegExp(Object.keys(entities).join('|'), 'g'),
(match) => entities[match as keyof typeof entities],
)
} | /**
* Decode HTML entities in a string
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/resolve.ts#L161-L174 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | transformGitHubUrl | function transformGitHubUrl(url: string): string | undefined {
const githubRegex =
/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/
const match = url.match(githubRegex)
if (match) {
const [, owner, repo, branch, path] = match
return `https://raw.githubusercontent.com/${owner}/${repo}/... | /**
* Transform GitHub URLs to raw file URLs, preserving the branch information
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/scalar-app/src/main/resolve.ts#L179-L190 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | CodeBuilder.constructor | constructor({ indent, join } = {}) {
this.postProcessors = []
this.code = []
this.indentationCharacter = DEFAULT_INDENTATION_CHARACTER
this.lineJoin = DEFAULT_LINE_JOIN
/**
* Add given indentation level to given line of code
*/
this.indentLine = (line, indentationLevel = 0) => {
... | /**
* Helper object to format and aggragate lines of code.
* Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/snippetz/src/httpsnippet-lite/esm/helpers/code-builder.ts#L10-L62 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | concatValues | function concatValues(concatType, values, pretty, indentation, indentLevel) {
const currentIndent = indentation.repeat(indentLevel)
const closingBraceIndent = indentation.repeat(indentLevel - 1)
const join = pretty ? `,\n${currentIndent}` : ', '
const openingBrace = concatType === 'object' ? '{' : '['
const c... | // eslint-disable-next-line @typescript-eslint/ban-ts-comment | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/snippetz/src/httpsnippet-lite/esm/targets/python/helpers.ts#L7-L20 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | buildString | const buildString = (length, str) => str.repeat(length) | // eslint-disable-next-line @typescript-eslint/ban-ts-comment | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/snippetz/src/httpsnippet-lite/esm/targets/swift/helpers.ts#L9-L9 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | concatArray | const concatArray = (arr, pretty, indentation, indentLevel) => {
const currentIndent = buildString(indentLevel, indentation)
const closingBraceIndent = buildString(indentLevel - 1, indentation)
const join = pretty ? `,\n${currentIndent}` : ', '
if (pretty) {
return `[\n${currentIndent}${arr.join(join)}\n${c... | /**
* Create a string corresponding to a Dictionary or Array literal representation with pretty option and indentation.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/snippetz/src/httpsnippet-lite/esm/targets/swift/helpers.ts#L13-L21 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | signNumber | const signNumber = (operator: PrefixUnaryOperator, operand: UnaryExpression) =>
operator === SyntaxKind.MinusToken && isNumericLiteral(operand)
? -1 * Number(operand.text)
: operand | /** Add a sign to negative numbers */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/ts-to-openapi/src/node.ts#L26-L29 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | hasProvider | const hasProvider = (
params: UseCodeMirrorParameters,
): params is BaseParameters & {
content?: MaybeRefOrGetter<string | undefined>
provider: MaybeRefOrGetter<Extension>
} => 'provider' in params && !!toValue(params.provider) | /** Check if the hook has a provider. In provider mode we ignore the content variable */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useCodeMirror.ts#L90-L95 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | setCodeMirrorContent | const setCodeMirrorContent = (newValue = '') => {
if (!codeMirror.value) return
// No need to set the CodeMirror content if nothing has changed
if (codeMirror.value.state.doc.toString() === newValue) return
codeMirror.value.dispatch({
changes: {
from: 0,
to: codeMirror.value.stat... | /** Set the codemirror content value */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useCodeMirror.ts#L119-L138 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | mountCodeMirror | function mountCodeMirror() {
if (params.codeMirrorRef.value) {
const provider = hasProvider(params) ? toValue(params.provider) : null
const extensions = getCodeMirrorExtensions({
...extensionConfig.value,
provider,
})
codeMirror.value = new EditorView({
parent: param... | // Initializes CodeMirror. | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useCodeMirror.ts#L174-L190 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | getCodeMirrorExtensions | function getCodeMirrorExtensions({
onChange,
onBlur,
onFocus,
provider,
language,
classes = [],
readOnly = false,
lineNumbers = false,
withVariables = false,
forceFoldGutter = false,
disableEnter = false,
disableCloseBrackets = false,
disableTabIndent = false,
withoutTheme = false,
lint = ... | /** Generate the list of extension from parameters */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useCodeMirror.ts#L263-L493 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | updateDropdownPosition | function updateDropdownPosition() {
const cursorPos = getCursorPos()
requestAnimationFrame(() => {
const coords = getCoordsAtPos(cursorPos - query.value.length - 2)
if (coords) {
dropdownPosition.value = {
left: coords.left,
top: Math.max(coords.bottom),
}
}... | /** Updates position of the dropdown based on the current cursor position */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useDropdown.ts#L23-L34 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | handleDropdownSelect | function handleDropdownSelect(item: string) {
const formattedItem = `{{${item}}}`
const cursor = getCursorPos()
const from = Math.max(0, cursor - query.value.length - 2)
const to = cursor
codeMirror.value?.dispatch({
changes: { from, to, insert: formattedItem },
})
showDropdown.value =... | /** Inserts selected item at the current cursor position */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useDropdown.ts#L40-L49 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | updateDropdownVisibility | function updateDropdownVisibility() {
const cursor = getCursorPos()
const text = codeMirror.value?.state.doc.sliceString(0, cursor) || ''
const lastOpenBraceIndex = text.lastIndexOf('{{')
const lastCloseBraceIndex = text.lastIndexOf('}}')
if (lastOpenBraceIndex > lastCloseBraceIndex) {
query.v... | /** Updates dropdown visibility based on current cursor position */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-codemirror/src/hooks/useDropdown.ts#L52-L68 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | toggleColorMode | function toggleColorMode() {
// Update state
colorMode.value = darkLightMode.value === 'dark' ? 'light' : 'dark'
// Store in local storage
if (typeof window === 'undefined') return
window?.localStorage?.setItem('colorMode', colorMode.value)
} | /** Toggles the color mode between light and dark. */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-hooks/src/useColorMode/useColorMode.ts#L20-L27 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | setColorMode | function setColorMode(value: ColorMode) {
colorMode.value = value
if (typeof window === 'undefined') return
window?.localStorage?.setItem('colorMode', colorMode.value)
} | /** Sets the color mode to the specified value. */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-hooks/src/useColorMode/useColorMode.ts#L30-L34 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | getSystemModePreference | function getSystemModePreference(): DarkLightMode {
if (typeof window === 'undefined') return 'light'
if (typeof window?.matchMedia !== 'function') return 'dark'
return window?.matchMedia('(prefers-color-scheme: dark)')?.matches
? 'dark'
: 'light'
} | /** Gets the system mode preference. */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-hooks/src/useColorMode/useColorMode.ts#L37-L44 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | applyColorMode | function applyColorMode(mode: ColorMode): void {
if (typeof document === 'undefined' || typeof window === 'undefined') return
const classMode =
overrideColorMode ??
(mode === 'system' ? getSystemModePreference() : mode)
if (classMode === 'dark') {
document.body.classList.add('dark-mode')... | /** Applies the appropriate color mode class to the body. */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-hooks/src/useColorMode/useColorMode.ts#L62-L76 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | html | function html(strings: any, ...values: any) {
let str = ''
strings.forEach((string: any, i: number) => {
str += string + (values[i] || '')
})
return str
} | /** Mocked tagged template string to support lit-html syntax highlighting */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-tooltip/src/useTooltip.ts#L35-L41 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | css | function css(strings: any, ...values: any) {
let str = ''
strings.forEach((string: any, i: number) => {
str += string + (values[i] || '')
})
return str
} | /** Mocked tagged template string to support lit-html syntax highlighting */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-tooltip/src/useTooltip.ts#L44-L50 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | differentKeyboardShortcutsForMacOS | const differentKeyboardShortcutsForMacOS = (k: string) =>
k
.split('+')
.map((key) => {
if (key === 'mod') {
if (isMacOS()) {
return 'command'
} else {
return 'ctrl'
}
}
return key
})
.join('+') | // 'mod+b' -> 'command+b'/'control+b' (depending on the OS) | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-tooltip/src/useTooltip.ts#L55-L69 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | formattedKeyboardShortcuts | const formattedKeyboardShortcuts = (k: string) =>
differentKeyboardShortcutsForMacOS(k)
.split('+')
.map((key) => {
const keyMap: Record<string, string> = {
escape: 'ESC',
command: '⌘',
shift: '⇧',
ctrl: '⌃',
alt: '⌥',
}
// comma... | // 'command+b' -> '⌘B' | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/use-tooltip/src/useTooltip.ts#L72-L91 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | createObjectTree | function createObjectTree(data: Record<string, any>) {
let html = ''
for (const key in data) {
if (Object.hasOwn(data, key)) {
const value = data[key]
if (typeof value === 'object') {
html += `<li><strong>${key}:</strong> <ul>${createObjectTree(value)}</ul></li>`
} else {
htm... | /**
* Loop through object recursively and create a JSON string as formatted HTML
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/void-server/src/utils/createHtmlResponse.ts#L56-L72 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | transformFormData | function transformFormData(formData: Record<string, any>) {
const body: Record<string, any> = {}
for (const [key, value] of Object.entries(formData)) {
// String
if (typeof value === 'string') {
body[key] = value
continue
}
if (isFile(value)) {
body[key] = {
name: value?.... | /**
* Transform form data to a more readable format, including file information
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/void-server/src/utils/getBody.ts#L56-L107 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | isFile | function isFile(data: any) {
return (
typeof data === 'object' &&
data.name !== undefined &&
data.size !== undefined &&
data.type !== undefined &&
data.lastModified !== undefined
)
} | /**
* Check if the data is a file, just a polyfill for Node 18
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/void-server/src/utils/getBody.ts#L112-L120 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | findFolder | const findFolder = () => {
const possiblePaths = [
'../../packages/scalar-app',
'../packages/scalar-app',
'./packages/scalar-app',
]
for (const path of possiblePaths) {
try {
const absolutePath = join(process.cwd(), path)
if (statSync(absolutePath).isDirectory()) {
return abs... | // Helper function to find the frontend build | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/playwright/tests/electron.spec.ts#L8-L28 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | formatPackage | async function formatPackage(filepath: string) {
const file = await fs.readFile(filepath, 'utf-8').catch(() => null)
if (!file) {
return
}
const data = JSON.parse(file)
if (data.type !== 'module' && !NO_MODULE_PACKAGES.includes(data.name)) {
printColor(
'brightRed',
`Package ${data.name... | /** Format a package json file and validate scalar-org linting rules */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/scripts/format-package.ts#L75-L153 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | run | const run = async () => {
await formatDirectoryPackageFiles('packages')
await formatDirectoryPackageFiles('examples')
} | /**
* Lint all package.json files in the project. Sorts keys and checks critical fields like
* licenses and private.
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/scripts/format-package.ts#L167-L170 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | sortObjectKeys | function sortObjectKeys(obj: Record<string, any>) {
const sorted: Record<string, any> = {}
Object.keys(obj)
.sort()
.forEach((key) => {
sorted[key] = obj[key]
})
return sorted
} | // --------------------------------------------------------------------------- | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/scripts/format-package.ts#L178-L187 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | validatePackageScripts | function validatePackageScripts(
scripts: Record<string, string>,
packageName: string,
) {
if (!scripts) {
printColor('yellow', `WARNING: No scripts detected for ${packageName}`)
return
}
const required = ['lint:fix', 'lint:check', 'types:check']
required.forEach((scriptName) => {
const command... | /** Validate that required package scripts exists */ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/scripts/format-package.ts#L190-L212 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
scalar | github_2023 | scalar | typescript | updateSnapshots | async function updateSnapshots() {
const testResultsFolders = await fs.readdir(
path.join(__dirname, '../playwright/test-results'),
)
// filter out retry reports
const playwrightReports = testResultsFolders.filter(
(report) => !report.includes('retry'),
)
for await (const report of playwrightRepor... | /**
* This script checks the playwright test results
* for the CDN API Reference test
* and updates the snapshot files.
*
* The intended use is to be run in the test-cdn-jsdelvr.yml GitHub action workflow
*/ | https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/scripts/update-snapshots.ts#L18-L63 | 11d873d0be2b3fb82c1a1a8416425be8483014db |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.scheduleStabilizeWidgets | scheduleStabilizeWidgets(ms = 100) {
if (!this.schedulePromise) {
this.schedulePromise = new Promise((resolve) => {
setTimeout(() => {
this.schedulePromise = null;
this.doStablization();
resolve();
}, ms);
});
}
return this.schedulePromise;
} | /**
* Schedules a promise to run a stabilization, debouncing duplicate requests.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L69-L80 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.stabilizeInputsOutputs | private stabilizeInputsOutputs() : boolean {
let changed = false;
const hasEmptyInput = !this.inputs[this.inputs.length - 1]?.link;
if (!hasEmptyInput) {
this.addInput("", "*");
changed = true;
}
for (let index = this.inputs.length - 2; index >= 0; index--) {
const input = this.inp... | /**
* Ensures we have at least one empty input at the end, returns true if changes were made, or false
* if no changes were needed.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L86-L113 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.doStablization | private doStablization() {
if (!this.graph) {
return;
}
let dirty = false;
// When we add/remove widgets, litegraph is going to mess up the size, so we
// store it so we can retrieve it in computeSize. Hacky..
(this as any)._tempWidth = this.size[0];
dirty = this.stabilizeInputsOutpu... | /**
* Stabilizes the node's inputs and widgets.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L118-L139 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.handleLinkedNodesStabilization | handleLinkedNodesStabilization(linkedNodes: TLGraphNode[]) : boolean {
linkedNodes; // No-op, but makes overridding in VSCode cleaner.
throw new Error("handleLinkedNodesStabilization should be overridden.");
} | /**
* Handles stabilization of linked nodes. To be overridden. Should return true if changes were
* made, or false if no changes were needed.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L145-L148 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.removeWidget | override removeWidget(widgetOrSlot?: IWidget | number) {
(this as any)._tempWidth = this.size[0];
super.removeWidget(widgetOrSlot);
} | /**
* Guess this doesn't exist in Litegraph...
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L198-L201 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.onConnectOutput | override onConnectOutput(
outputIndex: number,
inputType: string | -1,
inputSlot: INodeInputSlot,
inputNode: TLGraphNode,
inputIndex: number,
): boolean {
let canConnect = true;
if (super.onConnectOutput) {
canConnect = super.onConnectOutput(outputIndex, inputType, inputSlot, inputNo... | /**
* When we connect our output, check our inputs and make sure we're not trying to connect a loop.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L227-L251 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseAnyInputConnectedNode.connectByTypeOutput | override connectByTypeOutput<T = any>(
slot: string | number,
sourceNode: TLGraphNode,
sourceSlotType: string,
optsIn: string,
): T | null {
const lastInput = this.inputs[this.inputs.length - 1];
if (!lastInput?.link && lastInput?.type === "*") {
var sourceSlot = sourceNode.findOutputSlo... | /**
* If something is dropped on us, just add it to the bottom. onConnectInput should already cancel
* if it's disallowed.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_any_input_connected_node.ts#L289-L301 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | RgthreeBaseServerNode.setupFromServerNodeData | async setupFromServerNodeData() {
const nodeData = (this.constructor as any).nodeData;
if (!nodeData) {
throw Error("No node data");
}
// Necessary for serialization so Comfy backend can check types.
// Serialized as `class_type`. See app.js#graphToPrompt
this.comfyClass = nodeData.name;
... | /**
* This takes the server data and builds out the inputs, outputs and widgets. It's similar to the
* ComfyNode constructor in registerNodes in ComfyUI's app.js, but is more stable and thus
* shouldn't break as often when it modifyies widgets and types.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_node.ts#L325-L403 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | BaseCollectorNode.onConnectInput | override onConnectInput(
inputIndex: number,
outputType: string | -1,
outputSlot: INodeOutputSlot,
outputNode: LGraphNode,
outputIndex: number,
): boolean {
let canConnect = super.onConnectInput(
inputIndex,
outputType,
outputSlot,
outputNode,
outputIndex,
);
... | /**
* When we connect an input, check to see if it's already connected and cancel it.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_node_collector.ts#L39-L97 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | PowerPrompt.onNodeConnectionsChange | onNodeConnectionsChange(
_type: number,
_slotIndex: number,
_isConnected: boolean,
_linkInfo: LLink,
_ioSlot: INodeOutputSlot | INodeInputSlot,
) {
this.stabilizeInputsOutputs();
} | /**
* Cleans up optional out puts when we don't have the optional input. Purely a vanity function.
*/ | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_power_prompt.ts#L135-L143 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | PowerPrompt.addAndHandleKeyboardLoraEditWeight | addAndHandleKeyboardLoraEditWeight() {
this.promptEl.addEventListener("keydown", (event: KeyboardEvent) => {
// If we're not doing a ctrl/cmd + arrow key, then bail.
if (!(event.key === "ArrowUp" || event.key === "ArrowDown")) return;
if (!event.ctrlKey && !event.metaKey) return;
// Unfortun... | /**
* Adds a keydown event listener to our prompt so we can see if we're using the
* ctrl/cmd + up/down arrows shortcut. This kind of competes with the core extension
* "Comfy.EditAttention" but since that only handles parenthesis and listens on window, we should
* be able to intercept and cancel the bubble... | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_power_prompt.ts#L297-L347 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
rgthree-comfy | github_2023 | rgthree | typescript | PowerPrompt.patchNodeRefresh | patchNodeRefresh() {
this.boundOnFreshNodeDefs = this.onFreshNodeDefs.bind(this);
api.addEventListener("fresh-node-defs", this.boundOnFreshNodeDefs as EventListener);
const oldNodeRemoved = this.node.onRemoved;
this.node.onRemoved = () => {
oldNodeRemoved?.call(this.node);
api.removeEventLis... | /**
* Patches over api.getNodeDefs in comfy's api.js to fire a custom event that we can listen to
* here and manually refresh our combos when a request comes in to fetch the node data; which
* only happens once at startup (but before custom nodes js runs), and then after clicking
* the "Refresh" button in t... | https://github.com/rgthree/rgthree-comfy/blob/5d771b8b56a343c24a26e8cea1f0c87c3d58102f/src_web/comfyui/base_power_prompt.ts#L355-L363 | 5d771b8b56a343c24a26e8cea1f0c87c3d58102f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.